Example #1
0
int init()
{
    SDL_DisplayMode mode;

    // Initialize SDL itself
    printf("SDL_Init()\n");
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0)
    {
        printf("SDL_Init error: %s\n", SDL_GetError());

        return 0;
    }

    // Get the current display mode
    printf("SDL_GetCurrentDisplayMode()\n");
    if(SDL_GetCurrentDisplayMode( 0, &mode ) != 0)
    {
        printf("SDL_GetCurrentDisplayMode error: %s\n", SDL_GetError());

        SDL_Quit();

        return 0;
    }

    rect_screen.w = mode.w;
    rect_screen.h = mode.h;

    //Create a new full-screen window
    printf("SDL_CreateWindow()\n");
    window = SDL_CreateWindow("Multiplatform Base Application",
                              SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              rect_screen.w,
                              rect_screen.h,
                              SDL_WINDOW_SHOWN);
    if(!window)
    {
        printf("SDL_CreateWindow error: %s\n", SDL_GetError());

        SDL_Quit();

        return 0;
    }

    // Create a renderer
    printf("SDL_CreateRenderer()\n");
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if(!renderer)
    {
        printf("SDL_CreateRenderer error: %s\n", SDL_GetError());

        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    // Init audio
    printf("Mix_Init()\n");
    if(Mix_Init(MIX_INIT_OGG) != MIX_INIT_OGG)
    {
        printf("Mix_Init error: %s\n", Mix_GetError());

        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    // Open audio device
    printf("Mix_OpenAudio()\n");
    if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) != 0)
    {
        printf("Mix_OpenAudio error: %s\n", Mix_GetError());

        Mix_Quit();
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();

        return 0;
    }

    return 1;
}
Example #2
0
/* should just simplify all this:                                      */
void LibInit(Uint32 lib_flags)
{
  LOG( "LibInit():\n-About to init SDL Library\n" );

  /* Initialize video: */
  if (SDL_Init(SDL_INIT_VIDEO) < 0)
  {
    fprintf(stderr, "Couldn't initialize SDL: %s\n",
    SDL_GetError());
    exit(2);
  }
  /* Initialize audio if desired: */
  if (settings.sys_sound)
  {
    if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
    {
      fprintf(stderr, "Couldn't initialize SDL Sound: %s\n",
              SDL_GetError());
      settings.sys_sound = 0;
    }
    else
      LOG("SDL_InitSubSystem(SDL_INIT_AUDIO) succeeded\n");
  }

// atexit(SDL_Quit); // fire and forget... 

  LOG( "-SDL Library init'd successfully\n" );

  DEBUGCODE
  { fprintf(stderr, "settings.sys_sound = %d\n", settings.sys_sound); }

  /* FIXME should read settings before we do this: */ 
  if (settings.sys_sound) //can be turned off with "--nosound" runtime flag
  {
    int initted = 1;

    /* For SDL_mixer 1.2.10 and later, we must call Mix_Init() before any */
    /* other SDL_mixer functions. We can see what types of audio files    */
    /* are supported at this time (ogg and mod are required):             */

#ifdef HAVE_MIX_INIT
    int flags = MIX_INIT_OGG | MIX_INIT_MP3 | MIX_INIT_MOD | MIX_INIT_FLAC;
    initted = Mix_Init(flags);

    /* Just give warnings if MP3 or FLAC not supported: */
    if((initted & MIX_INIT_MP3) != MIX_INIT_MP3)
      LOG("NOTE - MP3 playback not supported\n");
    if((initted & MIX_INIT_FLAC) != MIX_INIT_FLAC)
      LOG("NOTE - MP3 playback not supported\n");

    /* We must have Ogg and Mod support to have sound: */
    if((initted & (MIX_INIT_OGG | MIX_INIT_MOD)) != (MIX_INIT_OGG | MIX_INIT_MOD))
    {
      fprintf(stderr, "Mix_Init: Failed to init required ogg and mod support!\n");
      fprintf(stderr, "Mix_Init: %s\n", Mix_GetError());
      settings.sys_sound = 0;
      initted = 0;
    }
    else
      LOG("Mix_Init() succeeded\n");
#endif

    DOUT(initted);

    /* If Mix_Init() succeeded (or wasn't required), set audio parameters: */
    if(initted)
    {
      LOG("About to call Mix_OpenAudio():\n");
//    if (Mix_OpenAudio(22050, AUDIO_S16, 1, 2048) == -1)
      if(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 1, 2048) ==
		      -1)
      {
        fprintf(stderr, "Warning: Mix_OpenAudio() failed\n - Reasons: %s\n", SDL_GetError());
        settings.sys_sound = 0;
      }
      else
        LOG("Mix_OpenAudio() successful\n");
    }
  }

  LOG( "-about to init SDL text library (SDL_ttf or SDL_Pango\n" );

  if (!Setup_SDL_Text())
  {
    fprintf( stderr, "Couldn't initialize desired SDL text library\n" );
    exit(2);
  }
//	atexit(TTF_Quit);

  LOG( "LibInit():END\n" );
}
Example #3
0
/**
 *  Läd ein Musikstück.
 *
 *  @param[in] type Typ der Daten
 *  @param[in] data Datenblock
 *  @param[in] size Größe des Datenblocks
 *
 *  @return Sounddeskriptor bei Erfolg, @p NULL bei Fehler
 *
 *  @author FloSoft
 */
Sound* AudioSDL::LoadMusic(unsigned int data_type, unsigned char* data, unsigned long size)
{
    SoundSDL_Music* sd = new SoundSDL_Music;

    char file[512];
    if (!tempname(file, 512))
        return(NULL);

    switch(data_type)
    {
        default:
            return(NULL);

        case AudioDriver::AD_MIDI:
        {
            strncat(file, ".mid", 512);
        } break;

        case AudioDriver::AD_WAVE:
        {
            strncat(file, ".wav", 512);
        } break;

        case AudioDriver::AD_OTHER:
        {
            const char* header = (const char*)data;
            if(strncmp(header, "OggS", 4) == 0)
                strncat(file, ".ogg", 512);
            else if (strncmp(header, "ID3", 3) == 0 || ((unsigned char)header[0] == 0xFF && (unsigned char)header[1] == 0xFB) )
                strncat(file, ".mp3", 512);
            else
                strncat(file, ".tmp", 512);
        } break;

        /// @todo Alle Formate die SDL mit LoadMUS laden kann angeben
    }

    FILE* dat = fopen(file, "wb");
    if (!dat)
        return(NULL);

    if (fwrite(data, 1, size, dat) != size)
        return(NULL);

    fclose(dat);

    sd->music = Mix_LoadMUS(file);

    unlink(file);

    if(sd->music == NULL)
    {
        fprintf(stderr, "%s\n", Mix_GetError());
        delete sd;
        return(NULL);
    }

    sd->SetNr((int)sounds.size());
    sounds.push_back(sd);

    return sd;
}
Example #4
0
int main(int argc, char *argv[])
{
	int audio_rate;
	Uint16 audio_format;
	int audio_channels;
	int loops = 0;
	int i;
	int reverse_stereo = 0;
	int reverse_sample = 0;

	setbuf(stdout, NULL);    /* rcg06132001 for debugging purposes. */
	setbuf(stderr, NULL);    /* rcg06192001 for debugging purposes, too. */
	output_test_warnings();

	/* Initialize variables */
	audio_rate = MIX_DEFAULT_FREQUENCY;
	audio_format = MIX_DEFAULT_FORMAT;
	audio_channels = 2;

	/* Check command line usage */
	for ( i=1; argv[i] && (*argv[i] == '-'); ++i ) {
		if ( (strcmp(argv[i], "-r") == 0) && argv[i+1] ) {
			++i;
			audio_rate = atoi(argv[i]);
		} else
		if ( strcmp(argv[i], "-m") == 0 ) {
			audio_channels = 1;
		} else
		if ( (strcmp(argv[i], "-c") == 0) && argv[i+1] ) {
			++i;
			audio_channels = atoi(argv[i]);
		} else
		if ( strcmp(argv[i], "-l") == 0 ) {
			loops = -1;
		} else
		if ( strcmp(argv[i], "-8") == 0 ) {
			audio_format = AUDIO_U8;
		} else
		if ( strcmp(argv[i], "-f") == 0 ) { /* rcg06122001 flip stereo */
			reverse_stereo = 1;
		} else
		if ( strcmp(argv[i], "-F") == 0 ) { /* rcg06172001 flip sample */
			reverse_sample = 1;
		} else {
			Usage(argv[0]);
			return(1);
		}
	}
	if ( ! argv[i] ) {
		Usage(argv[0]);
		return(1);
	}

	/* Initialize the SDL library */
	if ( SDL_Init(SDL_INIT_AUDIO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(255);
	}
	signal(SIGINT, CleanUp);
	signal(SIGTERM, CleanUp);

	/* Open the audio device */
	if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, 4096) < 0) {
		fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
		CleanUp(2);
	} else {
		Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
		printf("Opened audio at %d Hz %d bit %s", audio_rate,
			(audio_format&0xFF),
			(audio_channels > 2) ? "surround" :
			(audio_channels > 1) ? "stereo" : "mono");
		if ( loops ) {
		  printf(" (looping)\n");
		} else {
		  putchar('\n');
		}
	}
	audio_open = 1;

#if (defined TEST_MIX_VERSIONS)
    test_versions();
#endif

	/* Load the requested wave file */
	wave = Mix_LoadWAV(argv[i]);
	if ( wave == NULL ) {
		fprintf(stderr, "Couldn't load %s: %s\n",
						argv[i], SDL_GetError());
		CleanUp(2);
	}

	if (reverse_sample) {
		flip_sample(wave);
	}

#ifdef TEST_MIX_CHANNELFINISHED  /* rcg06072001 */
	Mix_ChannelFinished(channel_complete_callback);
#endif

	if ( (!Mix_SetReverseStereo(MIX_CHANNEL_POST, reverse_stereo)) &&
		 (reverse_stereo) )
	{
		printf("Failed to set up reverse stereo effect!\n");
		printf("Reason: [%s].\n", Mix_GetError());
	}

	/* Play and then exit */
	Mix_PlayChannel(0, wave, loops);

	while (still_playing()) {

#if (defined TEST_MIX_PANNING)  /* rcg06132001 */
		do_panning_update();
#endif

#if (defined TEST_MIX_DISTANCE) /* rcg06192001 */
		do_distance_update();
#endif

#if (defined TEST_MIX_POSITION) /* rcg06202001 */
		do_position_update();
#endif

		SDL_Delay(1);

	} /* while still_playing() loop... */

	CleanUp(0);

	/* Not reached, but fixes compiler warnings */
	return 0;
}
Example #5
0
//the massive main function
int main(int argc, char* args[]) // Gets command line input
{
	bool quit = false, playing = true, falling = true, held = false, paused = false, cheating = false; // All our miscellaneous bools to keep track of game states.
	
	int level = 0, lines = 0, score = 0, choice = 0, cheatseq = 0;
	
	Scores scores("gfx"); // Opens the uber camoflaged gfx file for getting highscores. Tricksy, eh?
	
	Uint32 start = 0; // A REALLY big int for keeping track of time
	
	srand(SDL_GetTicks()); // seeding the random... seed
	
	if( init() == false ) // Initialize SDL
	{
		cout << "Init fail" << endl;
		return 1; //ERR !!!!
	}
	
	block = load_image( "blocks.png" ); // load blocks
	
	if(block == NULL) 
	{
		cout << "Error loading blocks.png" << endl;
		return 1; //ERR!
	}
	
	back = load_image( "back.png" ); // load background
	
	if(back == NULL)
	{
		cout << "Error loading back.png" << endl;
		return 1; //ERR!
	}
	
	smallblock = load_image( "smallblocks.png" ); // small blocks for next and hold
	
	if(smallblock == NULL)
	{
		cout << "Error loading smallblocks.png" << endl;
		return 1; //ERR!
	}
	
	title = load_image( "title.png" ); // title
	
	if(title == NULL)
	{
		cout << "Error loading title.png" << endl;
		return 1; //ERR!
	}
	
	cursor = load_image( "cursor.png" ); // cursor in menu
	
	if(cursor == NULL)
	{
		cout << "Error loading cursor.png" << endl;
		return 1; //ERR!
	}
	
	font = TTF_OpenFont("ProggyClean.ttf", FONTSIZE); // our font
	
	if(font == NULL)
	{
		cout << "Error loading ProggyClean.ttf" << endl;
		return 1; //Yup. Didn't load.
	}
	
	effect = Mix_LoadWAV( "pause.wav" ); // dee doo sound
	
	if(effect == NULL)
	{
		cout << "Mix_LoadWAV: " << Mix_GetError() << endl;
	}
	
	while(playing) // while the user hasn't quit
	{
		score = 0;
		quit = false;
		Mix_FadeOutMusic(100); // fades out the music (if playing) for menu.
		
		Mix_FreeMusic(music); // gets rid of any music we might have loaded
		
		if(XM == true) // load title music
		{
			music = Mix_LoadMUS("title.xm");
		}
		else
		{
			music = Mix_LoadMUS("title.mp3");
		}
		
		if(!music)
		{
	   		cout << "Mix_LoadMUS(\"title.mp3\"): %s\n" << Mix_GetError() << endl;
	   		// music didn't load...
		}
		
		Mix_PlayMusic(music, -1); // play it til the user can't stand it no mo'.

		for(int i = 600; i>=100; i--) // slowly bring up the title
		{
			while( SDL_PollEvent( &event ) ) // gets any recent events (mouse, keyboard, whatev)
			{
				if( event.type == SDL_QUIT ) // X button
				{
					i = 100;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) //escape
				{
					i = 100; // brings the title screen instantly
				}
			}
			SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) ); // fill screen black
			apply_surface( 200, i, title, screen ); // apply title
			if( SDL_Flip( screen ) == -1 ) // hand *screen to video card
			{
				return 1; //ERRRRRRR !!
			}
			SDL_Delay(2); // slows it down a wee bit.
		}
		
		apply_surface( 325, 402 + choice * 50, cursor, screen ); // display cursor
		
		numbers = TTF_RenderText_Blended(font, "START", fontColor); // start
		apply_surface( 350, 400, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor); // high scores
		apply_surface( 350, 450, numbers, screen );
		
		numbers = TTF_RenderText_Blended(font, "EXIT", fontColor); // exit
		apply_surface( 350, 500, numbers, screen );
		
		if( SDL_Flip( screen ) == -1 )
		{
			return 1; //ERRRRRRR !!
		}
		
		paused = true; //pause for menu
		while(paused && !quit)
		{
			while( SDL_PollEvent( &event ) ) // wait for events
			{
				if( event.type == SDL_QUIT )
				{
					paused = false;
					playing = false;
					quit = true;
				}
				else if( event.type == SDL_KEYDOWN )
				{
					switch(event.key.keysym.sym)
					{
						case SDLK_ESCAPE:
							paused = false;
							quit = true;
							playing = false;
							break;
						case SDLK_RETURN:
							switch(choice)
							{
								case 0:
									paused = false;
									break;
								case 1:
									scores.display();
									break;
								case 2:
									paused = false;
									quit = true;
									playing = false;
									break;
							}
							break;
						case SDLK_DOWN: // down, move cursor down
							Mix_PlayChannel(-1, effect, 0); // dee doo sound
							if(choice < 2)
							{
								choice++;
							}
							else
							{
								choice = 0;
							}
							break;
						case SDLK_UP: // up, move cursor up
							Mix_PlayChannel(-1, effect, 0); // see above
							if(choice > 0)
							{
								choice--;
							}
							else
							{
								choice = 2;
							}
							break;
					}
					SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0x00, 0x00, 0x00 ) );
					
					apply_surface( 200, 100, title, screen );
					apply_surface( 325, 402 + choice * 50, cursor, screen );
							
					numbers = TTF_RenderText_Blended(font, "START", fontColor);
					apply_surface( 350, 400, numbers, screen );
					
					numbers = TTF_RenderText_Blended(font, "HIGH SCORES", fontColor);
					apply_surface( 350, 450, numbers, screen );
		
					numbers = TTF_RenderText_Blended(font, "EXIT", fontColor);
					apply_surface( 350, 500, numbers, screen );
		
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
				}
			}
		}
		
		if(!quit) // if the user didn't quit
		{		
			Mix_FadeOutMusic(100); //fade out title music
			
			Mix_FreeMusic(music); //free it
			
			if(XM == true) // change to game music
			{
				music = Mix_LoadMUS("music.xm");
			}
			else
			{
				music = Mix_LoadMUS("music.mp3");
			}
		
			if(!music)
			{
	   			cout << "Mix_LoadMUS(\"music.mp3\"): %s\n" << Mix_GetError() << endl;
	   			// music didn't load...
			}
			
			Mix_PlayMusic(music, -1);
		
			SDL_Delay(1500); // wait for ba-ding! to finish
		}
		
		Tile *tile = NULL, *next = NULL, *next2 = NULL, *next3 = NULL, *hold = NULL, *blank = NULL; //current tile, next tiles 1 2 3, hold, and the tile used for switching hold
		
		setclips(); // set the clip boxes for tiles
		
		clearfield(); // initialize the field

		next = new Tile(); // inits new tiles
		next2 = new Tile();
		next3 = new Tile();
		
		while(!quit)
		{
			SDL_Delay(50); // wait a bit for the next block to drop
			tile = next; // next to current
			next = next2; // move nexts
			next2 = next3;
			next3 = new Tile(); // new next 3
			if(!tile->check(0, 0)) // if the tile is colliding from the get go
			{
				tile->show();
				if( SDL_Flip( screen ) == -1 )
				{
					return 1; //ERRRRRRR !!
				}
				gameOver(); // THEN YOU LOSE! HA!
				scores.checkScore(score); // Did you get a high score?
				scores.save(); // save the high score file
				scores.display(); // display the current high scores
				quit = true;
			}
			falling = true;
			
			while(falling && !quit) // the there a lot of !quits from now on so it goes straight back to the menu
			{
				apply_surface( 0, 0, back, screen ); // background
				tile->show(); // show the current tile
				if(hold != NULL)
				{
					hold->disp(27,78); // display hold
				}
				next->disp(390, 78); // display nexts
				next2->disp(390, 158);
				next3->disp(390, 238);
				start = SDL_GetTicks(); // start the timer
				while( falling && SDL_GetTicks() - start < (1/((static_cast<double>(level)/25) + 1))*(SPEED - MINSPEED)+MINSPEED) // spiffy formula I took way to long to make for speeding up
				{
					while( SDL_PollEvent( &event ) ) // get events
					{
						if( event.type == SDL_QUIT ) // quit immediatly
						{
							clean();
							exit(0);
							playing = false;
						}
						else if( event.type == SDL_KEYDOWN ) // was a key pressed?
						{
							switch( event.key.keysym.sym ) // what key was pressed?
							{
								case SDLK_LEFT: // move left
									tile->check(-1, 0);
									break;
								case SDLK_RIGHT: // move right
									tile->check(1, 0);
									break;
								case SDLK_z: // rotate CCW
									tile->rotate(CC);
									break;
								case SDLK_x: // rotate CW
									tile->rotate(CW);
									break;
								case SDLK_DOWN: // soft drop
									if(!tile->check(0,1)) // if it hits something as a result of dropping once
									{
	                                    falling = false; // apply the tile
	                                }
	                                start = SDL_GetTicks(); // reset the timer
									break;
								case SDLK_UP: // hard drop
									while(tile->check(0,1)) // move it down til it cant any more
									{
										score += 2 * (level + 1); // you get points for being so daring!
									}
									start -= 1000; //Lock that sucka!
									break;
								case SDLK_n: // this is the cheat key. But you have to be cheating to use it ;D
									if(cheating)
									{
										delete tile; // basically just gives you new tiles
										tile = new Tile();
									}
									break;
								case SDLK_ESCAPE: // back to main menu
									quit = true;
									break;
								case SDLK_k: //SUPER SECRET KYLE-MODE!
									block = load_image( "kyles.png" );
									back = load_image( "kyleback.png" );
									smallblock = load_image("smallkyles.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("rawk.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_o: // back to original
									block = load_image( "blocks.png" );
									back = load_image( "back.png" );
									smallblock = load_image("smallblocks.png");
									Mix_HaltMusic();
									music = Mix_LoadMUS("music.mp3");
									Mix_PlayMusic(music, -1);
									break;
								case SDLK_c: // hold
									if(hold && !held) // if there is something held and you haven't held yet this turn
									{
										blank = hold; // switch current and held
										hold = tile;
										tile = blank;
									}
									else if(!hold) // if you've never held
									{
										hold = tile; // hold current and make more tiles
										tile = next;
										next = next2;
										next2 = next3;
										next3 = new Tile();
									}
									hold->reset(); // reset the x and y values of the tile
									held = true;
									break;
								case SDLK_p: // pause
									paused = true;
									Mix_PauseMusic(); // pause music
									Mix_PlayChannel(-1, effect, 0); // play the dee doo
									apply_surface( 0, 0, back, screen ); // cover the tiles
									numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // but keep the scores
									apply_surface( 550, 50, numbers, screen );
									numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
									apply_surface( 550, 120, numbers, screen );
									if( SDL_Flip( screen ) == -1 ) // display screen
									{
										return 1; //ERRRRRRR !!
									}
									while(paused)
									{
										while(SDL_PollEvent( &event )) // get events
										{
											if( event.type == SDL_QUIT ) // quit immediatly
											{
												quit = true;
												paused = false;
												playing = false;
											}
											else if( event.type == SDL_KEYDOWN ) // key down?
											{
												switch( event.key.keysym.sym ) // what key?
												{
													case SDLK_ESCAPE: // unpause
													case SDLK_p: // unpause
														paused = false;
														break;
													case SDLK_UP: // CHEATING!! WOO!!! UP UP DOWN DOWN LEFT RIGHT LEFT RIGHT A B. <3 CONTRA.
														if(cheatseq == 0 || cheatseq == 1)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0; // if you screwed up
														}
														break;
													case SDLK_DOWN:
														if(cheatseq == 2 || cheatseq == 3)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_LEFT:
														if(cheatseq == 4 || cheatseq == 6)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_RIGHT:
														if(cheatseq == 5 || cheatseq == 7)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_z:
														if(cheatseq == 8)
														{
															cheatseq++;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													case SDLK_x:
														if(cheatseq == 9)
														{
															Mix_PlayChannel(-1, effect, 0);
															cheating = true;
														}
														else
														{
															cheatseq = 0;
														}
														break;
													default:
														cheatseq = 0;
														break;
												}
											}
										}
									}
									cheatseq = 0; // If you screwed up the cheat sequence
									Mix_ResumeMusic(); // play that funky music
									break;
							}
							apply_surface( 0, 0, back, screen ); // put the background up
							screen << *tile; //There. Overloading. Huzzah.
							if(hold != NULL) // display hold
							{
								hold->disp(27,78);
							}
							next->disp(390, 78); // display all the nexts
							next2->disp(390, 158);
							next3->disp(390, 238);
							numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); //display scores
							apply_surface( 550, 50, numbers, screen );
							numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor); //Pretty sweet you can use all the sweet string functions with a function that returns a string =D
							apply_surface( 550, 120, numbers, screen );
							if( SDL_Flip( screen ) == -1 ) // show screen
							{
								return 1; //ERRRRRRR !!
							}
						}
					}
					numbers = TTF_RenderText_Solid(font, intToStr(score).c_str(), fontColor); // display scores
					apply_surface( 550, 50, numbers, screen );
					numbers = TTF_RenderText_Solid(font, intToStr(level).c_str(), fontColor);
					apply_surface( 550, 120, numbers, screen );
					if( SDL_Flip( screen ) == -1 )
					{
						return 1; //ERRRRRRR !!
					}
					SDL_Delay(1);
				}
				if(tile->check(0, 1) == 0) // if it can't fall any more
				{
					falling = false; // stop falling
				}
			}
			tile->apply(); // apply it to the pile
			held = false; // you can hold again!
			score += (level+1)*checklines(lines); // check the lines and score accordingly
			level = lines/10; // level up?
			delete tile; // delete the current tile so we don't get yelled at
		}
		delete next; // delete all the other tiles if you lost
		delete next2;
		delete next3;
		delete hold;
	}
	clean(); // uninitialize SDL and everything
	return 0; // RETURN THAT ZERO, BABY.
} // Fin
Example #6
0
int main(int argc, char** argv) {
	srand(1707801);

	Server* server = NULL;
	Client* lan = NULL;
	if (argc > 1) {
		try {
			if (argv[1][0] == 's') {
				server = new Server();
				server->correr();
			}
		} catch ( ConnectionProblem &e ) { return -1; }
	}

	if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
		return -1;
	} else if (server == NULL) {
		TTF_Init();

		//Inicializo el Mixer:
		if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0){
			printf ("Error al inicializar SDL_mixer. Error: %s\n", Mix_GetError());
			SDL_Quit();
			IMG_Quit();
			TTF_Quit();
			return -1;
		}

		EstadoFinVentana estado = OK;
		VentanaEspera *ventanaEspera = NULL;
		ObjetivoEscenario modoDeJuego = MODO_DEFAULT;

		if (argc > 1) {
			try {
				if (argv[1][0] == 'c') {
					//ventanaEspera = new VentanaEspera(std::pair<int,int>(640,800)); // hardcode sabroso
					//estado = ventanaEspera->run();

					lan = new Client();	// Se conecta.
					modoDeJuego = Proxy::clienteEsperarComienzoYModoDeJuego(lan); // Espera comienzo de juego.
				}
			} catch ( ConnectionProblem &e ) { return -1; }
		}

		Controller *controller = new Controller(lan, modoDeJuego);	// Carga el juego (modelo)

		delete ventanaEspera;

		if (estado == OK){

			if (estado == OK){
				VentanaJuego *ventanaJuego = new VentanaJuego(controller);	// Carga y mantiene la vista.
				estado = ventanaJuego->run();
				delete ventanaJuego;
			}

			// Meter una ventana de resultado de la partida (GANADO - PERDIDO)
		}

		delete controller;
		Mix_Quit();
		TTF_Quit();
		IMG_Quit();
		SDL_Quit();
	}
	delete server;
	delete lan;

	return 0;
}
Example #7
0
int main(void)
{
//    int good = 0;
//    int numeroMap = 0;
//    do{
//        printf("Quelle map?\n");
//        printf("1 - Original\n");
//        printf("2 - Hard\n");
//        printf("3 - Lol\n");
//        printf("4 - Rez De chaussez Aile Sud Telecom Nancy\n");
//        scanf("%d", &numeroMap);
//        switch(numeroMap){
//            case 1:
//                loadMap("../projec/map/original.map");
//                good = 1;
//                break;
//            case 2:
//                loadMap("../projec/map/hard.map");
//                good = 1;
//                break;

//            case 3:
//                loadMap("../projec/map/maplol.map");
//                good = 1;
//                break;
//            case 4:
//                loadMap("../projec/map/rdastn.map");
//                good = 1;
//                break;

//            case 42:
//                loadMap("../projec/map/rdastn.map");
//                good = 1;
//                setQ();
//                break;
//        }
//    }while(!good);
    //Create SDL objects
    SDL_Window *window = 0;
    SDL_Event event;
    SDL_Renderer *renderer = 0;
    int terminate = 0;

    //Initialise SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0){
        printf("Error with SDL : %s\n", SDL_GetError());
        SDL_Quit();
        return EXIT_FAILURE;
    }

    window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 544, 344, SDL_WINDOW_SHOWN);
    terminate = 0;
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_Surface *menu = IMG_Load("../projec/texture/menu/menu.jpg");

    SDL_Texture *menuTexture = SDL_CreateTextureFromSurface(renderer, menu);

    SDL_FreeSurface(menu);
    SDL_RenderClear(renderer);
    int x, y;
    while(!terminate){
        SDL_Rect dest = {0, 0, 544, 344};
        SDL_RenderCopy(renderer, menuTexture, NULL, &dest);
        SDL_RenderPresent(renderer);
        SDL_WaitEvent(&event);
        switch(event.type){
            case SDL_MOUSEBUTTONDOWN:
                x = event.motion.x;
                y = event.motion.y;
                if(x >= 57 && x <= (57+54) && y >=  94 && y <= (94 + 74)){
                    loadMap("../projec/map/original.map");
                    terminate = 1;
                }
                if(x >= 124 && x <= (124+53) && y >=  208 && y <= (208 + 73)){
                    loadMap("../projec/map/hard.map");
                    terminate = 1;
                }
                if(x >= 221 && x <= (221+59) && y >=  95 && y <= (95 + 80)){
                    loadMap("../projec/map/maplol.map");
                    terminate = 1;
                }
                if(x >= 311 && x <= (311+63) && y >=  208 && y <= (208 + 76)){
                    loadMap("../projec/map/rdastn.map");
                    terminate = 1;
                }
                if(x >= 350 && x <= (350+124) && y >=  73 && y <= (73 + 109)){
                    loadMap("../projec/map/rdastn.map");
                    terminate = 1;
                    setQ();
                }
                break;
        }

        SDL_Delay(1000 / FPS);
    }
    SDL_DestroyTexture(menuTexture);

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    //Search the pacman on the map and create him
    Pacman *pacman = getPacmanInstance();
    unsigned int initialX = pacman->x;
    unsigned int initialY = pacman->y;
    Map *map = getMapInstance();
    //If the pacman is not found
    if(!pacman){
        printf("Pacman not found on map\n");
        freeMap(map);
        exit(EXIT_FAILURE);
    }
    printf("Pacman found !\n");

    Ghost *clyde = searchAndCreateGhost(CLYDE);
    if(!clyde){
        printf("Clyde not found on map\n");
        freeMap(map);
        exit(EXIT_FAILURE);
    }
    printf("Clyde found !\n");

    Ghost *blinky = searchAndCreateGhost(BLINKY);
    if(!blinky){
        printf("Blinky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        exit(EXIT_FAILURE);
    }
    printf("Blinky found !\n");

    Ghost *inky = searchAndCreateGhost(INKY);
    if(!inky){
        printf("Inky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        freeGhost(blinky);
        exit(EXIT_FAILURE);
    }
    printf("Inky found !\n");

    Ghost *pinky = searchAndCreateGhost(PINKY);
    if(!pinky){
        printf("Pinky not found on map\n");
        freeMap(map);
        freeGhost(clyde);
        freeGhost(blinky);
        freeGhost(inky);
        exit(EXIT_FAILURE);
    }
    printf("Pinky found !\n");
    printf("SDL initialisation\n");



    if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096) == -1){
        printf("%s", Mix_GetError());
    }

    Mix_Music *music = NULL;
    music = Mix_LoadMUS("../projec/pacman.wav");
    if(!music){
        printf("Erreur de chargement de la musique %s \n", Mix_GetError());
    }else{
        Mix_VolumeMusic(MIX_MAX_VOLUME);
        Mix_PlayMusic(music, -1);
    }

    if(TTF_Init() == -1){
        printf("Error during TTF initialization : %s\n", TTF_GetError());
    }

    TTF_Font *police = NULL;

    police = TTF_OpenFont("../projec/monof.ttf", 65);
    if(!police){
        printf("Error during font load : %s\n", TTF_GetError());
    }
    SDL_Color color = { 255, 255, 255, 255};



    //Create the window
    window = SDL_CreateWindow("Pacman", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, TILE_SIZE * map->col, TILE_SIZE * map->row + TILE_SIZE, SDL_WINDOW_SHOWN);

    //If there is an error
    if(window == 0){
        printf("Error during window creation : %s \n", SDL_GetError());
        SDL_Quit();
        freeMap(map);
        return EXIT_FAILURE;
    }
    int j;
    printf("SDL init success\n");
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    //NEED gerer erreurs

    loadTextures(renderer);

    SDL_Surface *score = TTF_RenderText_Solid(police, "Score : ", color);
    SDL_Texture *scoreT = SDL_CreateTextureFromSurface(renderer, score);
    SDL_FreeSurface(score);
    char scoreString[15];

    SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20};
    SDL_RenderCopy(renderer, scoreT, NULL, &dest);
    SDL_Surface *scoreN;
    SDL_Texture *scoreTN;
    int open = 0;
    int konami[10] = {0,0,0,0,0,0,0,0,0,0};
    //Infinite loop until we want to stop the game
    terminate = 0;
    while(!terminate){
        SDL_Rect dest2 = {map->row * TILE_SIZE / 6, map->row * TILE_SIZE, map->row * TILE_SIZE / 15, 20};
        sprintf(scoreString, "%d", pacman->point);
        scoreN = TTF_RenderText_Solid(police, scoreString, color);
        scoreTN = SDL_CreateTextureFromSurface(renderer, score);
        renderMap(renderer);
        open = renderPacman(open, renderer);
        renderClyde(clyde, renderer);
        renderBlinky(blinky, renderer);
        renderPinky(pinky, renderer);
        renderInky(inky, renderer);

        changeDirectionGhost(blinky);
        changeDirectionGhost(clyde);
        changeDirectionGhost(inky);
        changeDirectionGhost(pinky);
        SDL_Rect dest = {0, map->row * TILE_SIZE , map->row * TILE_SIZE / 6, 20};
        SDL_RenderCopy(renderer, scoreT, NULL, &dest);



        SDL_RenderCopy(renderer, scoreTN, NULL, &dest2);

        SDL_RenderPresent(renderer);
        //Event handling

        SDL_PollEvent(&event);
        switch(event.type){
            case SDL_KEYDOWN:
                switch(event.key.keysym.scancode){
                    case SDL_SCANCODE_UP:
                        setPacmanDirection(NORTH);
                        if(konami[0]){
                            if(konami[1]){
                                for(j = 0 ; j < 10 ; j++){
                                    konami[j] = 0;
                                }
//                                printf("Déjà deux\n");
                            }else{
                                konami[1] = 1;
                            }
                        }else{
                            konami[0] = 1;
                        }
                        break;
                    case SDL_SCANCODE_DOWN:
                        setPacmanDirection(SOUTH);
                        break;
                    case SDL_SCANCODE_RIGHT:
                        setPacmanDirection(EAST);
                        break;
                    case SDL_SCANCODE_LEFT:
                        setPacmanDirection(WEST);
                        break;
                    default:
                        break;
                }
                break;
        }
        terminate = update(clyde, blinky, inky, pinky);
        if(terminate){
            if(pacman->life > 0 ){
                pacman->life--;
                terminate = 0;
                pacman->x = initialX;
                pacman->y = initialY;
            }
        }
        if(event.window.event == SDL_WINDOWEVENT_CLOSE){
            terminate = 1;
        }
        SDL_Delay(1000 / FPS);
        SDL_DestroyTexture(scoreTN);
        SDL_FreeSurface(scoreN);
    }
    printf("Score final : %d\n", pacman->point);
    Mix_FreeMusic(music);
    Mix_CloseAudio();
    freeTextures();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    SDL_DestroyTexture(scoreT);
    freePacman();
    freeGhost(clyde);
    freeGhost(blinky);
    freeGhost(inky);
    freeGhost(pinky);
    freeMap();
    TTF_CloseFont(police);
    TTF_Quit();
    return EXIT_SUCCESS;
}
Example #8
0
bool CSoundEffect::Load()
{
    if (m_Chunk != nullptr)
        return false;

    m_Chunk = Mix_LoadWAV(m_Path.c_str());

    if (!m_Chunk)
    {
        CCoreEngine::Instance().GetLogManager().LogOutput(LOG_ERROR, LOGSUB_SOUND, "CSoundEffect::Load Error: %s", Mix_GetError());

        return false;
    }

    return true;
}
Example #9
0
int main(int argc, char *argv[])
{
	//Set the window title
	std::string title = "Sky Zone Omega";

	//Set the window and target resolutions
	C_Vec2 targetRes = C_Vec2(1080, 608);
	C_Vec2 windowRes = C_Vec2(1080, 608);

	//Initialise SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		//Failed initialisation
		C_Utilities::logE("SDL failed to initialise: " + std::string(SDL_GetError()));
		return -1;
	}

	//Initialise SDL_ttf
	if (TTF_Init() < 0)
	{
		//Failed initialisation
		C_Utilities::logE("SDL_ttf failed to initialise: " + std::string(TTF_GetError()));
		return -1;
	}

	//Initialise SDL_mixer
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
	{
		C_Utilities::logE("SDL_mixer failed to initialise: " + std::string(Mix_GetError()));
		return -1;
	}

	//Time Check
	unsigned int lastTime = SDL_GetTicks();


#if !defined(_DEBUG)

	//Create Window
	C_Vec2 windowPos = C_Vec2(100, 100);
	SDL_Window *window = SDL_CreateWindow(title.c_str(),
		(int)windowPos.x, (int)windowPos.y,
		(int)windowRes.x, (int)windowRes.y,
		SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP);

#else

	//Create Window
	C_Vec2 windowPos = C_Vec2(100, 100);
	SDL_Window *window = SDL_CreateWindow(title.c_str(),
		(int)windowPos.x, (int)windowPos.y,
		(int)windowRes.x, (int)windowRes.y,
		SDL_WINDOW_SHOWN);

#endif	

	//Create Renderer from the window
	SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);

	//Set the renderer to work out the render at this resolution and then scale it up the 
	//closest resolution it can to the windows resolution (adds bars of the render colour)
	SDL_RenderSetLogicalSize(renderer, (int)targetRes.x, (int)targetRes.y);

	//The background music
	C_Music* backgroundMusic = new C_Music("Assets/Audio/gameplayLoop.ogg");

	//Setup state manager and initial state
	S_StateManager * stateManager = new S_StateManager();
	stateManager->addState(new S_Splash(stateManager, renderer, targetRes, backgroundMusic));

	//Start Game Loop
	bool go = true;
	while (go)
	{
		//Time Check
		unsigned int current = SDL_GetTicks();
		float deltaTime = (float)(current - lastTime) / 1000.0f;
		lastTime = current;

		//Handle the current state inputs
		go = stateManager->input();

		//Update the current state
		stateManager->update(deltaTime);

		//set draw colour to black
		SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);

		//Clear the entire screen to the set colour
		SDL_RenderClear(renderer);

		//Draw the states
		stateManager->draw();

		//display renderer
		SDL_RenderPresent(renderer);

		//Time Limiter
		if (deltaTime < (1.0f / 50.0f))
		{
			SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f));
		}
	}
	//destroy data
	delete stateManager;
	//Stop music
	backgroundMusic->stopMusic();
	//Delete audio pointers
	delete backgroundMusic;
	SDL_DestroyWindow(window);
	SDL_Quit();
	return 0;
}
Example #10
0
	void SoundEffect::play(int loops) {
		const int defaultChannel{ -1 };
		if (Mix_PlayChannel(defaultChannel, m_chunk, loops) == -1) {
			fatalError("Mix_PlayChannel error:" + std::string(Mix_GetError()));
		}
	}
Example #11
0
void CSoundEffect::Play()
{
    // If sound is not pre-loaded, Load it
    if (m_Chunk == nullptr)
        if ( !Load() )
            return;

    // Stop sound in case this is playing
    Stop();

    // Play sound in an available channel
    m_Channel = Mix_PlayChannel( -1, m_Chunk, 0 );
    if (m_Channel == -1)
        CCoreEngine::Instance().GetLogManager().LogOutput(LOG_ERROR, LOGSUB_SOUND, "CSoundEffect::Play Mix_PlayChannel: %s", Mix_GetError());

}
Example #12
0
	void Music::play(int loops) {
		if (Mix_PlayMusic(m_music, loops) == -1) {
			fatalError("Mix_PlayChannel error:" + std::string(Mix_GetError()));
		}
	}
void soundLib::load_boss_music(string music_file) {
	string filename;

	if (boss_music != NULL) {
		Mix_HaltMusic();
		Mix_FreeMusic(boss_music);
        boss_music = NULL;
	}
	filename = FILEPATH + "data/music/" + music_file;
	//std::cout << "soundLib::load_boss_music - filename: " << filename << std::endl;
	boss_music = Mix_LoadMUS(filename.c_str());
	if (!boss_music) {
        std::cout << "Error in soundLib::load_boss_music::Mix_LoadMUS('" << filename << "': '" << Mix_GetError() << "'\n";
        std::fflush(stdout);
		exit(-1);
	}
}
void soundLib::load_music(std::string music_file) {
	string filename;

	unload_music();
	filename = FILEPATH + "data/music/" + music_file;
    //std::cout << "soundLib::load_music - filename: " << filename << std::endl;
	music = Mix_LoadMUS(filename.c_str());
	if (!music) {
        std::cout << "Error in soundLib::load_music::Mix_LoadMUS('" << filename << "': '" << Mix_GetError() << "'\n";
        std::fflush(stdout);
		exit(-1);
	}
}
Example #15
0
/* Load a music file */
Mix_Music *Mix_LoadMUS(const char *file)
{
    SDL_RWops *src;
    Mix_Music *music;
    Mix_MusicType type;
    char *ext = strrchr(file, '.');

#ifdef CMD_MUSIC
    if ( music_cmd ) {
        /* Allocate memory for the music structure */
        music = (Mix_Music *)SDL_malloc(sizeof(Mix_Music));
        if ( music == NULL ) {
            Mix_SetError("Out of memory");
            return(NULL);
        }
        music->error = 0;
        music->type = MUS_CMD;
        music->data.cmd = MusicCMD_LoadSong(music_cmd, file);
        if ( music->data.cmd == NULL ) {
            SDL_free(music);
            music = NULL;
        }
        return music;
    }
#endif

    src = SDL_RWFromFile(file, "rb");
    if ( src == NULL ) {
        Mix_SetError("Couldn't open '%s'", file);
        return NULL;
    }

    /* Use the extension as a first guess on the file type */
    type = MUS_NONE;
    ext = strrchr(file, '.');
    /* No need to guard these with #ifdef *_MUSIC stuff,
     * since we simply call Mix_LoadMUSType_RW() later */
    if ( ext ) {
        ++ext; /* skip the dot in the extension */
        if ( MIX_string_equals(ext, "WAV") ) {
            type = MUS_WAV;
        } else if ( MIX_string_equals(ext, "MID") ||
                    MIX_string_equals(ext, "MIDI") ||
                    MIX_string_equals(ext, "KAR") ) {
            type = MUS_MID;
        } else if ( MIX_string_equals(ext, "OGG") ) {
            type = MUS_OGG;
        } else if ( MIX_string_equals(ext, "FLAC") ) {
            type = MUS_FLAC;
        } else  if ( MIX_string_equals(ext, "MPG") ||
                     MIX_string_equals(ext, "MPEG") ||
                     MIX_string_equals(ext, "MP3") ||
                     MIX_string_equals(ext, "MAD") ) {
            type = MUS_MP3;
        }
    }
    if ( type == MUS_NONE ) {
        type = detect_music_type(src);
    }

    /* We need to know if a specific error occurs; if not, we'll set a
     * generic one, so we clear the current one. */
    Mix_SetError("");
    music = Mix_LoadMUSType_RW(src, type, SDL_TRUE);
    if ( music == NULL && Mix_GetError()[0] == '\0' ) {
        Mix_SetError("Unrecognized music format");
    }
    return music;
}
Example #16
0
void Init_Sound(void) {
	char *sd;

#if defined(sgi)
	int err;
#elif defined(HAVE_SDL)
#else
	char buf[PATH_MAX];
#endif

#ifdef DEBUG
	printf("Init_Sound\n");
#endif
	/*
	 * If sound_init is on in the .xtrekrc file (set in defaults.c)
	 * look for sounds in .xtrekrc sounddir parameter. If that fails
	 * look for an environment variable called SOUNDDIR and if that
	 * fails, try to open the hardcoded sound directory.
	 */
	if (sound_init) {
		if ((sounddir = getdefault("sounddir")) == NULL) {
			if ((sd=getenv("SOUNDDIR")) != NULL)
				sounddir = strdup(sd);
			else
#if defined(sgi)
				sounddir = "/usr/local/games/netrek-sgi/sounds";
#else
				sounddir = "/usr/share/sounds/netrek-client-cow";
#endif
		}
		if (!isDirectory(sounddir)) {
			sounddir = "sounds";
				if (!isDirectory(sounddir)) {
					(void) fprintf(stderr, "sound directory %s missing\n", sounddir);
					return;
			}
		}
	}
#if defined(sgi)
	err = sfxInit(sounddir, 3);			/* initialize up to three audio ports */
	if (err == SFX_ERR_NO_PORTS_AVAIL) {
		(void) fprintf(stderr, "No audio ports available.\n");
		sound_init = 0;
		sound_toggle = 0;
		return;
	}
	if (err == SFX_ERR_NO_SPROC) {
		(void) fprintf(stderr, "Unable to execute sound process.\n");
		sound_init = 0;
		sound_toggle = 0;
		return;
	}
	if (err == SFX_ERR_NO_MEM) {
		(void) fprintf(stderr, "No memory available for sound data.\n");
		sound_init = 0;
		sound_toggle = 0;
		return;
	}
	if (err > 0) {				/* load mandatory sounds f we got at least one audio port */
		sounds[FIRE_TORP_WAV] = sfxLoad("fire_torp.aiff");
		sounds[PHASER_WAV] = sfxLoad("phaser.aiff");
		sounds[FIRE_PLASMA_WAV] = sfxLoad("fire_plasma.aiff");
		sounds[EXPLOSION_WAV] = sfxLoad("explosion.aiff");
		sounds[FIRE_TORP_OTHER_WAV] = sfxLoad("fire_torp_other.aiff");
		sounds[PHASER_OTHER_WAV] = sfxLoad("phaser_other.aiff");
		sounds[FIRE_PLASMA_OTHER_WAV] = sfxLoad("fire_plasma_other.aiff");
		sounds[EXPLOSION_OTHER_WAV] = sfxLoad("explosion_other.aiff");
		sounds[PLASMA_HIT_WAV] = sfxLoad("plasma_hit.aiff");
		sounds[TORP_HIT_WAV] = sfxLoad("torp_hit.aiff");

		if (err > 1) {			/* load optional sounds only if we got two audio ports */
			sounds[CLOAK_WAV] = sfxLoad("cloak.aiff");
			sounds[UNCLOAK_WAV] = sfxLoad("cloak.aiff");
			sounds[SHIELD_DOWN_WAV] = sfxLoad("shield_down.aiff");
			sounds[SHIELD_UP_WAV] = sfxLoad("shield_up.aiff");
			sounds[REDALERT_WAV] = sfxLoad("klaxon.aiff");
			sounds[INTRO_WAV] = sfxLoad("paradise.aiff");
			sounds[MESSAGE_WAV] = sfxLoad("message.aiff");

			/* load sound loops only if we got three audio ports */
			if (err > 2) {
				sounds[THERMAL_WAV] = sfxLoad("thermal_warn.aiff");
				sounds[ENTER_SHIP_WAV] = sfxLoad("enter_ship.aiff");
				sounds[SELF_DESTRUCT_WAV] = sfxLoad("self_destruct.aiff");

				if ((sounds[ENGINE_WAV] = sfxLoad("bridge.aiff")) != NULL) {
					sfxLoop(sounds[ENGINE_WAV]);
					sfxPitchBend(sounds[ENGINE_WAV], 0.0f, 1.0f, 1.0f, 2.0f, 1.1f, 20);
				}
			}
		}
		sfxPlay(sounds[INTRO_WAV]);
	}

#elif defined(HAVE_SDL)
#ifdef DEBUG
	printf("Init_Sound using SDL\n");
#endif

	/* Initialize the SDL library */
	if (SDL_Init(SDL_INIT_AUDIO) < 0) {
	  fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
	}
	atexit(SDL_Quit);

	/* Open the audio device at 8000 Hz 8 bit Microsoft PCM */
	if (Mix_OpenAudio(8000, AUDIO_U8, 1, 512) < 0) {
	  fprintf(stderr,"Mix_OpenAudio: %s\n", Mix_GetError());
	  sound_init = 0;
	}

        Mix_AllocateChannels(16);

	/* If we successfully loaded the wav files, so shut-off
	   sound_init and play the introduction */
	if (loadSounds()) {
	  if (sounds[INTRO_WAV])
	    if (Mix_PlayChannel(-1, sounds[INTRO_WAV], 0) < 0) {
	      fprintf(stderr, "Mix_PlayChannel: %s\n", Mix_GetError());
	    }
	}
#else
	if (InitSound() == -1) {
	  sound_toggle = 0;
	  sound_init = 0;
	} else {
	  sound_init = 1;
	  sound_toggle = 1;
	}

	strcpy(sound_prefix, sounddir);
	strcat(sound_prefix, "/");

	if (sound_toggle) {
	  strcpy(buf, sounddir);
	  strcat(buf, "/nt_intro");
	  StartSound(buf);
	}
#endif
}
Example #17
0
SoundPlayer::SoundPlayer()
{
	if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 0, 1024) < 0)
		throw std::runtime_error(Mix_GetError());
}
Example #18
0
int main(int argc, char *argv[]) {
    /* Declare some variables */
    SNDFILE *music_file = NULL;
    SF_INFO sfinfo;
    sfinfo.format = 0;

    printf("Audio visualizer for Comp 467\n");
    printf("By: Jorenz Paragas, Carlos Henriquez, Joshua Licudo\n");
    printf("----\n");

    /* Check if the user provided a .wav file */
    if (argc < 2) {
        fprintf(stderr, "Error: a .wav file was not provided.\n");
        fprintf(stderr, "Usage: %s input.wav\n", argv[0]);
        return EXIT_FAILURE;
    }

    /* Open the .wav file */
    music_file = sf_open(argv[1], SFM_READ, &sfinfo);
    if (music_file == NULL) {
        fprintf(stderr, "Cannot open .wav file: %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("Name of file: %s\n", argv[1]);
    printf("Sample rate: %d\n", sfinfo.samplerate);
    printf("Channels: %d\n", sfinfo.channels);

    /* The buffer size for libsndfile must be as large as the product of
     * the number of channels and the number of samples to be read */ 
    const int buffer_size = SAMPLE_COUNT * sfinfo.channels;

    /* For a real-to-complex transform, according to the FFTW docs,
     * the expected size of the array is n / 2 + 1 */
    const int out_buffer_size = buffer_size / 2 + 1;

    /* Declare the two buffers to hold the data and tell
     * FFTW how to calculate the frequencies */
    double samples[buffer_size];
    memset(&samples, 0, buffer_size);

    fftw_complex output[out_buffer_size];
    fftw_plan plan = fftw_plan_dft_r2c_1d(buffer_size, samples, 
        output, FFTW_ESTIMATE);

    if (plan == NULL) {
        fprintf(stderr, "Plan cannot be created.\n");
        sf_close(music_file);
        return EXIT_FAILURE;
    }

    /* Start SDL */
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    atexit(SDL_Quit);

    /* Create the window */
    SDL_Window *window = SDL_CreateWindow("Comp 467 Project", 10, 10, 
        WINDOW_WIDTH, WINDOW_HEIGHT, 0);
    if (window == NULL) {
        fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    
    /* Get the window's surface */
    SDL_Surface *surface = SDL_GetWindowSurface(window);
    
    /* Initialize the random number generator */
    srand(time(NULL));

    /* Open the music file */
    Mix_OpenAudio(sfinfo.samplerate, MIX_DEFAULT_FORMAT, 
        sfinfo.channels, 4096);
    Mix_Music *music = Mix_LoadMUS(argv[1]);
    if (music == NULL) {
        fprintf(stderr, "Mix_LoadMUS error: %s\n", Mix_GetError());
    }
    
    /* Start playing it */
    Mix_PlayMusic(music, 0);

    /* Timer-related variables */
    unsigned int start_time = SDL_GetTicks();
    unsigned int last_time = start_time;
    unsigned int current_time = start_time;

    /* The main loop */
    bool running = true;
    while (running) {
        /* Obtain any user input */
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
        }

        /* Based on the sample rate and the current time,
         * figure out what position to read the audio file from */
        double seconds = (current_time - start_time) / 1000.0; 
        //printf("Current time: %.2f\n", seconds);

        sf_count_t sample_pos = (int) sfinfo.samplerate * seconds; 
        int result = sf_seek(music_file, sample_pos, SEEK_SET);
        if (result == -1) {
            running = false;
        }

        /* Read the samples */
        int samples_read = sf_readf_double(music_file, samples, 
            SAMPLE_COUNT); 
        if (samples_read <= 0) {
            running = false;        
        }
    
        /* Calculate the FFT */
        fftw_execute(plan);

        /* Fill the screen with black first */
        SDL_Rect surf_rect;
        
        surf_rect.w = WINDOW_WIDTH;
        surf_rect.h = WINDOW_HEIGHT;

        surf_rect.x = 0;
        surf_rect.y = 0;

        SDL_FillRect(surface, &surf_rect, SDL_MapRGB(surface->format,
                     0, 0, 0));

        /* Draw all the rectangles */
        int x_pos;
        for (x_pos = 0; x_pos < WINDOW_WIDTH; x_pos += 1) {
            SDL_Rect rect;

            /* Based on the rectangle's position, get a different
             * frequency; the second half of the buffer is useless
             * data, so ignore that portion */
            double relative_pos = x_pos * 1.0f / WINDOW_WIDTH; 
            int buf_range_max = out_buffer_size / 2;
            int index = (int) (relative_pos * buf_range_max);

            /* Figure out the normalized magnitude of the frequency */
            double mag = sqrt(output[index][0] * output[index][0] +
                              output[index][1] * output[index][1]);
            double norm_mag = mag * (1 / sqrt(buffer_size)); 
            //printf("%d: %f\n", index, norm_mag);

            /* Set the rectangle's size */
            rect.w = 1;
            rect.h = norm_mag * WINDOW_HEIGHT;

            /* Set the rectangle's lower left corner */
            rect.x = x_pos;
            rect.y = WINDOW_HEIGHT - rect.h;

            /* Draw the rectangle to the screen */
            SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format,
                         0, 0, 255));
        }

        /* Update the display */
        SDL_UpdateWindowSurface(window);

        /* Ensure that it runs around 30 FPS and also update the
         * timer variables */ 
        current_time = SDL_GetTicks();
        int delta = current_time - last_time;
        if (delta <= 33) {
            SDL_Delay(33 - delta);
        }
        last_time = current_time;
    }

    /* Stop the music and free its memory */
    Mix_HaltMusic();
    Mix_FreeMusic(music);

    /* Clean up and exit */
    SDL_FreeSurface(surface);
    SDL_DestroyWindow(window);

    fftw_destroy_plan(plan);
    sf_close(music_file);

    return EXIT_SUCCESS;
}
Example #19
0
File: midi.cpp Project: paud/d2x-xl
int CMidi::PlaySong (char* pszSong, char* melodicBank, char* drumBank, int bLoop, int bD1Song)
{
#if (defined (_WIN32) || USE_SDL_MIXER)
	int	bCustom;

PrintLog ("DigiPlayMidiSong (%s)\n", pszSong);
audio.StopCurrentSong ();
if (!(pszSong && *pszSong))
	return 0;
if (m_nVolume < 1)
	return 0;

bCustom = ((strstr (pszSong, ".mp3") != NULL) || (strstr (pszSong, ".ogg") != NULL));
if (bCustom) {
	if (audio.Format () != AUDIO_S16LSB) {
		audio.Shutdown ();
		audio.Setup (1, AUDIO_S16LSB);
		}
	}
else if (!(m_hmp = hmp_open (pszSong, bD1Song)))
	return 0;

#	if USE_SDL_MIXER
if (gameOpts->sound.bUseSDLMixer) {
	char	fnSong [FILENAME_LEN], *pfnSong;

	if (bCustom) {
		pfnSong = pszSong;
		if (strstr (pszSong, ".mp3") && !songManager.MP3 ()) {
			audio.Shutdown ();
			songManager.SetMP3 (1);
			audio.Setup (1);
			}
		}
	else {
		if (!strstr (pszSong, ".mp3") && songManager.MP3 ()) {
			audio.Shutdown ();
			songManager.SetMP3 (0);
			audio.Setup (1);
			}
#if defined (_WIN32)
		sprintf (fnSong, "%s/d2x-temp.mid", *gameFolders.szCacheDir ? gameFolders.szCacheDir : gameFolders.szHomeDir);
#else
		sprintf (fnSong, "%s/d2x-temp.mid", *gameFolders.szCacheDir ? gameFolders.szCacheDir : gameFolders.szHomeDir);
#endif
		if (!hmp_to_midi (m_hmp, fnSong)) {
			PrintLog ("SDL_mixer failed to load %s\n(%s)\n", fnSong, Mix_GetError ());
			return 0;
			}
		pfnSong = fnSong;
		}
	if (!(m_music = Mix_LoadMUS (pfnSong))) {
		PrintLog ("SDL_mixer failed to load %s\n(%s)\n", fnSong, Mix_GetError ());
		return 0;
		}
	if (-1 == Mix_FadeInMusicPos (m_music, bLoop ? -1 : 1, songManager.Pos () ? 1000 : 1500, (double) songManager.Pos () / 1000.0)) {
		PrintLog ("SDL_mixer cannot play %s\n(%s)\n", pszSong, Mix_GetError ());
		songManager.SetPos (0);
		return 0;
		}
	PrintLog ("SDL_mixer playing %s\n", pszSong);
	if (songManager.Pos ())
		songManager.SetPos (0);
	else
		songManager.SetStart (SDL_GetTicks ());
	
	songManager.SetPlaying (1);
	SetVolume (m_nVolume);
	return 1;
	}
#	endif
#	if defined (_WIN32)
if (bCustom) {
	PrintLog ("Cannot play %s - enable SDL_mixer\n", pszSong);
	return 0;
	}
hmp_play (m_hmp, bLoop);
songManager.SetPlaying (1);
SetVolume (m_nVolume);
#	endif
#endif
return 1;
}
Example #20
0
/*
--------------------------------------------------------------------------------
                                      INIT
--------------------------------------------------------------------------------
 *  Master init function.  Being a game made in SDL2, SDL2 and its subsystems
 *  are obviously critical to the functionality of the program.  Also, their
 *  initialization is kept here because it's tidier.
*/
bool init( void )
{
    /*  Init SDL */
    if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO ) < 0 )
    {
        printf("ERROR:  Could not init SDL.  SDL Error:  %s\n",
                SDL_GetError() );
        return( false );
    }

    /*  Init SDL_image */
    if( ( IMG_Init( IMG_INIT_PNG ) & IMG_INIT_PNG ) == false )
    {
        printf("ERROR:  Could not init SDL_image.  IMG Error:  %s\n",
                IMG_GetError() );
        return( false );
    }

    /*  Init SDL_mixer */
    if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
    {
        printf("ERROR:  Could not init SDL_mixer.  Mix Error:  %s\n",
                Mix_GetError() );
        return( false );
    }


    /*  Init SDL_ttf */
    if( TTF_Init() == -1 )
    {
        printf("ERROR:  Could not init SDL_ttf.  TTF Error:  %s\n",
                TTF_GetError() );
        return( false );
    }


    /*  Create our window */
    gWindow = SDL_CreateWindow( "BELTED (working title)",
            SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
            WWIDTH, WHEIGHT, SDL_WINDOW_SHOWN );
    if( gWindow == NULL )
    {
        printf("ERROR:  Could not create window.  SDL Error:  %s\n",
                SDL_GetError() );
        return( false );
    }

    /*
     *  Create the renderer
     *
     *  We check for the limiting of FPS as a futureproofing thing.  Also,
     *  theoretically a bug-solving or performance thing.
     */

    /*  If they want to limit FPS, don't vsync */
    if( limitFPS )
        gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED );

    /*  Otherwise, use vsync */
    else
    {
        gRenderer = SDL_CreateRenderer( gWindow, -1,
                SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
    }
    if( gRenderer == NULL )
    {
        printf("ERROR:  Could not create renderer.  SDL Error:  %s\n",
                SDL_GetError() );
        return( false );
    }


    /*  Just for shits and giggles, we'll seed random here */
    srand( (unsigned int)time(NULL) );

    /*  Init boundary dimensions */
    BWIDTH = WWIDTH;
    BHEIGHT = WHEIGHT - 100;

    /*  Init colors */
    init_colors();

    /*  Init blend mode */
    SDL_SetRenderDrawBlendMode( gRenderer, SDL_BLENDMODE_BLEND );

    /*  Init transitions */
    init_transition();


    /*  If we made it this far, we're golden */
    return( true );
}
Example #21
0
/**
 * @sa M_Stop
 */
static void M_Start (const char* file)
{
	if (Q_strnull(file))
		return;

	if (!s_env.initialized) {
		Com_Printf("M_Start: No sound started!\n");
		return;
	}

	if (music.playingStream || !music.playing)
		return;

	char name[MAX_QPATH];
	Com_StripExtension(file, name, sizeof(name));
	const size_t len = strlen(name);
	if (len + 4 >= MAX_QPATH) {
		Com_Printf("M_Start: MAX_QPATH exceeded: " UFO_SIZE_T "\n", len + 4);
		return;
	}

	/* we are already playing that track */
	if (Q_streq(name, music.currentTrack) && music.data && Mix_PlayingMusic())
		return;

	/* we are still playing some background track - fade it out */
	if (music.data && Mix_PlayingMusic()) {
		if (!Mix_FadeOutMusic(1500))
			M_Stop();
		Q_strncpyz(music.nextTrack, name, sizeof(music.nextTrack));
		return;
	}

	/* make really sure the last track is closed and freed */
	M_Stop();

	/* load it in */
	byte* musicBuf;
	const int size = FS_LoadFile(va("music/%s.ogg", name), &musicBuf);
	if (size == -1) {
		Com_Printf("M_Start: Could not load '%s' background track!\n", name);
		return;
	}

	SDL_RWops* rw = SDL_RWFromMem(musicBuf, size);
	if (!rw) {
		Com_Printf("M_Start: Could not load music: 'music/%s'!\n", name);
		FS_FreeFile(musicBuf);
		return;
	}
#if SDL_VERSION_ATLEAST(2,0,0)
	music.data = Mix_LoadMUS_RW(rw, 1);
#else
	music.data = Mix_LoadMUS_RW(rw);
#endif
	if (!music.data) {
		Com_Printf("M_Start: Could not load music: 'music/%s' (%s)!\n", name, Mix_GetError());
		SDL_FreeRW(rw);
		FS_FreeFile(musicBuf);
		return;
	}

	Q_strncpyz(music.currentTrack, name, sizeof(music.currentTrack));
	music.buffer = musicBuf;
	if (Mix_FadeInMusic(music.data, 1, 1500) == -1)
		Com_Printf("M_Start: Could not play music: 'music/%s' (%s)!\n", name, Mix_GetError());
}
Example #22
0
void I_PlaySong (int handle, int _looping)
{
	if(!music_initialized)
		return;

	if(--handle < 0 || handle >= MUSIC_TRACKS)
		return;

	if(!registered_tracks[handle].Track)
		return;

#ifdef OSX

	if(MusicSequenceSetAUGraph(sequence, graph) != noErr)
	{
		Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceSetAUGraph failed\n");
		return;
	}

	if(MusicPlayerSetSequence(player, sequence) != noErr)
	{
		Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerSetSequence failed\n");
		return;
	}

	if(MusicPlayerPreroll(player) != noErr)
	{
		Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerPreroll failed\n");
		return;
	}

	UInt32 outNumberOfTracks = 0;
	if(MusicSequenceGetTrackCount(sequence, &outNumberOfTracks) != noErr)
	{
		Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceGetTrackCount failed\n");
		return;
	}

	for(UInt32 i = 0; i < outNumberOfTracks; i++)
	{
		MusicTrack track;

		if(MusicSequenceGetIndTrack(sequence, i, &track) != noErr)
		{
			Printf (PRINT_HIGH, "I_PlaySong: MusicSequenceGetIndTrack failed\n");
			return;
		}

		struct s_loopinfo
		{
			MusicTimeStamp time;
			long loops;
		}LoopInfo;

		UInt32 inLength = sizeof(LoopInfo);

		if(MusicTrackGetProperty(track, kSequenceTrackProperty_LoopInfo, &LoopInfo, &inLength) != noErr)
		{
			Printf (PRINT_HIGH, "I_PlaySong: MusicTrackGetProperty failed\n");
			return;
		}

		inLength = sizeof(LoopInfo.time);

		if(MusicTrackGetProperty(track, kSequenceTrackProperty_TrackLength, &LoopInfo.time, &inLength) != noErr)
		{
			Printf (PRINT_HIGH, "I_PlaySong: MusicTrackGetProperty failed\n");
			return;
		}

		LoopInfo.loops = _looping ? 0 : 1;

		if(MusicTrackSetProperty(track, kSequenceTrackProperty_LoopInfo, &LoopInfo, sizeof(LoopInfo)) != noErr)
		{
			Printf (PRINT_HIGH, "I_PlaySong: MusicTrackSetProperty failed\n");
			return;
		}
	}

	if(MusicPlayerStart(player) != noErr)
	{
		Printf (PRINT_HIGH, "I_PlaySong: MusicPlayerStart failed\n");
		return;
	}

#else

	if(Mix_PlayMusic(registered_tracks[handle].Track, _looping ? -1 : 1) == -1)
	{
		Printf(PRINT_HIGH, "Mix_PlayMusic: %s\n", Mix_GetError());
		current_track = 0;
		return;
	}

    // [Russell] - Hack for setting the volume on windows vista, since it gets
    // reset on every music change
    I_SetMusicVolume(snd_musicvolume);

#endif

	current_track = handle;
}
Example #23
0
bool Enemy::check_collision(Projectile *p)
{
    if(p->x > _x && p->x < _x + _w &&
       p->y > _y && p->y < _y + _h)
    {
        --_health;

        _w -= ((_tier - 1 < 1 ? 2 : (_tier - 1) * 2) + 1);
        _h -= (_tier + 1);

        if(_w < 16)  _w = 16;
        if(_h < 16)  _h = 16;

        ParticleSystem *_hit_psys;

        if(_health > 0)
        {
            if(Mix_PlayChannel(-1, _hit_sound, 0) == -1)
            {
                std::cout << "Unable to play sound: " << Mix_GetError() << std::endl;
            }

            _hit_psys = new ParticleSystem(_x + _w / 2, _y + _h / 2, 10, 0.0001f, (((double) rand()) / RAND_MAX) * 360, 20, 5, 1.0f, 0.0f, 0.0f, 600, 4, true);
        }
        else
        {
            int r = (((double) rand()) / RAND_MAX) * 10 / _tier / 1.5;
            // std::cout << "r = " << r << " vs. " << (int) (10 / _tier / 2) << std::endl;
            if(r == (int) (10 / _tier / 2))
            {
                POWERUP_TYPE t = POWERUP_SPEED;

                r = (((double) rand()) / RAND_MAX) * 3;
                int d;
                if(r == 1)
                {
                    t = POWERUP_PROJECTILE_SPEED;
                    d = 10;
                }
                else if(r == 2)
                {
                    t = POWERUP_SPEED;
                    d = 10;
                }
                else
                {
                    t = POWERUP_TRIPLESHOT;
                    d = 20;
                }
                Powerup *p = new Powerup(t, _x, _y, 32, 32, d, 4);
                p->start();
                PowerupManager::register_powerup(p);
            }

            if(Mix_PlayChannel(-1, _dead_sound, 0) == -1)
            {
                std::cout << "Unable to play sound: " << Mix_GetError() << std::endl;
            }

            _hit_psys = new ParticleSystem(_x + _w / 2, _y + _h / 2, 20, 0.0001f, 0, 360, 100, 1.0f, 0.0f, 0.0f, 400, 4, true);
        }
        _hit_psys->start();
        ParticleManager::register_system(_hit_psys);

        return true;
    }

    return false;
}
Example #24
0
int I_RegisterSong (char *data, size_t musicLen)
{
	if(!music_initialized)
		return 0;

	// input mus memory file and midi
	MEMFILE *mus = mem_fopen_read(data, musicLen);
	MEMFILE *midi = mem_fopen_write();

	I_UnRegisterSong(0);

	int result = mus2mid(mus, midi);

	switch(result)
    {
        case 1:
            Printf(PRINT_HIGH, "MUS is not valid\n");
            break;
        case 0:
        case 2:
		{
#ifdef OSX

		if (NewMusicSequence(&sequence) != noErr)
			return 0;

		cfd = CFDataCreate(NULL, (const Uint8 *)mem_fgetbuf(midi), mem_fsize(midi));

		if(!cfd)
		{
			DisposeMusicSequence(sequence);
			return 0;
		}

		if (MusicSequenceLoadSMFData(sequence, (CFDataRef)cfd) != noErr)
		{
			DisposeMusicSequence(sequence);
			CFRelease(cfd);
			return 0;
		}

		registered_tracks[0].Track = (Mix_Music*)1;

#else

		Mix_Music *music = 0;

		// older versions of sdl-mixer require a physical midi file to be read, 1.2.7+ can read from memory
#ifndef TEMP_MIDI // SDL >= 1.2.7

            if (result == 0) // it is a midi
            {
                registered_tracks[0].Data = SDL_RWFromMem(mem_fgetbuf(midi), mem_fsize(midi));
            }
            else // it is another format
            {
                registered_tracks[0].Data = SDL_RWFromMem(data, musicLen);
            }


            if (!registered_tracks[0].Data)
            {
                Printf(PRINT_HIGH, "SDL_RWFromMem: %s\n", SDL_GetError());
                break;
            }

            music = Mix_LoadMUS_RW(registered_tracks[0].Data);

			if(!music)
            {
                Printf(PRINT_HIGH, "Mix_LoadMUS_RW: %s\n", Mix_GetError());

                SDL_FreeRW(registered_tracks[0].Data);
                registered_tracks[0].Data = NULL;

                break;
            }

#else // SDL <= 1.2.6 - Create a file so it can load the midi

			FILE *fp = fopen(TEMP_MIDI, "wb+");

			if(!fp)
			{
				Printf(PRINT_HIGH, "Could not open temporary music file %s, not playing track\n", TEMP_MIDI);

				break;
			}

			for(int i = 0; i < mem_fsize(midi); i++)
				fputc(mem_fgetbuf(midi)[i], fp);

			fclose(fp);

            music = Mix_LoadMUS(TEMP_MIDI);

            if(!music)
			{
				Printf(PRINT_HIGH, "Mix_LoadMUS: %s\n", Mix_GetError());
				break;
			}

#endif

		registered_tracks[0].Track = music;

#endif // OSX
            break;
		} // case 2
    }

	mem_fclose(mus);
	mem_fclose(midi);

	return 1;
}
Example #25
0
bool Platform::initSDL()
{
	bool status = true;
	
	#ifndef __ANDROID__
		//Android doesn't need this at SDL internally does this
		if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) 
		{ 
			status = false; 
			Utility::log(Utility::E, "SDL Init failed: " + std::string(SDL_GetError()));
		}
	#endif
	
	//SDL TTF Initialization
	if (TTF_Init() < 0)
	{
		status = false;
		Utility::log(Utility::E, "SDL_ttf init failed: " + std::string(TTF_GetError()));
	}

	//SDL Mixer Initialization
	Mix_Init(MIX_INIT_OGG);
	//Initialize SDL_Mixer with some standard audio formats/freqs. Also set channels to 2 for stereo sound.
	if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
	{
		status = false;
		Utility::log(Utility::E, "SDL_mixer init failed: " + std::string(Mix_GetError()));
	}
	
	//SDL Image Initialization
	int flags= IMG_INIT_PNG;
	int result = IMG_Init(flags);
	
	// If the inputed flags are not returned, an error has occurred
	if((result & flags) != flags) 
	{
		Utility::log(Utility::E, "Failed to Initialise SDL_Image and png support: "+ std::string(IMG_GetError()));
	}

	#ifdef __ANDROID__
	
		//SDL Android is very temperamental here, but these settings work fine
		if(SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer) < 0)
		{
			status = false;
			Utility::log(Utility::E, "Android Window/Renderer failed to be created: " + 
				std::string(SDL_GetError()));
		}

		if (window == NULL || renderer == NULL) 
		{ 
			status = false;
			Utility::log(Utility::E, "Window/Renderer failed to be created: " + 
				std::string(SDL_GetError()));
		}
	
	#else
	
		window = SDL_CreateWindow("MGP Assignment 2 by Richard Hancock",
		SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
		640, 480,
		SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

		renderer = SDL_CreateRenderer(window, -1, 0);

		if (!window || !renderer) 
		{ 
			status = false;
			Utility::log(Utility::E, "Window/Renderer failed to be created: " + 
				std::string(SDL_GetError()));
		}
	
	#endif

	int width;
	int height;

	SDL_GetWindowSize(window, &width, &height);

	windowSize.x = (float)width;
	windowSize.y = (float)height;
	
	Utility::log(Utility::I, "Window Dimensions: " + Utility::intToString(width) +
		"x" + Utility::intToString(height));

	return status;
}
Example #26
0
Engine::Engine(): run_(true),dt_(0.f),timeScale_(1.f) {
    if(SDL_Init(SDL_INIT_EVERYTHING)) {
        std::string error = "SDL Initialization failed: " + std::string(SDL_GetError());
        xLOG[Util::LogType::ERROR]("Engine :: ctor") << error << "\0";
        throw Util::RunTimeError(error);
    }
    xLOG[Util::LogType::SUCCESS]("Engine :: ctor") << "Successfully initialized SDL" << "\0";

	if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY*2, MIX_DEFAULT_FORMAT, 2 , 2048) == -1){
        xLOG[Util::LogType::ERROR]("Engine :: ctor") << "Error occured while initializing SDL_mixer: " << Mix_GetError() << "\0";
    } else {
        xLOG[Util::LogType::SUCCESS]("Engine :: ctor") << "Successfully initialized SDL_mixer" << "\0";
    }

    assetManager_ = std::unique_ptr<AssetLoader::AssetManager>(new AssetLoader::AssetManager(*this));

	config_ = std::unique_ptr<Util::Config>(new Util::Config(*this));
	config_->loadCfg();

	scriptEngine_ = std::unique_ptr<Script::ScriptEngine>(new Script::ScriptEngine(*this));
    renderSystem_ = std::unique_ptr<Renderer::RenderSystem>(new Renderer::RenderSystem(*this));
    fontRenderer_ = std::unique_ptr<Renderer::FontRenderer>(new Renderer::FontRenderer(*this));
	gameWorld_ = std::unique_ptr<World::GameWorld>(new World::GameWorld(*this));
    physicsSystem_ = std::unique_ptr<Physics::PhysicsSystem>(new Physics::PhysicsSystem(*this));

	entityManager_= std::unique_ptr<ECS::EntityManager>(new ECS::EntityManager(*this));
	stateMachine_ = std::unique_ptr<StateMachine>(new StateMachine(*this));
	uiManager_ = std::unique_ptr<UI::UIManager>(new UI::UIManager(*this));
	inputSystem_ = std::unique_ptr<Input::InputSystem>(new Input::InputSystem(*this));
	camera_ = std::unique_ptr<Renderer::Camera>(new Renderer::Camera(*this));
	soundEngine_ = std::unique_ptr<Sound::SoundEngine>(new Sound::SoundEngine(*this));

    soundEngine_->setMasterMusicVolume(config_->getInt("musicVolume"));
    soundEngine_->setMasterSoundVolume(config_->getInt("soundVolume"));

	scriptEngine_->init();

    //When States become scripts you can build the UI in the state onEnter
    scriptEngine_->setMainControlScript("Main");

	xLOG[Util::LogType::SUCCESS]("Engine :: ctor") << "Successfully initialized Engine" << "\0";
}
Example #27
0
void SDLAudio::logError(std::ostream &os, const std::string &msg) {
  os << msg << " (SDL error): " << SDL_GetError() << std::endl;
  os << msg << " (Mix error): " << Mix_GetError() << std::endl;
}
Example #28
0
BOOL init( void )
{
  const SDL_VideoInfo *info = NULL;
  int depth;
  int flags;

  load_options();

  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK ) < 0 )
  {
    fprintf( stderr, "SDL says: %s\n", SDL_GetError() );
    return FALSE;
  }

  joy = SDL_JoystickOpen( 0 );
  if( joy ) SDL_JoystickEventState( SDL_ENABLE );
  
//  printf( "%p\n", joy );

  needquit = TRUE;

  depth = 32;
  if( (info = SDL_GetVideoInfo()) )
    depth = info->vfmt->BitsPerPixel;

#ifdef __amigaos4__
  printf( "Detected MiniGL v%d.%d\n",
    MiniGLBase->lib_Version,
    MiniGLBase->lib_Revision );

  if( ( MiniGLBase->lib_Version < 2 ) ||
      ( ( MiniGLBase->lib_Version == 2 ) &&
        ( MiniGLBase->lib_Revision < 1 ) ) )
  {
    //screenbodge = TRUE;
    printf( "WARNING: The video screen won't work properly on the spaceship level\n" );
    printf( "with this version on MiniGL.\n" );
  }
#endif

#ifdef HAVE_GLES
flags = 0;
#else
flags = SDL_OPENGL;
#endif

#ifndef PANDORA
  if( fullscreen )
#endif
	flags |= SDL_FULLSCREEN;

#ifdef PANDORA
  ssrf = SDL_SetVideoMode( 800, 480, depth, flags );
#else
  ssrf = SDL_SetVideoMode( WINWIDTH, WINHEIGHT, depth, flags );
#endif
	
  if( ssrf == 0 )
  {
    fprintf( stderr, "SDL says: %s\n", SDL_GetError() );
    return FALSE;
  }

  SDL_ShowCursor( SDL_DISABLE );
#ifdef HAVE_GLES
// create EGL context
// *TODO* : real egl Checking for error
#define eglCheck()	 FALSE
	eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY);
	
	// Initialise EGL
	EGLint maj, min;
	if (!eglInitialize(eglDisplay, &maj, &min))
	{
		fprintf( stderr, "EGL Error: eglInitialize failed\n");
		return FALSE;
	}
	
	EGLint pi32ConfigAttribs[]  = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT , EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, EGL_NONE };
	EGLint pi32ContextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 1 , EGL_NONE };

	int num_config;
	
	EGLConfig config;
	if (!eglChooseConfig(eglDisplay, pi32ConfigAttribs, &config, 1, &num_config) || (num_config != 1))
	{
		fprintf(stderr, "EGL Error: eglChooseConfig failed\n");
		return FALSE;
	}
	
	eglSurface = eglCreateWindowSurface(eglDisplay, config, NULL, NULL);
	
	if (eglCheck())
	return FALSE;
	
	eglBindAPI(EGL_OPENGL_ES_API);
	if (eglCheck())
	return FALSE;
	
	eglContext = eglCreateContext(eglDisplay, config, NULL, pi32ContextAttribs);
	
	if (eglCheck())
	return FALSE;

	eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
	
	if (eglCheck())
	return FALSE;
	
	EGLint w,h;
	eglQuerySurface(eglDisplay, eglSurface, EGL_WIDTH, &w);
	eglQuerySurface(eglDisplay, eglSurface, EGL_HEIGHT, &h);
	
	// now, setup viewport to adapt to the surface
	//*TODO* adjust if surface is smaller
	int dx = (w-WINWIDTH)/2;
	int dy = (h-WINHEIGHT)/2;
	glViewport(dx, dy, WINWIDTH, WINHEIGHT);
#endif
/*
#ifdef __amigaos4__
  if( screenbodge )
  {
    struct IntuitionBase *ibase = (struct IntuitionBase *)IntuitionBase;
    win = ibase->ActiveWindow;
    if( !win )
      screenbodge = FALSE;
  }
#endif
*/
  // initialize sdl mixer, open up the audio device
  if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
  {
    fprintf( stderr, "SDL_Mixer says: %s\n", Mix_GetError() );
  } else {
    audioavailable = TRUE;
  }

  loadsounds();

  if( !render_init() ) return FALSE;

  titlestate = 0;
  what_are_we_doing = WAWD_TITLES;

  return TRUE;
}
Example #29
0
/**
 * @sa S_Shutdown
 * @sa S_Restart_f
 */
void S_Init (void)
{
    SDL_version version;
    char drivername[MAX_VAR];

    Com_Printf("\n------- sound initialization -------\n");

    OBJZERO(s_env);

    snd_init = Cvar_Get("snd_init", "1", CVAR_ARCHIVE, "Should the sound renderer get initialized");
    snd_init->modified = false; /* don't restart right away */
    Cmd_AddCommand("snd_restart", S_Restart_f, "Restart the sound renderer");

    if (!snd_init->integer) {
        Com_Printf("not initializing.\n");
        Cmd_AddCommand("music_change", Cmd_Dummy_f, "Dummy command if sound is disabled");
        Cvar_Get("snd_music", "PsymongN3", 0, "Background music track");
        return;
    }

    cl_soundSysPool = Mem_CreatePool("Client: Sound system");

    snd_distance_scale = Cvar_Get("snd_distance_scale", "0.1", 0, "Sound distance scale");
    snd_volume = Cvar_Get("snd_volume", "0.7", CVAR_ARCHIVE, "Sound volume - default is 0.7");
    snd_rate = Cvar_Get("snd_rate", "44100", CVAR_ARCHIVE, "Hz value for sound renderer - default is 44100");
    snd_chunkbufsize = Cvar_Get("snd_chunkbufsize", "1024", CVAR_ARCHIVE, "The sound buffer chunk size");
    /* set volumes to be changed so they are applied again for next sound/music playing */
    /** @todo implement the volume change for already loaded sample chunks */
    snd_volume->modified = true;

    Cmd_AddCommand("snd_play", S_Play_f, "Plays a sound fx file. Pass path relative to base/sound without file extension");
    Cmd_AddParamCompleteFunction("snd_play", S_CompleteSounds);

    if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
        if (SDL_Init(SDL_INIT_AUDIO) < 0) {
            Com_Printf("S_Init: %s.\n", SDL_GetError());
            return;
        }
    }

    MIX_VERSION(&version)
    Com_Printf("SDL_mixer version: %d.%d.%d\n", version.major, version.minor, version.patch);
    Com_Printf("... requested audio rate: %i\n", snd_rate->integer);

    if (Mix_OpenAudio(snd_rate->integer, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, snd_chunkbufsize->integer) == -1) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    if (Mix_QuerySpec(&s_env.rate, &s_env.format, &s_env.numChannels) == 0) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    if (SDL_AudioDriverName(drivername, sizeof(drivername)) == NULL)
        Q_strncpyz(drivername, "(UNKNOWN)", sizeof(drivername));
    Com_Printf("... driver: '%s'\n", drivername);

    if (Mix_AllocateChannels(MAX_CHANNELS) != MAX_CHANNELS) {
        Com_Printf("S_Init: %s\n", Mix_GetError());
        return;
    }

    Mix_ChannelFinished(S_FreeChannel);

    Com_Printf("... audio rate: %i\n", s_env.rate);
    Com_Printf("... audio channels: %i\n", s_env.numChannels);

#if COMPARE_VERSION(1, 2, 10)
    if (!(Mix_Init(MIX_INIT_OGG) & MIX_INIT_OGG))
        Com_Printf("... could not load ogg vorbis support\n");
    else
        Com_Printf("... loaded ogg vorbis support\n");
#endif

    s_env.initialized = true;

    M_Init();
}
Example #30
0
int main(int argc, char** argv)
{
    int running = 1;

    int move_right = 1;

    int frame_current = 0;
    Uint32 ticks;


    // Initialize everything
    if(!init())
    {
        printf("Failed to initialize SDL, exiting.\n");

        return 1;
    }

    // Load the resources
    if(!load_resources())
    {
        printf("Failed to load all necessary resources, exiting.\n");

        cleanup();

        return 1;
    }

    // Initialize Panda
    rect_panda.x = 1;
    rect_panda.y = rect_screen.h - rect_panda.h;

    // Measure time
    ticks = SDL_GetTicks();

    // Start playing music
    if(Mix_PlayChannel(0, music_bg, -1) == -1)
        printf("Failed to play background music: %s\n", Mix_GetError());

    // Main loop
    do
    {
        frame_current++;

        // Move the Panda
        if(move_right)
        {
            rect_panda.x = rect_panda.x + 3;
            rotation += 1.5;
        }
        else
        {
            rect_panda.x = rect_panda.x - 3;
            rotation -= 1.5;
        }


        rect_panda.y -= accel;
        accel -= 1;



        // Handle edges and floor
        if(move_right && rect_panda.x > rect_screen.w - rect_panda.w)
            move_right = 0;

        if(!move_right && rect_panda.x < 1)
            move_right = 1;

        if(rect_panda.y > rect_screen.h - rect_panda.h)
            rect_panda.y = rect_screen.h - rect_panda.h;


        // Handle events
        running = handle_events();

        // Set the background color
        SDL_SetRenderDrawColor(renderer,
                               frame_current % 255,
                               frame_current % 255,
                               frame_current % 255,
                               SDL_ALPHA_OPAQUE);

        // Clear the renderer
        SDL_RenderClear(renderer);

        // Draw the panda
        SDL_RenderCopyEx(renderer,
                         texture_panda,
                         NULL,
                         &rect_panda,
                         rotation,
                         NULL,
                         move_right ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL);

        // Update the screen
        SDL_RenderPresent(renderer);

        // Calculate FPS
        if(frame_current % 60 == 0)
        {
            Uint32 tick_diff = SDL_GetTicks() - ticks;
            printf("%.2f FPS (%i milliseconds) for the last 60 frames\n", 1.0 / (tick_diff / 60000.0), tick_diff);

            ticks = SDL_GetTicks();
        }
    } while(running);

    // Free resources
    free_resources();

    // Clean up SDL
    cleanup();

    // Exit
    return 0;
}