コード例 #1
0
void ScreenPackages::HTTPUpdate()
{
	if( !m_bIsDownloading )
		return;

	int BytesGot=0;
	//Keep this as a code block
	//as there may be need to "if" it out some time.
	/* If you need a conditional for a large block of code, stick it in
	 * a function and return. */
	while(1)
	{
		char Buffer[1024];
		int iSize = m_wSocket.ReadData( Buffer, 1024 );
		if( iSize <= 0 )
			break;

		m_sBUFFER.append( Buffer, iSize );
		BytesGot += iSize;
	}

	if( !m_bGotHeader )
	{
		m_sStatus = "Waiting for header.";
		//We don't know if we are using unix-style or dos-style
		size_t iHeaderEnd = FindEndOfHeaders( m_sBUFFER );
		if( iHeaderEnd == m_sBUFFER.npos )
			return;

		// "HTTP/1.1 200 OK"
		size_t i = m_sBUFFER.find(" ");
		size_t j = m_sBUFFER.find(" ",i+1);
		size_t k = m_sBUFFER.find("\n",j+1);
		if ( i == string::npos || j == string::npos || k == string::npos )
		{
			m_iResponseCode = -100;
			m_sResponseName = "Malformed response.";
			return;
		}
		m_iResponseCode = atoi(m_sBUFFER.substr(i+1,j-i).c_str());
		m_sResponseName = m_sBUFFER.substr( j+1, k-j );

		i = m_sBUFFER.find("Content-Length:");
		j = m_sBUFFER.find("\n", i+1 );

		if( i != string::npos )
			m_iTotalBytes = atoi(m_sBUFFER.substr(i+16,j-i).c_str());
		else
			m_iTotalBytes = -1;	//We don't know, so go until disconnect

		m_bGotHeader = true;
		m_sBUFFER.erase( 0, iHeaderEnd );
	}

	if( m_bIsPackage )
	{
		m_iDownloaded += m_sBUFFER.length();
		m_fOutputFile.Write( m_sBUFFER );
		m_sBUFFER = "";
	}
	else
	{
		m_iDownloaded = m_sBUFFER.length();
	}

	if ( ( m_iTotalBytes <= m_iDownloaded && m_iTotalBytes != -1 ) ||
					//We have the full doc. (And we knew how big it was)
		( m_iTotalBytes == -1 && 
			( m_wSocket.state == EzSockets::skERROR || m_wSocket.state == EzSockets::skDISCONNECTED ) ) )
				//We didn't know how big it was, and were disconnected
				//So that means we have it all.
	{
		m_wSocket.close();
		m_bIsDownloading = false;
		m_bGotHeader=false;
		m_sStatus = ssprintf( "Done;%dB", int(m_iDownloaded) );

		if( m_iResponseCode < 200 || m_iResponseCode >= 400 )
		{
			m_sStatus = ssprintf( "%ld", m_iResponseCode ) + m_sResponseName;
		}
		else
		{
			if( m_bIsPackage && m_iResponseCode < 300 )
			{
				m_fOutputFile.Close();
				FlushDirCache();
				RefreshPackages();
				m_iDownloaded = 0;
			}
			else
				HTMLParse();
		}
	}
}
コード例 #2
0
ファイル: main.cpp プロジェクト: ShadowWolfTJC/warzone2100
int realmain(int argc, char *argv[])
{
	wzMain(argc, argv);
	int utfargc = argc;
	const char** utfargv = (const char**)argv;

#ifdef WZ_OS_MAC
	cocoaInit();
#endif

	debug_init();
	debug_register_callback( debug_callback_stderr, NULL, NULL, NULL );
#if defined(WZ_OS_WIN) && defined(DEBUG_INSANE)
	debug_register_callback( debug_callback_win32debug, NULL, NULL, NULL );
#endif // WZ_OS_WIN && DEBUG_INSANE

	// *****
	// NOTE: Try *NOT* to use debug() output routines without some other method of informing the user.  All this output is sent to /dev/nul at this point on some platforms!
	// *****
	if (!getUTF8CmdLine(&utfargc, &utfargv))
	{
		return EXIT_FAILURE;
	}
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));	// make Qt treat all C strings in Warzone as UTF-8

	setupExceptionHandler(utfargc, utfargv, version_getFormattedVersionString());

	/*** Initialize PhysicsFS ***/
	initialize_PhysicsFS(utfargv[0]);

	/*** Initialize translations ***/
	initI18n();

	// find early boot info
	if (!ParseCommandLineEarly(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	/* Initialize the write/config directory for PhysicsFS.
	 * This needs to be done __after__ the early commandline parsing,
	 * because the user might tell us to use an alternative configuration
	 * directory.
	 */
	initialize_ConfigDir();

	/*** Initialize directory structure ***/
	make_dir(ScreenDumpPath, "screenshots", NULL);
	make_dir(SaveGamePath, "savegames", NULL);
	PHYSFS_mkdir("savegames/campaign");
	PHYSFS_mkdir("savegames/skirmish");
	make_dir(MultiCustomMapsPath, "maps", NULL); // MUST have this to prevent crashes when getting map
	PHYSFS_mkdir("music");
	PHYSFS_mkdir("logs");		// a place to hold our netplay, mingw crash reports & WZ logs
	PHYSFS_mkdir("userdata");	// a place to store per-mod data user generated data
	memset(rulesettag, 0, sizeof(rulesettag)); // tag to add to userdata to find user generated stuff
	make_dir(MultiPlayersPath, "multiplay", NULL);
	make_dir(MultiPlayersPath, "multiplay", "players");

	if (!customDebugfile)
	{
		// there was no custom debug file specified  (--debug-file=blah)
		// so we use our write directory to store our logs.
		time_t aclock;
		struct tm *newtime;
		char buf[PATH_MAX];

		time( &aclock );					// Get time in seconds
		newtime = localtime( &aclock );		// Convert time to struct
		// Note: We are using fopen(), and not physfs routines to open the file
		// log name is logs/(or \)WZlog-MMDD_HHMMSS.txt
		snprintf(buf, sizeof(buf), "%slogs%sWZlog-%02d%02d_%02d%02d%02d.txt", PHYSFS_getWriteDir(), PHYSFS_getDirSeparator(),
			newtime->tm_mon + 1, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec );
		debug_register_callback( debug_callback_file, debug_callback_file_init, debug_callback_file_exit, buf );

		// FIXME: Change this to LOG_WZ on next release
		debug(LOG_INFO, "Using %s debug file", buf);
	}

	// NOTE: it is now safe to use debug() calls to make sure output gets captured.
	check_Physfs();
	debug(LOG_WZ, "Warzone 2100 - %s", version_getFormattedVersionString());
	debug(LOG_WZ, "Using language: %s", getLanguage());
	debug(LOG_WZ, "Backend: %s", BACKEND);
	debug(LOG_MEMORY, "sizeof: SIMPLE_OBJECT=%ld, BASE_OBJECT=%ld, DROID=%ld, STRUCTURE=%ld, FEATURE=%ld, PROJECTILE=%ld",
	      (long)sizeof(SIMPLE_OBJECT), (long)sizeof(BASE_OBJECT), (long)sizeof(DROID), (long)sizeof(STRUCTURE), (long)sizeof(FEATURE), (long)sizeof(PROJECTILE));


	/* Put in the writedir root */
	sstrcpy(KeyMapPath, "keymap.map");

	// initialise all the command line states
	war_SetDefaultStates();

	debug(LOG_MAIN, "initializing");

	PhysicsEngineHandler engine;	// register abstract physfs filesystem

	loadConfig();

	// parse the command line
	if (!ParseCommandLine(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	// Save new (commandline) settings
	saveConfig();

	// Find out where to find the data
	scanDataDirs();

	// Now we check the mods to see if they exist or not (specified on the command line)
	// They are all capped at 100 mods max(see clparse.c)
	// FIX ME: I know this is a bit hackish, but better than nothing for now?
	{
		char *modname;
		char modtocheck[256];
		int i = 0;
		int result = 0;

		// check global mods
		for(i=0; i < 100; i++)
		{
			modname = global_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/global/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The (global) mod (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("(global) mod (%s) is enabled", modname);
			}
		}
		// check campaign mods
		for(i=0; i < 100; i++)
		{
			modname = campaign_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/campaign/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_ca (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_ca (%s) is enabled", modname);
			}
		}
		// check multiplay mods
		for(i=0; i < 100; i++)
		{
			modname = multiplay_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/multiplay/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_mp (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_mp (%s) is enabled", modname);
			}
		}
	}

	if (!wzMain2())
	{
		return EXIT_FAILURE;
	}
	int w = pie_GetVideoBufferWidth();
	int h = pie_GetVideoBufferHeight();

	char buf[256];
	ssprintf(buf, "Video Mode %d x %d (%s)", w, h, war_getFullscreen() ? "fullscreen" : "window");
	addDumpInfo(buf);

	debug(LOG_MAIN, "Final initialization");
	if (!frameInitialise())
	{
		return EXIT_FAILURE;
	}
	war_SetWidth(pie_GetVideoBufferWidth());
	war_SetHeight(pie_GetVideoBufferHeight());

	// Fix up settings from the config file
	// And initialize shader usage setting
	if (!pie_GetShaderAvailability())
	{
		war_SetShaders(FALLBACK);
		pie_SetShaderUsage(false);
	}
	else
	{
		if (war_GetShaders() == FALLBACK)
		{
			war_SetShaders(SHADERS_OFF);
		}
		if (!pie_GetFallbackAvailability())
		{
			war_SetShaders(SHADERS_ONLY);
			pie_SetShaderUsage(true);
		}
		else if (war_GetShaders() == SHADERS_ONLY || war_GetShaders() == SHADERS_ON)
		{
			war_SetShaders(SHADERS_ON);
			pie_SetShaderUsage(true);
		}
		else  // (war_GetShaders() == SHADERS_OFF)
		{
			pie_SetShaderUsage(false);
		}
	}

	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	pal_Init();

	pie_LoadBackDrop(SCREEN_RANDOMBDROP);
	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	if (!systemInitialise())
	{
		return EXIT_FAILURE;
	}

	//set all the pause states to false
	setAllPauseStates(false);

	// Copy this info to be used by the crash handler for the dump file
	ssprintf(buf,"Using Backend: %s", BACKEND);
	addDumpInfo(buf);
	ssprintf(buf,"Using language: %s", getLanguageName());
	addDumpInfo(buf);

	// Do the game mode specific initialisation.
	switch(GetGameMode())
	{
		case GS_TITLE_SCREEN:
			startTitleLoop();
			break;
		case GS_SAVEGAMELOAD:
			initSaveGameLoad();
			break;
		case GS_NORMAL:
			startGameLoop();
			break;
		default:
			debug(LOG_ERROR, "Weirdy game status, I'm afraid!!");
			break;
	}

#if defined(WZ_CC_MSVC) && defined(DEBUG)
	debug_MEMSTATS();
#endif
	debug(LOG_MAIN, "Entering main loop");
	wzMain3();
	saveConfig();
	systemShutdown();
#ifdef WZ_OS_WIN	// clean up the memory allocated for the command line conversion
	for (int i=0; i<argc; i++)
	{
		const char*** const utfargvF = &utfargv;
		free((void *)(*utfargvF)[i]);
	}
	free(utfargv);
#endif
	wzShutdown();
	debug(LOG_MAIN, "Completed shutting down Warzone 2100");
	return EXIT_SUCCESS;
}
コード例 #3
0
static void MemoryCardUsbLevelInit( size_t /*PlayerNumber*/ i, RString &sNameOut, int &defaultValueOut )
{
	sNameOut = ssprintf( "MemoryCardUsbLevelP%d", int(i+1) );
	defaultValueOut = -1;
}
コード例 #4
0
void EditCoursesSongMenu::OnRowValueChanged( Row row )
{
	LOG->Trace( "EditCoursesSongMenu::OnRowValueChanged(%i)", row );

	m_sprArrows[0].SetDiffuse( CanGoLeft()?RageColor(1,1,1,1):RageColor(0.2f,0.2f,0.2f,1) );
	m_sprArrows[1].SetDiffuse( CanGoRight()?RageColor(1,1,1,1):RageColor(0.2f,0.2f,0.2f,1) );
	m_sprArrows[0].EnableAnimation( CanGoLeft() );
	m_sprArrows[1].EnableAnimation( CanGoRight() );

	CString sGroup = GetSelectedGroup();
	Song *pSong = GetSelectedSong();
	
	switch( row )
	{
	case ROW_GROUP:
	{
		CHECKPOINT;
		m_textValue[ROW_GROUP].SetText( sGroup );

		UpdateSongList();

		pSong = GetSelectedSong();
	}
		// fall through
	case ROW_SONG:
		CHECKPOINT;
		m_textValue[ROW_SONG].SetText( pSong? pSong->GetTranslitMainTitle():CString("") );
		// fall through

	case ROW_TYPE:
		CHECKPOINT;
		m_textValue[ROW_TYPE].SetText( CourseEntryTypeToString(GetSelectedType()) );
		for( int i = 0; i < NUM_ROWS; ++i )
			m_textValue[i].SetDiffuse( 
				g_bRowEnabledForType[GetSelectedType()][i]?
					RageColor(1,1,1,1):RageColor(0.4f,0.4f,0.4f,1) );
		// fall through

	case ROW_DIFFICULTY:
	{
		CHECKPOINT;
		Difficulty dc = GetSelectedDifficulty();
		if( dc == DIFFICULTY_INVALID )
			m_textValue[ROW_DIFFICULTY].SetText( "(any)" );
		else
			m_textValue[ROW_DIFFICULTY].SetText( DifficultyToString(dc) );
		// fall through
	}
	case ROW_LOW_METER:
		CHECKPOINT;
		if( GetLowMeter() == -1 )
			m_textValue[ROW_LOW_METER].SetText( "(any)" );
		else
			m_textValue[ROW_LOW_METER].SetText( ssprintf("%d",GetLowMeter()) );
		// fall through

	case ROW_HIGH_METER:
		CHECKPOINT;
		if( GetHighMeter() == -1 )
			m_textValue[ROW_HIGH_METER].SetText( "(any)" );
		else
			m_textValue[ROW_HIGH_METER].SetText( ssprintf("%d",GetHighMeter()) );
		// fall through

	case ROW_BEST_WORST_VALUE:
		CHECKPOINT;
		m_textValue[ROW_BEST_WORST_VALUE].SetText( ssprintf("%d",GetBestWorst()+1) );
		break;

	default:
		ASSERT(0);	// invalid row
	}
}
コード例 #5
0
static RString CURSOR_OFFSET_Y_FROM_ICON_NAME( size_t p ) { return ssprintf("CursorP%dOffsetYFromIcon",int(p+1)); }
コード例 #6
0
ファイル: rbldnsd.c プロジェクト: 0xxon/rbldnsd
static int do_reload(int do_fork) {
  int r;
  char ibuf[150];
  int ip;
  struct dataset *ds;
  struct zone *zone;
  pid_t cpid = 0;	/* child pid; =0 to make gcc happy */
  int cfd = 0;		/* child stats fd; =0 to make gcc happy */
#ifndef NO_TIMES
  struct tms tms;
  clock_t utm, etm;
#ifndef HZ
  static clock_t HZ;
#endif
#endif /* NO_TIMES */

  ds = nextdataset2reload(NULL);
  if (!ds && call_hook(reload_check, (zonelist)) == 0) {
    check_expires();
    return 1;	/* nothing to reload */
  }

  if (do_fork) {
    int pfd[2];
    if (flog && !flushlog)
      fflush(flog);
    /* forking reload. if anything fails, just do a non-forking one */
    if (pipe(pfd) < 0)
      do_fork = 0;
    else if ((cpid = fork()) < 0) {	/* fork failed, close the pipe */
      close(pfd[0]);
      close(pfd[1]);
      do_fork = 0;
    }
    else if (!cpid) {	/* child, continue answering queries */
      signal(SIGALRM, SIG_IGN);
      signal(SIGHUP, SIG_IGN);
#ifndef NO_STATS
      signal(SIGUSR1, SIG_IGN);
      signal(SIGUSR2, SIG_IGN);
#endif
      close(pfd[0]);
      /* set up the fd#1 to write stats later on SIGTERM */
      if (pfd[1] != 1) {
        dup2(pfd[1], 1);
        close(pfd[1]);
      }
      fork_on_reload = -1;
      return 1;
    }
    else {
      close(pfd[1]);
      cfd = pfd[0];
    }
  }

#ifndef NO_TIMES
#ifndef HZ
  if (!HZ)
    HZ = sysconf(_SC_CLK_TCK);
#endif
  etm = times(&tms);
  utm = tms.tms_utime;
#endif /* NO_TIMES */

  r = 1;
  while(ds) {
    if (!loaddataset(ds))
      r = 0;
    ds = nextdataset2reload(ds);
  }

  for (zone = zonelist; zone; zone = zone->z_next) {
    time_t stamp = 0;
    time_t expires = 0;
    const struct dssoa *dssoa = NULL;
    const struct dsns *dsns = NULL;
    unsigned nsttl = 0;
    struct dslist *dsl;

    for(dsl = zone->z_dsl; dsl; dsl = dsl->dsl_next) {
      const struct dataset *ds = dsl->dsl_ds;
      if (!ds->ds_stamp) {
        stamp = 0;
        break;
      }
      if (stamp < ds->ds_stamp)
        stamp = ds->ds_stamp;
      if (ds->ds_expires && (!expires || expires > ds->ds_expires))
        expires = ds->ds_expires;
      if (!dssoa)
        dssoa = ds->ds_dssoa;
      if (!dsns)
        dsns = ds->ds_dsns, nsttl = ds->ds_nsttl;
    }

    zone->z_expires = expires;
    zone->z_stamp = stamp;
    if (!stamp) {
      zlog(LOG_WARNING, zone,
           "not all datasets are loaded, zone will not be serviced");
      r = 0;
    }
    else if (!update_zone_soa(zone, dssoa) ||
             !update_zone_ns(zone, dsns, nsttl, zonelist))
      zlog(LOG_WARNING, zone,
           "NS or SOA RRs are too long, will be ignored");
  }

  if (call_hook(reload, (zonelist)) != 0)
    r = 0;

  ip = ssprintf(ibuf, sizeof(ibuf), "zones reloaded");
#ifndef NO_TIMES
  etm = times(&tms) - etm;
  utm = tms.tms_utime - utm;
# define sec(tm) (unsigned long)(tm/HZ), (unsigned long)((tm*100/HZ)%100)
  ip += ssprintf(ibuf + ip, sizeof(ibuf) - ip,
        ", time %lu.%lue/%lu.%luu sec", sec(etm), sec(utm));
# undef sec
#endif /* NO_TIMES */
#ifndef NO_MEMINFO
  {
    struct mallinfo mi = mallinfo();
# define kb(x) ((mi.x + 512)>>10)
    ip += ssprintf(ibuf + ip, sizeof(ibuf) - ip,
          ", mem arena=%d free=%d mmap=%d Kb",
          kb(arena), kb(fordblks), kb(hblkhd));
# undef kb
  }
#endif /* NO_MEMINFO */
  dslog(LOG_INFO, 0, ibuf);

  check_expires();

  /* ok, (something) loaded. */

  if (do_fork) {
    /* here we should notify query-answering child (send SIGTERM to it),
     * and wait for it to complete.
     * Unfortunately at least on linux, the SIGTERM sometimes gets ignored
     * by the child process, so we're trying several times here, in a loop.
     */
    int s, n;
    fd_set fds;
    struct timeval tv;

    for(n = 1; ++n;) {
      if (kill(cpid, SIGTERM) != 0)
        dslog(LOG_WARNING, 0, "kill(qchild): %s", strerror(errno));
      FD_ZERO(&fds);
      FD_SET(cfd, &fds);
      tv.tv_sec = 0;
      tv.tv_usec = 500000;
      s = select(cfd+1, &fds, NULL, NULL, &tv);
      if (s > 0) break;
      dslog(LOG_WARNING, 0, "waiting for qchild process: %s, retrying",
            s ? strerror(errno) : "timeout");
    }
    ipc_read_stats(cfd);
    close(cfd);
    wait(&s);
  }

  return r;
}
コード例 #7
0
ファイル: NotesWriterDWI.cpp プロジェクト: goofwear/stepmania
static void WriteDWINotesField( RageFile &f, const Steps &out, int start )
{
	NoteData notedata;
	out.GetNoteData( notedata );
	NoteDataUtil::InsertHoldTails( notedata );

	const int iLastMeasure = int( notedata.GetLastBeat()/BEATS_PER_MEASURE );
	for( int m=0; m<=iLastMeasure; m++ )	// foreach measure
	{
		NoteType nt = NoteDataUtil::GetSmallestNoteTypeForMeasure( notedata, m );

		double fCurrentIncrementer = 0;
		switch( nt )
		{
		case NOTE_TYPE_4TH:
		case NOTE_TYPE_8TH:	
			fCurrentIncrementer = 1.0/8 * BEATS_PER_MEASURE;
			break;
		case NOTE_TYPE_12TH:
		case NOTE_TYPE_24TH:
			f.Write( "[" );
			fCurrentIncrementer = 1.0/24 * BEATS_PER_MEASURE;
			break;
		case NOTE_TYPE_16TH:
			f.Write( "(" );
			fCurrentIncrementer = 1.0/16 * BEATS_PER_MEASURE;
			break;
		case NOTE_TYPE_32ND:
		case NOTE_TYPE_64TH:
			f.Write( "{" );
			fCurrentIncrementer = 1.0/64 * BEATS_PER_MEASURE;
			break;
		case NOTE_TYPE_48TH:
		case NOTE_TYPE_192ND:
		case NoteType_Invalid:
			// since, for whatever reason, the only way to do
			// 48ths is through a block of 192nds...
			f.Write(  "`" );
			fCurrentIncrementer = 1.0/192 * BEATS_PER_MEASURE;
			break;
		default:
			ASSERT_M(0, ssprintf("nt = %d",nt) );
			break;
		}

		double fFirstBeatInMeasure = m * BEATS_PER_MEASURE;
		double fLastBeatInMeasure = (m+1) * BEATS_PER_MEASURE;

		for( double b=fFirstBeatInMeasure; b<=fLastBeatInMeasure-1/64.0f; b+=fCurrentIncrementer )	// need the -0.0001 to account for rounding errors
		{
			int row = BeatToNoteRow( (float)b );

			RString str;
			switch( out.m_StepsType )
			{
			case StepsType_dance_single:
			case StepsType_dance_couple:
			case StepsType_dance_double:
				str = NotesToDWIString( 
					notedata.GetTapNote(start+0, row), 
					notedata.GetTapNote(start+1, row),
					notedata.GetTapNote(start+2, row),
					notedata.GetTapNote(start+3, row) );

				// Blank out the notes so we don't write them again if the incrementer is small
				notedata.SetTapNote(start+0, row, TAP_EMPTY);
				notedata.SetTapNote(start+1, row, TAP_EMPTY);
				notedata.SetTapNote(start+2, row, TAP_EMPTY);
				notedata.SetTapNote(start+3, row, TAP_EMPTY);
				break;
			case StepsType_dance_solo:
				str = NotesToDWIString( 
					notedata.GetTapNote(0, row),
					notedata.GetTapNote(1, row),
					notedata.GetTapNote(2, row),
					notedata.GetTapNote(3, row),
					notedata.GetTapNote(4, row),
					notedata.GetTapNote(5, row) );

				// Blank out the notes so we don't write them again if the incrementer is small
				notedata.SetTapNote(start+0, row, TAP_EMPTY);
				notedata.SetTapNote(start+1, row, TAP_EMPTY);
				notedata.SetTapNote(start+2, row, TAP_EMPTY);
				notedata.SetTapNote(start+3, row, TAP_EMPTY);
				notedata.SetTapNote(start+4, row, TAP_EMPTY);
				notedata.SetTapNote(start+5, row, TAP_EMPTY);
				break;
			default:
				ASSERT(0);	// not a type supported by DWI.  We shouldn't have called in here if that's the case
			}
			f.Write( str );
		}

		switch( nt )
		{
		case NOTE_TYPE_4TH:
		case NOTE_TYPE_8TH:	
			break;
		case NOTE_TYPE_12TH:
		case NOTE_TYPE_24TH:
			f.Write( "]" );
			break;
		case NOTE_TYPE_16TH:
			f.Write( ")" );
			break;
		case NOTE_TYPE_32ND:
		case NOTE_TYPE_64TH:
			f.Write( "}" );
			break;
		case NOTE_TYPE_48TH:
		case NOTE_TYPE_192ND:
		case NoteType_Invalid:
			f.Write( "'" );
			break;
		default:
			ASSERT(0);
			// fall though
		}
		f.PutLine( "" );
	}
}
コード例 #8
0
ファイル: ScreenEnding.cpp プロジェクト: Fighter19/PSPMania
CString GetStatsLineValue( PlayerNumber pn, EndingStatsLine line )
{
	Profile* pProfile = PROFILEMAN->GetProfile( pn );
	ASSERT( pProfile );

	StepsType st = GAMESTATE->GetCurrentStyle()->m_StepsType;

	switch( line )
	{
	case CALORIES_TODAY:		return pProfile->GetDisplayTotalCaloriesBurnedToday();
	case CURRENT_COMBO:			return Commify( pProfile->m_iCurrentCombo );
	case PERCENT_COMPLETE:
		{
			float fActual = 0;
			float fPossible = 0;

			if( GAMESTATE->IsCourseMode() )
			{
				set<CourseDifficulty> vDiffs;
				GAMESTATE->GetCourseDifficultiesToShow( vDiffs );
				for( set<CourseDifficulty>::iterator iter = vDiffs.begin(); iter != vDiffs.end(); iter++ )
				{
					fActual += pProfile->GetCoursesActual(st,*iter);
					fPossible += pProfile->GetCoursesPossible(st,*iter);
				}
			}
			else
			{
				set<Difficulty> vDiffs;
				GAMESTATE->GetDifficultiesToShow( vDiffs );
				for( set<Difficulty>::iterator iter = vDiffs.begin(); iter != vDiffs.end(); iter++ )
				{
					fActual += pProfile->GetSongsActual(st,*iter);
					fPossible += pProfile->GetSongsPossible(st,*iter);
				}
			}

			return ssprintf( "%05.2f%%", fActual/fPossible*100 );
		}
	case PERCENT_COMPLETE_EASY:
	case PERCENT_COMPLETE_MEDIUM:
	case PERCENT_COMPLETE_HARD:
	case PERCENT_COMPLETE_CHALLENGE:
		// Ugly...
		{
			CString sStepsType = GAMEMAN->StepsTypeToThemedString(st);
			float fPercent = 0;
			if( GAMESTATE->IsCourseMode() )
			{
				CourseDifficulty cd = (CourseDifficulty)(DIFFICULTY_EASY+line-PERCENT_COMPLETE_EASY);
				ASSERT( cd >= 0 && cd < NUM_COURSE_DIFFICULTIES );
				if( !GAMESTATE->IsCourseDifficultyShown(cd) )
					return "";
//				CString sDifficulty = CourseDifficultyToThemedString(cd);
				fPercent = pProfile->GetCoursesPercentComplete(st,cd);
			}
			else
			{
				Difficulty dc = (Difficulty)(DIFFICULTY_EASY+line-PERCENT_COMPLETE_EASY);
				ASSERT( dc >= 0 && dc < NUM_DIFFICULTIES );
//				CString sDifficulty = DifficultyToThemedString(dc);
				fPercent = pProfile->GetSongsPercentComplete(st,dc);
			}
			return ssprintf( "%05.2f%%", fPercent*100 );
		}
	default:	ASSERT(0);	return "";
	}
}
コード例 #9
0
ファイル: cgroup01.c プロジェクト: 0x7f454c46/criu
int main(int argc, char **argv)
{
	int cgfd, l, ret = 1, i;
	char aux[1024], paux[1024];
	FILE *cgf;
	struct stat st;

	test_init(argc, argv);

	if (mkdir(dirname, 0700) < 0) {
		pr_perror("Can't make dir");
		goto out;
	}

	sprintf(aux, "none,name=%s", cgname);
	if (mount("none", dirname, "cgroup", 0, aux)) {
		pr_perror("Can't mount cgroups");
		goto out_rd;
	}

	sprintf(paux, "%s/%s", dirname, subname);
	mkdir(paux, 0600);

	l = sprintf(aux, "%d", getpid());
	sprintf(paux, "%s/%s/tasks", dirname, subname);

	cgfd = open(paux, O_WRONLY);
	if (cgfd < 0) {
		pr_perror("Can't open tasks");
		goto out_rs;
	}

	l = write(cgfd, aux, l);
	close(cgfd);

	if (l < 0) {
		pr_perror("Can't move self to subcg");
		goto out_rs;
	}

	for (i = 0; i < 2; i++) {
		sprintf(paux, "%s/%s/%s.%d", dirname, subname, empty, i);
		if (mkdir(paux, 0600)) {
			pr_perror("mkdir %s", paux);
			goto out_rs;
		}
	}

	test_daemon();
	test_waitsig();

	cgf = fopen("/proc/self/mountinfo", "r");
	if (cgf == NULL) {
		fail("No mountinfo file");
		goto out_rs;
	}

	while (fgets(paux, sizeof(paux), cgf)) {
		char *s;

		s = strstr(paux, cgname);
		if (!s)
			continue;

		sscanf(paux, "%*d %*d %*d:%*d %*s %s", aux);
		test_msg("found cgroup at %s\n", aux);

		for (i = 0; i < 2; i++) {
			ssprintf(paux, "%s/%s/%s.%d", aux, subname, empty, i);

			if (stat(paux, &st)) {
				fail("couldn't stat %s\n", paux);
				ret = -1;
				goto out_close;
			}

			if (!S_ISDIR(st.st_mode)) {
				fail("%s is not a directory\n", paux);
				ret = -1;
				goto out_close;
			}
		}

		pass();
		ret = 0;
		goto out_close;
	}

	fail("empty cgroup not found!\n");

out_close:
	fclose(cgf);
out_rs:
	umount(dirname);
out_rd:
	rmdir(dirname);
out:
	return ret;
}
コード例 #10
0
ファイル: levels.cpp プロジェクト: ik3210/warzone2100
// load up the data for a level
bool levLoadData(char const *name, Sha256 const *hash, char *pSaveName, GAME_TYPE saveType)
{
	LEVEL_DATASET	*psNewLevel, *psBaseData, *psChangeLevel;
	bool            bCamChangeSaveGame;

	debug(LOG_WZ, "Loading level %s hash %s (%s, type %d)", name, hash == nullptr ? "builtin" : hash->toString().c_str(), pSaveName, (int)saveType);
	if (saveType == GTYPE_SAVE_START || saveType == GTYPE_SAVE_MIDMISSION)
	{
		if (!levReleaseAll())
		{
			debug(LOG_ERROR, "Failed to unload old data");
			return false;
		}
	}

	levelLoadType = saveType;

	// find the level dataset
	psNewLevel = levFindDataSet(name, hash);
	if (psNewLevel == nullptr)
	{
		debug(LOG_INFO, "Dataset %s not found - trying to load as WRF", name);
		return levLoadSingleWRF(name);
	}
	debug(LOG_WZ, "** Data set found is %s type %d", psNewLevel->pName, (int)psNewLevel->type);

	/* Keep a copy of the present level name */
	sstrcpy(currentLevelName, name);

	bCamChangeSaveGame = false;
	if (pSaveName && saveType == GTYPE_SAVE_START)
	{
		if (psNewLevel->psChange != nullptr)
		{
			bCamChangeSaveGame = true;
			debug(LOG_WZ, "** CAMCHANGE FOUND");
		}
	}

	// select the change dataset if there is one
	psChangeLevel = nullptr;
	if (((psNewLevel->psChange != nullptr) && (psCurrLevel != nullptr)) || bCamChangeSaveGame)
	{
		//store the level name
		debug(LOG_WZ, "Found CAMCHANGE dataset");
		psChangeLevel = psNewLevel;
		psNewLevel = psNewLevel->psChange;
	}

	// ensure the correct dataset is loaded
	if (psNewLevel->type == LDS_CAMPAIGN)
	{
		debug(LOG_ERROR, "Cannot load a campaign dataset (%s)", psNewLevel->pName);
		return false;
	}
	else
	{
		if (psCurrLevel != nullptr)
		{
			if ((psCurrLevel->psBaseData != psNewLevel->psBaseData) ||
			    (psCurrLevel->type < LDS_NONE && psNewLevel->type  >= LDS_NONE) ||
			    (psCurrLevel->type >= LDS_NONE && psNewLevel->type  < LDS_NONE))
			{
				// there is a dataset loaded but it isn't the correct one
				debug(LOG_WZ, "Incorrect base dataset loaded (%p != %p, %d - %d)",
				      psCurrLevel->psBaseData, psNewLevel->psBaseData, (int)psCurrLevel->type, (int)psNewLevel->type);
				if (!levReleaseAll())	// this sets psCurrLevel to NULL
				{
					debug(LOG_ERROR, "Failed to release old data");
					return false;
				}
			}
			else
			{
				debug(LOG_WZ, "Correct base dataset already loaded.");
			}
		}

		// setup the correct dataset to load if necessary
		if (psCurrLevel == nullptr)
		{
			if (psNewLevel->psBaseData != nullptr)
			{
				debug(LOG_WZ, "Setting base dataset to load: %s", psNewLevel->psBaseData->pName);
			}
			psBaseData = psNewLevel->psBaseData;
		}
		else
		{
			debug(LOG_WZ, "No base dataset to load");
			psBaseData = nullptr;
		}
	}

	if (!rebuildSearchPath(psNewLevel->dataDir, true, psNewLevel->realFileName))
	{
		debug(LOG_ERROR, "Failed to rebuild search path");
		return false;
	}

	// reset the old mission data if necessary
	if (psCurrLevel != nullptr)
	{
		debug(LOG_WZ, "Reseting old mission data");
		if (!levReleaseMissionData())
		{
			debug(LOG_ERROR, "Failed to unload old mission data");
			return false;
		}
	}

	// need to free the current map and droids etc for a save game
	if (psBaseData == nullptr && pSaveName != nullptr)
	{
		if (!saveGameReset())
		{
			debug(LOG_ERROR, "Failed to saveGameReset()!");
			return false;
		}
	}

	// initialise if necessary
	if (psNewLevel->type == LDS_COMPLETE || psBaseData != nullptr)
	{
		debug(LOG_WZ, "Calling stageOneInitialise!");
		if (!stageOneInitialise())
		{
			debug(LOG_ERROR, "Failed stageOneInitialise!");
			return false;
		}
	}

	// load up a base dataset if necessary
	if (psBaseData != nullptr)
	{
		debug(LOG_WZ, "Loading base dataset %s", psBaseData->pName);
		for (int i = 0; i < LEVEL_MAXFILES; i++)
		{
			if (psBaseData->apDataFiles[i])
			{
				// load the data
				debug(LOG_WZ, "Loading [directory: %s] %s ...", PHYSFS_getRealDir(psBaseData->apDataFiles[i]), psBaseData->apDataFiles[i]);
				if (!resLoad(psBaseData->apDataFiles[i], i))
				{
					debug(LOG_ERROR, "Failed resLoad(%s)!", psBaseData->apDataFiles[i]);
					return false;
				}
			}
		}
	}
	if (psNewLevel->type == LDS_CAMCHANGE)
	{
		if (!campaignReset())
		{
			debug(LOG_ERROR, "Failed campaignReset()!");
			return false;
		}
	}
	if (psNewLevel->game == -1)  //no .gam file to load - BETWEEN missions (for Editor games only)
	{
		ASSERT(psNewLevel->type == LDS_BETWEEN, "Only BETWEEN missions do not need a .gam file");
		debug(LOG_WZ, "No .gam file for level: BETWEEN mission");
		if (pSaveName != nullptr)
		{
			if (psBaseData != nullptr)
			{
				if (!stageTwoInitialise())
				{
					debug(LOG_ERROR, "Failed stageTwoInitialise()!");
					return false;
				}
			}

			//set the mission type before the saveGame data is loaded
			if (saveType == GTYPE_SAVE_MIDMISSION)
			{
				debug(LOG_WZ, "Init mission stuff");
				if (!startMissionSave(psNewLevel->type))
				{
					debug(LOG_ERROR, "Failed startMissionSave(%d)!", psNewLevel->type);
					return false;
				}

				debug(LOG_NEVER, "dataSetSaveFlag");
				dataSetSaveFlag();
			}

			debug(LOG_NEVER, "Loading savegame: %s", pSaveName);
			if (!loadGame(pSaveName, false, true, true))
			{
				debug(LOG_ERROR, "Failed loadGame(%s)!", pSaveName);
				return false;
			}
		}

		if (pSaveName == nullptr || saveType == GTYPE_SAVE_START)
		{
			debug(LOG_NEVER, "Start mission - no .gam");
			if (!startMission((LEVEL_TYPE)psNewLevel->type, nullptr))
			{
				debug(LOG_ERROR, "Failed startMission(%d)!", psNewLevel->type);
				return false;
			}
		}
	}

	//we need to load up the save game data here for a camchange
	if (bCamChangeSaveGame)
	{
		if (pSaveName != nullptr)
		{
			if (psBaseData != nullptr)
			{
				if (!stageTwoInitialise())
				{
					debug(LOG_ERROR, "Failed stageTwoInitialise() [camchange]!");
					return false;
				}
			}

			debug(LOG_NEVER, "loading savegame: %s", pSaveName);
			if (!loadGame(pSaveName, false, true, true))
			{
				debug(LOG_ERROR, "Failed loadGame(%s)!", pSaveName);
				return false;
			}

			campaignReset();
		}
	}


	// load the new data
	debug(LOG_NEVER, "Loading mission dataset: %s", psNewLevel->pName);
	for (int i = 0; i < LEVEL_MAXFILES; i++)
	{
		if (psNewLevel->game == i)
		{
			// do some more initialising if necessary
			if (psNewLevel->type == LDS_COMPLETE || psNewLevel->type >= LDS_MULTI_TYPE_START || (psBaseData != nullptr && !bCamChangeSaveGame))
			{
				if (!stageTwoInitialise())
				{
					debug(LOG_ERROR, "Failed stageTwoInitialise() [newdata]!");
					return false;
				}
			}

			// load a savegame if there is one - but not if already done so
			if (pSaveName != nullptr && !bCamChangeSaveGame)
			{
				//set the mission type before the saveGame data is loaded
				if (saveType == GTYPE_SAVE_MIDMISSION)
				{
					debug(LOG_WZ, "Init mission stuff");
					if (!startMissionSave(psNewLevel->type))
					{
						debug(LOG_ERROR, "Failed startMissionSave(%d)!", psNewLevel->type);
						return false;
					}

					debug(LOG_NEVER, "dataSetSaveFlag");
					dataSetSaveFlag();
				}

				debug(LOG_NEVER, "Loading save game %s", pSaveName);
				if (!loadGame(pSaveName, false, true, true))
				{
					debug(LOG_ERROR, "Failed loadGame(%s)!", pSaveName);
					return false;
				}
			}

			if (pSaveName == nullptr || saveType == GTYPE_SAVE_START)
			{
				// load the game
				debug(LOG_WZ, "Loading scenario file %s", psNewLevel->apDataFiles[i]);
				switch (psNewLevel->type)
				{
				case LDS_COMPLETE:
				case LDS_CAMSTART:
					debug(LOG_WZ, "LDS_COMPLETE / LDS_CAMSTART");
					if (!startMission(LDS_CAMSTART, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_CAMSTART, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				case LDS_BETWEEN:
					debug(LOG_WZ, "LDS_BETWEEN");
					if (!startMission(LDS_BETWEEN, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_BETWEEN, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;

				case LDS_MKEEP:
					debug(LOG_WZ, "LDS_MKEEP");
					if (!startMission(LDS_MKEEP, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_MKEEP, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				case LDS_CAMCHANGE:
					debug(LOG_WZ, "LDS_CAMCHANGE");
					if (!startMission(LDS_CAMCHANGE, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_CAMCHANGE, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;

				case LDS_EXPAND:
					debug(LOG_WZ, "LDS_EXPAND");
					if (!startMission(LDS_EXPAND, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_EXPAND, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				case LDS_EXPAND_LIMBO:
					debug(LOG_WZ, "LDS_LIMBO");
					if (!startMission(LDS_EXPAND_LIMBO, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_EXPAND_LIMBO, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;

				case LDS_MCLEAR:
					debug(LOG_WZ, "LDS_MCLEAR");
					if (!startMission(LDS_MCLEAR, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_MCLEAR, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				case LDS_MKEEP_LIMBO:
					debug(LOG_WZ, "LDS_MKEEP_LIMBO");
					if (!startMission(LDS_MKEEP_LIMBO, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s)!", LDS_MKEEP_LIMBO, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				default:
					ASSERT(psNewLevel->type >= LDS_MULTI_TYPE_START, "Unexpected mission type");
					debug(LOG_WZ, "default (MULTIPLAYER)");
					if (!startMission(LDS_CAMSTART, psNewLevel->apDataFiles[i]))
					{
						debug(LOG_ERROR, "Failed startMission(%d, %s) (default)!", LDS_CAMSTART, psNewLevel->apDataFiles[i]);
						return false;
					}
					break;
				}
			}
		}
		else if (psNewLevel->apDataFiles[i])
		{
			// load the data
			debug(LOG_WZ, "Loading %s", psNewLevel->apDataFiles[i]);
			if (!resLoad(psNewLevel->apDataFiles[i], i + CURRENT_DATAID))
			{
				debug(LOG_ERROR, "Failed resLoad(%s, %d) (default)!", psNewLevel->apDataFiles[i], i + CURRENT_DATAID);
				return false;
			}
		}
	}

	if (bMultiPlayer)
	{
		// This calls resLoadFile("SMSG", "multiplay.txt"). Must be before loadMissionExtras, which calls loadSaveMessage, which calls getViewData.
		loadMultiScripts();
	}

	if (pSaveName != nullptr)
	{
		//load MidMission Extras
		if (!loadMissionExtras(pSaveName, psNewLevel->type))
		{
			debug(LOG_ERROR, "Failed loadMissionExtras(%s, %d)!", pSaveName, psNewLevel->type);
			return false;
		}
	}

	if (pSaveName != nullptr && saveType == GTYPE_SAVE_MIDMISSION)
	{
		//load script stuff
		// load the event system state here for a save game
		debug(LOG_SAVE, "Loading script system state");
		if (!loadScriptState(pSaveName))
		{
			debug(LOG_ERROR, "Failed loadScriptState(%s)!", pSaveName);
			return false;
		}
	}

	if (!stageThreeInitialise())
	{
		debug(LOG_ERROR, "Failed stageThreeInitialise()!");
		return false;
	}

	dataClearSaveFlag();

	//this enables us to to start cam2/cam3 without going via a save game and get the extra droids
	//in from the script-controlled Transporters
	if (!pSaveName && psNewLevel->type == LDS_CAMSTART)
	{
		eventFireCallbackTrigger((TRIGGER_TYPE)CALL_NO_REINFORCEMENTS_LEFT);
	}

	//restore the level name for comparisons on next mission load up
	if (psChangeLevel == nullptr)
	{
		psCurrLevel = psNewLevel;
	}
	else
	{
		psCurrLevel = psChangeLevel;
	}

	// Copy this info to be used by the crash handler for the dump file
	char buf[256];

	ssprintf(buf, "Current Level/map is %s", psCurrLevel->pName);
	addDumpInfo(buf);

	triggerEvent(TRIGGER_GAME_LOADED);

	if (autogame_enabled())
	{
		gameTimeSetMod(Rational(500));
		if (hostlaunch != 2) // tests will specify the AI manually
		{
			jsAutogameSpecific("multiplay/skirmish/semperfi.js", selectedPlayer);
		}
	}

	return true;
}
コード例 #11
0
ファイル: ScreenEnding.cpp プロジェクト: Fighter19/PSPMania
ScreenEnding::ScreenEnding( const CString &sClassName ) : ScreenAttract( sClassName, false/*dont reset GAMESTATE*/ )
{
	if( PREFSMAN->m_bScreenTestMode )
	{
		PROFILEMAN->LoadFirstAvailableProfile(PLAYER_1);
		PROFILEMAN->LoadFirstAvailableProfile(PLAYER_2);

		GAMESTATE->m_PlayMode = PLAY_MODE_REGULAR;
		GAMESTATE->m_pCurStyle = GAMEMAN->GameAndStringToStyle( GAMEMAN->GetDefaultGame(), "versus" );
		GAMESTATE->m_bSideIsJoined[PLAYER_1] = true;
		GAMESTATE->m_bSideIsJoined[PLAYER_2] = true;
		GAMESTATE->m_MasterPlayerNumber = PLAYER_1;
		GAMESTATE->m_pCurSong = SONGMAN->GetRandomSong();
		GAMESTATE->m_pCurCourse = SONGMAN->GetRandomCourse();
		GAMESTATE->m_pCurSteps[PLAYER_1] = GAMESTATE->m_pCurSong->GetAllSteps()[0];
		GAMESTATE->m_pCurSteps[PLAYER_2] = GAMESTATE->m_pCurSong->GetAllSteps()[0];
		g_CurStageStats.vpSteps[PLAYER_1].push_back( GAMESTATE->m_pCurSteps[PLAYER_1] );
		g_CurStageStats.vpSteps[PLAYER_2].push_back( GAMESTATE->m_pCurSteps[PLAYER_2] );
		GAMESTATE->m_PlayerOptions[PLAYER_1].m_fScrollSpeed = 2;
		GAMESTATE->m_PlayerOptions[PLAYER_2].m_fScrollSpeed = 2;
		GAMESTATE->m_iCurrentStageIndex = 0;
		GAMESTATE->m_PlayerOptions[PLAYER_1].ChooseRandomMofifiers();
		GAMESTATE->m_PlayerOptions[PLAYER_2].ChooseRandomMofifiers();

		for( float f = 0; f < 100.0f; f += 1.0f )
		{
			float fP1 = fmodf(f/100*4+.3f,1);
			g_CurStageStats.SetLifeRecordAt( PLAYER_1, fP1, f );
			g_CurStageStats.SetLifeRecordAt( PLAYER_2, 1-fP1, f );
		}
	
		g_CurStageStats.iActualDancePoints[PLAYER_1] = rand()%3;
		g_CurStageStats.iPossibleDancePoints[PLAYER_1] = 2;
		g_CurStageStats.iActualDancePoints[PLAYER_2] = rand()&1;
		g_CurStageStats.iPossibleDancePoints[PLAYER_2] = 1;
		g_CurStageStats.iCurCombo[PLAYER_1] = 0;
		g_CurStageStats.UpdateComboList( PLAYER_1, 0, false );
		g_CurStageStats.iCurCombo[PLAYER_1] = 1;
		g_CurStageStats.UpdateComboList( PLAYER_1, 1, false );
		g_CurStageStats.iCurCombo[PLAYER_1] = 50;
		g_CurStageStats.UpdateComboList( PLAYER_1, 25, false );
		g_CurStageStats.iCurCombo[PLAYER_1] = 250;
		g_CurStageStats.UpdateComboList( PLAYER_1, 100, false );

		g_CurStageStats.iTapNoteScores[PLAYER_1][TNS_MARVELOUS] = rand()&1;
		g_CurStageStats.iTapNoteScores[PLAYER_1][TNS_PERFECT] = rand()&1;
		g_CurStageStats.iTapNoteScores[PLAYER_1][TNS_GREAT] = rand()&1;
		g_CurStageStats.iTapNoteScores[PLAYER_2][TNS_MARVELOUS] = rand()&1;
		g_CurStageStats.iTapNoteScores[PLAYER_2][TNS_PERFECT] = rand()&1;
		g_CurStageStats.iTapNoteScores[PLAYER_2][TNS_GREAT] = rand()&1;

		g_vPlayedStageStats.clear();
	}


	// Update final profile stats before we load them for display below.
	GAMESTATE->FinishStage();


	vector<Song*> arraySongs;
	SONGMAN->GetSongs( arraySongs );
	SongUtil::SortSongPointerArrayByTitle( arraySongs );

	const CString sStatsTitleFont = THEME->GetPathToF( "ScreenEnding stats title" );
	const CString sStatsValueFont = THEME->GetPathToF( "ScreenEnding stats value" );
	FOREACH_PlayerNumber( p )
	{
		if( !GAMESTATE->IsHumanPlayer(p) )
			continue;	// skip

		Profile* pProfile = PROFILEMAN->GetProfile( p );

		m_textPlayerName[p].LoadFromFont( THEME->GetPathToF("ScreenEnding player name") );
		m_textPlayerName[p].SetText( pProfile ? pProfile->GetDisplayName() : CString("NO CARD") );
		m_textPlayerName[p].SetName( ssprintf("PlayerNameP%d",p+1) );
		SET_XY_AND_ON_COMMAND( m_textPlayerName[p] );
		this->AddChild( &m_textPlayerName[p] );

		if( pProfile == NULL )
			continue;	// don't show the stats lines
	
		FOREACH_EndingStatsLine( i )
		{
			m_Lines[i][p].title.LoadFromFont( sStatsTitleFont );
			m_Lines[i][p].title.SetText( GetStatsLineTitle(p, i) );
			m_Lines[i][p].title.SetName( ssprintf("StatsTitleP%dLine%d",p+1,i+1) );
			SET_XY_AND_ON_COMMAND( m_Lines[i][p].title );
			this->AddChild( &m_Lines[i][p].title );
		
			m_Lines[i][p].value.LoadFromFont( sStatsValueFont );
			m_Lines[i][p].value.SetText( GetStatsLineValue(p, i) );
			m_Lines[i][p].value.SetName( ssprintf("StatsValueP%dLine%d",p+1,i+1) );
			SET_XY_AND_ON_COMMAND( m_Lines[i][p].value );
			this->AddChild( &m_Lines[i][p].value );
		}
	}

	
	this->MoveToTail( &m_In );		// put it in the back so it covers up the stuff we just added
	this->MoveToTail( &m_Out );		// put it in the back so it covers up the stuff we just added

	SOUND->PlayOnceFromDir( ANNOUNCER->GetPathTo("music scroll") );

	// Now that we've read the data from the profile, it's ok to Reset()
	GAMESTATE->Reset();

	float fSecsUntilBeginFadingOut = m_Background.GetLengthSeconds() - m_Out.GetLengthSeconds();
	if( fSecsUntilBeginFadingOut < 0 )
	{
		LOG->Warn( "Screen '%s' Out BGAnimation (%f seconds) is longer than Background BGAnimation (%f seconds); background BGA will be truncated",
			m_sName.c_str(), m_Out.GetLengthSeconds(), m_Background.GetLengthSeconds() );
		fSecsUntilBeginFadingOut = 0;
	}
	this->PostScreenMessage( SM_BeginFadingOut, fSecsUntilBeginFadingOut );
}
コード例 #12
0
EditCoursesMenu::EditCoursesMenu()
{
	LOG->Trace( "ScreenEditCoursesMenu::ScreenEditCoursesMenu()" );

	GAMESTATE->m_bEditing = true;

	m_bInSongMenu = false;

	int i;

	for( i=0; i<2; i++ )
	{
		m_sprArrows[i].Load( THEME->GetPathToG(ssprintf("EditCoursesMenu %s",(i==0?"left":"right"))) );
		m_sprArrows[i].SetX( ARROWS_X(i) );
		this->AddChild( &m_sprArrows[i] );
	}

	m_SelectedRow = (Row)0;

	ZERO( m_iSelection );

	const CString sTitleFontPath = THEME->GetPathToF( "Common title" );
	const CString sNormalFontPath = THEME->GetPathToF( "Common normal" );
	const float fRowLabelsX = ROW_LABELS_X;
	for( i=0; i<NUM_ROWS; i++ )
	{
		const float fRowY = ROW_Y(i);

		m_textLabel[i].LoadFromFont( sTitleFontPath );
		m_textLabel[i].SetXY( fRowLabelsX, fRowY );
		m_textLabel[i].SetText( RowToString((Row)i) );
		m_textLabel[i].SetZoom( 0.8f );
		m_textLabel[i].SetHorizAlign( Actor::align_left );
		this->AddChild( &m_textLabel[i] );

		m_textValue[i].LoadFromFont( sNormalFontPath );
		m_textValue[i].SetXY( ROW_VALUE_X(i), fRowY );
		m_textValue[i].SetText( "blah" );
		m_textValue[i].SetZoom( 0.6f );
		this->AddChild( &m_textValue[i] );
	}

	m_CourseBanner.SetXY( COURSE_BANNER_X, COURSE_BANNER_Y );
	this->AddChild( &m_CourseBanner );

	m_EntryBanner.SetXY( ENTRY_BANNER_X, ENTRY_BANNER_Y );
	this->AddChild( &m_EntryBanner );

	m_EntryTextBanner.SetName( "TextBanner" );
	m_EntryTextBanner.SetXY( ENTRY_TEXT_BANNER_X, ENTRY_TEXT_BANNER_Y );
	this->AddChild( &m_EntryTextBanner );
	

	m_soundChangeRow.Load( THEME->GetPathToS("EditCoursesMenu row") );
	m_soundChangeValue.Load( THEME->GetPathToS("EditCoursesMenu value") );
	m_soundSave.Load( THEME->GetPathToS("EditCoursesMenu save") );


	// fill in data structures
	SONGMAN->GetAllCourses( m_pCourses, false );
	
	ChangeToRow( (Row)0 );
	OnRowValueChanged( (Row)0 );
}
コード例 #13
0
void EditCoursesMenu::OnRowValueChanged( Row row )
{
	LOG->Trace( "EditCoursesMenu::OnRowValueChanged(%i)", row );

	const bool bCanGoLeft = CanGoLeft(), bCanGoRight = CanGoRight();
	m_sprArrows[0].SetDiffuse( bCanGoLeft?RageColor(1,1,1,1):RageColor(0.2f,0.2f,0.2f,1) );
	m_sprArrows[1].SetDiffuse( bCanGoRight?RageColor(1,1,1,1):RageColor(0.2f,0.2f,0.2f,1) );
	m_sprArrows[0].EnableAnimation( bCanGoLeft );
	m_sprArrows[1].EnableAnimation( bCanGoRight );

	Course* pCourse = GetSelectedCourse();
	CourseEntry* pEntry = GetSelectedEntry();

	switch( row )
	{
	case ROW_COURSE:
		CHECKPOINT;
		m_textValue[ROW_COURSE].SetText( pCourse->GetFullDisplayTitle() );
		m_CourseBanner.LoadFromCourse( pCourse );
		m_CourseBanner.ScaleToClipped( COURSE_BANNER_WIDTH, COURSE_BANNER_HEIGHT );
		m_iSelection[ROW_ENTRY] = 0;
		pEntry = GetSelectedEntry();
		if( pEntry == NULL )
		{
			CourseEntry ce;
			const vector<Song*> &apSongs = SONGMAN->GetAllSongs();
			ASSERT( !apSongs.empty() );
			ce.pSong = apSongs[0];
			pCourse->m_entries.push_back( ce );
			pEntry = GetSelectedEntry();
		}
		// fall through
	case ROW_COURSE_OPTIONS:
		CHECKPOINT;
		m_textValue[ROW_COURSE_OPTIONS].SetText( 
			ssprintf(
				"(START)  %s, %s, ",
				pCourse->m_bRepeat ? "repeat" : "no repeat",
				pCourse->m_bRandomize ? "randomize" : "no randomize" ) + 
			ssprintf(
				(pCourse->m_iLives==-1) ? "use bar life" : "%d lives",
				pCourse->m_iLives ) );
		// fall through
	case ROW_ACTION:
		CHECKPOINT;
		m_textValue[ROW_ACTION].SetText( "(START) " + ActionToString(GetSelectedAction()) );
		// fall through
	case ROW_ENTRY:
		CHECKPOINT;
		m_textValue[ROW_ENTRY].SetText( ssprintf("%d of %d",m_iSelection[ROW_ENTRY]+1, (int)GetSelectedCourse()->m_entries.size()) );
		m_iSelection[ROW_ENTRY_TYPE] = pEntry->type;
		// fall through
	case ROW_ENTRY_TYPE:
		CHECKPOINT;
		m_textValue[ROW_ENTRY_TYPE].SetText( pEntry ? CourseEntryTypeToString(pEntry->type) : CString("(none)") );
		// fall through
	case ROW_ENTRY_OPTIONS:
		CHECKPOINT;
		{
			CStringArray as;
			const bool *bShow = g_bRowEnabledForType[GetSelectedEntry()->type];

			if( bShow[song] )
				as.push_back( pEntry->pSong ? pEntry->pSong->GetFullTranslitTitle() : CString("(missing song)") );
			if( bShow[group] )
				as.push_back( pEntry->group_name.empty() ? CString("(no group)") : pEntry->group_name );
			if( bShow[difficulty] )
				if( pEntry->difficulty != DIFFICULTY_INVALID )
					as.push_back( DifficultyToString(pEntry->difficulty) );
			if( bShow[low_meter] )
				if( pEntry->low_meter > 0 )
					as.push_back( ssprintf("low meter %d", pEntry->low_meter) );
			if( bShow[high_meter] )
				if( pEntry->high_meter > 0 )
					as.push_back( ssprintf("high meter %d", pEntry->high_meter) );
			if( bShow[best_worst_value] )
				if( pEntry->players_index != -1 )
					as.push_back( ssprintf("rank %d", pEntry->players_index+1) );

			m_textValue[ROW_ENTRY_OPTIONS].SetText( "(START) " + join(", ",as) );
		}
		// fall through
	case ROW_ENTRY_PLAYER_OPTIONS:
		CHECKPOINT;
		{
			CString s = "(START) ";
		
			PlayerOptions po;
			po.FromString( pEntry->modifiers );
			if( po.GetString().empty() )
				s += "(none)";
			else
				s += po.GetString();
		
			m_textValue[ROW_ENTRY_PLAYER_OPTIONS].SetText( s );
		}
		// fall through
	case ROW_ENTRY_SONG_OPTIONS:
		CHECKPOINT;
		{
			CString s = "(START) ";

			SongOptions so;
			so.FromString( pEntry->modifiers );
			if( so.GetString().empty() )
				s += "(none)";
			else
				s += so.GetString();

			m_textValue[ROW_ENTRY_SONG_OPTIONS].SetText( s );
		}
		break;
	default:
		ASSERT(0);	// invalid row
	}
}
コード例 #14
0
ファイル: main.cpp プロジェクト: Rimbok/warzone2100
int main(int argc, char *argv[])
{
	QApplication app(argc, argv);
	int utfargc = argc;
	const char** utfargv = (const char**)argv;

#ifdef WZ_OS_MAC
	cocoaInit();
#endif

	debug_init();
	debug_register_callback( debug_callback_stderr, NULL, NULL, NULL );
#if defined(WZ_OS_WIN) && defined(DEBUG_INSANE)
	debug_register_callback( debug_callback_win32debug, NULL, NULL, NULL );
#endif // WZ_OS_WIN && DEBUG_INSANE

	// *****
	// NOTE: Try *NOT* to use debug() output routines without some other method of informing the user.  All this output is sent to /dev/nul at this point on some platforms!
	// *****
	if (!getUTF8CmdLine(&utfargc, &utfargv))
	{
		return EXIT_FAILURE;
	}
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));	// make Qt treat all C strings in Warzone as UTF-8

	setupExceptionHandler(utfargc, utfargv, version_getFormattedVersionString());

	/*** Initialize PhysicsFS ***/
	initialize_PhysicsFS(utfargv[0]);

	/*** Initialize translations ***/
	initI18n();

	// find early boot info
	if (!ParseCommandLineEarly(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	/* Initialize the write/config directory for PhysicsFS.
	 * This needs to be done __after__ the early commandline parsing,
	 * because the user might tell us to use an alternative configuration
	 * directory.
	 */
	initialize_ConfigDir();

	/*** Initialize directory structure ***/
	make_dir(ScreenDumpPath, "screenshots", NULL);
	make_dir(SaveGamePath, "savegames", NULL);
	make_dir(MultiCustomMapsPath, "maps", NULL); // MUST have this to prevent crashes when getting map
	PHYSFS_mkdir("music");
	PHYSFS_mkdir("logs");		// a place to hold our netplay, mingw crash reports & WZ logs
	make_dir(MultiPlayersPath, "multiplay", NULL);
	make_dir(MultiPlayersPath, "multiplay", "players");

	if (!customDebugfile)
	{
		// there was no custom debug file specified  (--debug-file=blah)
		// so we use our write directory to store our logs.
		time_t aclock;
		struct tm *newtime;
		char buf[PATH_MAX];

		time( &aclock );					// Get time in seconds
		newtime = localtime( &aclock );		// Convert time to struct
		// Note: We are using fopen(), and not physfs routines to open the file
		// log name is logs/(or \)WZlog-MMDD_HHMMSS.txt
		snprintf(buf, sizeof(buf), "%slogs%sWZlog-%02d%02d_%02d%02d%02d.txt", PHYSFS_getWriteDir(), PHYSFS_getDirSeparator(),
			newtime->tm_mon, newtime->tm_mday, newtime->tm_hour, newtime->tm_min, newtime->tm_sec );
		debug_register_callback( debug_callback_file, debug_callback_file_init, debug_callback_file_exit, buf );
	}

	// NOTE: it is now safe to use debug() calls to make sure output gets captured.
	check_Physfs();
	debug(LOG_WZ, "Warzone 2100 - %s", version_getFormattedVersionString());
	debug(LOG_WZ, "Using language: %s", getLanguage());
	debug(LOG_MEMORY, "sizeof: SIMPLE_OBJECT=%ld, BASE_OBJECT=%ld, DROID=%ld, STRUCTURE=%ld, FEATURE=%ld, PROJECTILE=%ld",
	      (long)sizeof(SIMPLE_OBJECT), (long)sizeof(BASE_OBJECT), (long)sizeof(DROID), (long)sizeof(STRUCTURE), (long)sizeof(FEATURE), (long)sizeof(PROJECTILE));


	/* Put in the writedir root */
	sstrcpy(KeyMapPath, "keymap.map");

	// initialise all the command line states
	war_SetDefaultStates();

	debug(LOG_MAIN, "initializing");

	PhysicsEngineHandler engine;	// register abstract physfs filesystem

	loadConfig();

	// parse the command line
	if (!ParseCommandLine(utfargc, utfargv))
	{
		return EXIT_FAILURE;
	}

	// Save new (commandline) settings
	saveConfig();

	// Find out where to find the data
	scanDataDirs();

	// This needs to be done after "scanDataDirs"
	// for the root cert from cacert.
	NETinit(true);

	// Must be run before OpenGL driver is properly initialized due to
	// strange conflicts - Per
	if (selfTest)
	{
		memset(enabled_debug, 0, sizeof(*enabled_debug) * LOG_LAST);
		fprintf(stdout, "Carrying out self-test:\n");
		playListTest();
		audioTest();
		soundTest();
	}

	// Now we check the mods to see if they exist or not (specified on the command line)
	// They are all capped at 100 mods max(see clparse.c)
	// FIX ME: I know this is a bit hackish, but better than nothing for now?
	{
		char *modname;
		char modtocheck[256];
		int i = 0;
		int result = 0;

		// check global mods
		for(i=0; i < 100; i++)
		{
			modname = global_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/global/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The (global) mod (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("(global) mod (%s) is enabled", modname);
			}
		}
		// check campaign mods
		for(i=0; i < 100; i++)
		{
			modname = campaign_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/campaign/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_ca (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_ca (%s) is enabled", modname);
			}
		}
		// check multiplay mods
		for(i=0; i < 100; i++)
		{
			modname = multiplay_mods[i];
			if (modname == NULL)
			{
				break;
			}
			ssprintf(modtocheck, "mods/multiplay/%s", modname);
			result = PHYSFS_exists(modtocheck);
			result |= PHYSFS_isDirectory(modtocheck);
			if (!result)
			{
				debug(LOG_ERROR, "The mod_mp (%s) you have specified doesn't exist!", modname);
			}
			else
			{
				info("mod_mp (%s) is enabled", modname);
			}
		}
	}

	debug(LOG_MAIN, "Qt initialization");
	QGL::setPreferredPaintEngine(QPaintEngine::OpenGL); // Workaround for incorrect text rendering on nany platforms.

	// Setting up OpenGL
	QGLFormat format;
	format.setDoubleBuffer(true);
	format.setAlpha(true);
	int w = pie_GetVideoBufferWidth();
	int h = pie_GetVideoBufferHeight();

	if (war_getFSAA())
	{
		format.setSampleBuffers(true);
		format.setSamples(war_getFSAA());
	}
	WzMainWindow mainwindow(QSize(w, h), format);
	mainwindow.setMinimumResolution(QSize(800, 600));
	if (!mainwindow.context()->isValid())
	{
		QMessageBox::critical(NULL, "Oops!", "Warzone2100 failed to create an OpenGL context. This probably means that your graphics drivers are out of date. Try updating them!");
		return EXIT_FAILURE;
	}

	screenWidth = w;
	screenHeight = h;
	if (war_getFullscreen())
	{
		mainwindow.resize(w,h);
		mainwindow.showFullScreen();
		if(w>mainwindow.width()) {
			w = mainwindow.width();
		}
		if(h>mainwindow.height()) {
			h = mainwindow.height();
		}
		pie_SetVideoBufferWidth(w);
		pie_SetVideoBufferHeight(h);
	}
	else
	{
		mainwindow.show();
		mainwindow.setMinimumSize(w, h);
		mainwindow.setMaximumSize(w, h);
	}

	mainwindow.setSwapInterval(war_GetVsync());
	war_SetVsync(mainwindow.swapInterval() > 0);

	mainwindow.setReadyToPaint();

	char buf[256];
	ssprintf(buf, "Video Mode %d x %d (%s)", w, h, war_getFullscreen() ? "fullscreen" : "window");
	addDumpInfo(buf);

	debug(LOG_MAIN, "Final initialization");
	if (!frameInitialise())
	{
		return EXIT_FAILURE;
	}
	war_SetWidth(pie_GetVideoBufferWidth());
	war_SetHeight(pie_GetVideoBufferHeight());

	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	pal_Init();

	pie_LoadBackDrop(SCREEN_RANDOMBDROP);
	pie_SetFogStatus(false);
	pie_ScreenFlip(CLEAR_BLACK);

	if (!systemInitialise())
	{
		return EXIT_FAILURE;
	}

	//set all the pause states to false
	setAllPauseStates(false);

	/* Runtime unit testing */
	if (selfTest)
	{
		parseTest();
		levTest();
		mapTest();
		fprintf(stdout, "All tests PASSED!\n");
		exit(0);
	}

	// Copy this info to be used by the crash handler for the dump file
	ssprintf(buf,"Using language: %s", getLanguageName());
	addDumpInfo(buf);

	// Do the game mode specific initialisation.
	switch(GetGameMode())
	{
		case GS_TITLE_SCREEN:
			startTitleLoop();
			break;
		case GS_SAVEGAMELOAD:
			initSaveGameLoad();
			break;
		case GS_NORMAL:
			startGameLoop();
			break;
		default:
			debug(LOG_ERROR, "Weirdy game status, I'm afraid!!");
			break;
	}

#if defined(WZ_CC_MSVC) && defined(DEBUG)
	debug_MEMSTATS();
#endif
	debug(LOG_MAIN, "Entering main loop");
	app.exec();
	saveConfig();
	systemShutdown();
	debug(LOG_MAIN, "Completed shutting down Warzone 2100");
	return EXIT_SUCCESS;
}
コード例 #15
0
void ScreenBookkeeping::UpdateView()
{
	BookkeepingView view = m_vBookkeepingViews[m_iViewIndex];


	{
		RString s;
		s += ALL_TIME.GetValue();
		s += ssprintf( " %i\n", BOOKKEEPER->GetCoinsTotal() );
		m_textAllTime.SetText( s );
	}

	switch( view )
	{
	case BookkeepingView_SongPlays:
		{
			Profile *pProfile = PROFILEMAN->GetMachineProfile();

			vector<Song*> vpSongs;
			int iCount = 0;
			FOREACH_CONST( Song *, SONGMAN->GetAllSongs(), s )
			{
				Song *pSong = *s;
				if( UNLOCKMAN->SongIsLocked(pSong) & ~LOCKED_DISABLED )
					continue;
				iCount += pProfile->GetSongNumTimesPlayed( pSong );
				vpSongs.push_back( pSong );
			}
			m_textTitle.SetText( ssprintf(SONG_PLAYS.GetValue(), iCount) );
			SongUtil::SortSongPointerArrayByNumPlays( vpSongs, pProfile, true );

			const int iSongPerCol = 15;
			
			int iSongIndex = 0;
			for( int i=0; i<NUM_BOOKKEEPING_COLS; i++ )
			{
				RString s;
				for( int j=0; j<iSongPerCol; j++ )
				{
					if( iSongIndex < (int)vpSongs.size() )
					{
						Song *pSong = vpSongs[iSongIndex];
						int iCount = pProfile->GetSongNumTimesPlayed( pSong );
						RString sTitle = ssprintf("%4d",iCount) + " " + pSong->GetDisplayFullTitle();
						if( sTitle.length() > 22 )
							sTitle = sTitle.Left(20) + "...";
						s += sTitle + "\n";
						iSongIndex++;
					}
				}
				m_textData[i].SetText( s );
				m_textData[i].SetHorizAlign( align_left );
			}
		}
		break;
	case BookkeepingView_LastDays:
		{
			m_textTitle.SetText( ssprintf(LAST_DAYS.GetValue(), NUM_LAST_DAYS) );

			int coins[NUM_LAST_DAYS];
			BOOKKEEPER->GetCoinsLastDays( coins );
			int iTotalLast = 0;
			
			RString sTitle, sData;
			for( int i=0; i<NUM_LAST_DAYS; i++ )
			{
				sTitle += LastDayToLocalizedString(i) + "\n";
				sData += ssprintf("%d",coins[i]) + "\n";
				iTotalLast += coins[i];
			}

			sTitle += ALL_TIME.GetValue()+"\n";
			sData += ssprintf("%i\n", iTotalLast);
			
			m_textData[0].SetText( "" );
			m_textData[1].SetHorizAlign( align_left );
			m_textData[1].SetText( sTitle );
			m_textData[2].SetText( "" );
			m_textData[3].SetHorizAlign( align_right );
			m_textData[3].SetText( sData );
		}
		break;
	case BookkeepingView_LastWeeks:
		{
			m_textTitle.SetText( ssprintf(LAST_WEEKS.GetValue(), NUM_LAST_WEEKS) );

			int coins[NUM_LAST_WEEKS];
			BOOKKEEPER->GetCoinsLastWeeks( coins );

			RString sTitle, sData;
			for( int col=0; col<4; col++ )
			{
				RString sTemp;
				for( int row=0; row<52/4; row++ )
				{
					int week = row*4+col;
					sTemp += LastWeekToLocalizedString(week) + ssprintf(": %d",coins[week]) + "\n";
				}

				m_textData[col].SetHorizAlign( align_left );
				m_textData[col].SetText( sTemp );
			}
		}
		break;
	case BookkeepingView_DayOfWeek:
		{
			m_textTitle.SetText( DAY_OF_WEEK );

			int coins[DAYS_IN_WEEK];
			BOOKKEEPER->GetCoinsByDayOfWeek( coins );

			RString sTitle, sData;
			for( int i=0; i<DAYS_IN_WEEK; i++ )
			{
				sTitle += DayOfWeekToString(i) + "\n";
				sData += ssprintf("%d",coins[i]) + "\n";
			}
			
			m_textData[0].SetText( "" );
			m_textData[1].SetHorizAlign( align_left );
			m_textData[1].SetText( sTitle );
			m_textData[2].SetText( "" );
			m_textData[3].SetHorizAlign( align_right );
			m_textData[3].SetText( sData );
		}
		break;
	case BookkeepingView_HourOfDay:
		{
			m_textTitle.SetText( HOUR_OF_DAY );

			int coins[HOURS_IN_DAY];
			BOOKKEEPER->GetCoinsByHour( coins );

			RString sTitle1, sData1;
			for( int i=0; i<HOURS_IN_DAY/2; i++ )
			{
				sTitle1 += HourInDayToLocalizedString(i) + "\n";
				sData1 += ssprintf("%d",coins[i]) + "\n";
			}
			
			RString sTitle2, sData2;
			for( int i=(HOURS_IN_DAY/2); i<HOURS_IN_DAY; i++ )
			{
				sTitle2 += HourInDayToLocalizedString(i) + "\n";
				sData2 += ssprintf("%d",coins[i]) + "\n";
			}
			
			m_textData[0].SetHorizAlign( align_left );
			m_textData[0].SetText( sTitle1 );
			m_textData[1].SetHorizAlign( align_right );
			m_textData[1].SetText( sData1 );
			m_textData[2].SetHorizAlign( align_left );
			m_textData[2].SetText( sTitle2 );
			m_textData[3].SetHorizAlign( align_right );
			m_textData[3].SetText( sData2 );
		}
		break;
	default:
		ASSERT(0);
	}
}
コード例 #16
0
void NetworkSyncManager::ProcessInput()
{
	//If we're disconnected, just exit
	if ((NetPlayerClient->state!=NetPlayerClient->skCONNECTED) || 
			NetPlayerClient->IsError())
	{
		SCREENMAN->SystemMessageNoAnimate("Connection to server dropped.");
		useSMserver=false;
		return;
	}

	//load new data into buffer
	NetPlayerClient->update();

	m_packet.ClearPacket();

	while (NetPlayerClient->ReadPack((char *)&m_packet, NETMAXBUFFERSIZE)>0)
	{
		int command = m_packet.Read1();
		//Check to make sure command is valid from server
		if (command < NSServerOffset)
		{		
			LOG->Trace("CMD (below 128) Invalid> %d",command);
 			break;
		}

		command = command - NSServerOffset;

		switch (command)
		{
		case NSCPing: //Ping packet responce
			m_packet.ClearPacket();
			m_packet.Write1( NSCPingR );
			NetPlayerClient->SendPack((char*)m_packet.Data,m_packet.Position);
			break;
		case NSCPingR:	//These are in responce to when/if we send packet 0's
		case NSCHello: //This is already taken care of by the blocking code earlier on
		case NSCGSR: //This is taken care of by the blocking start code
			break;
		case NSCGON: 
			{
				int PlayersInPack = m_packet.Read1();
				for (int i=0; i<PlayersInPack; ++i)
					m_EvalPlayerData[i].name = m_packet.Read1();
				for (int i=0; i<PlayersInPack; ++i)
					m_EvalPlayerData[i].score = m_packet.Read4();
				for (int i=0; i<PlayersInPack; ++i)
					m_EvalPlayerData[i].grade = m_packet.Read1();
				for (int i=0; i<PlayersInPack; ++i)
					m_EvalPlayerData[i].difficulty = (Difficulty) m_packet.Read1();
				for (int j=0; j<NETNUMTAPSCORES; ++j) 
					for (int i=0; i<PlayersInPack; ++i)
						m_EvalPlayerData[i].tapScores[j] = m_packet.Read2();
				for (int i=0; i<PlayersInPack; ++i)
					m_EvalPlayerData[i].playerOptions = m_packet.ReadNT();
				SCREENMAN->SendMessageToTopScreen( SM_GotEval );
			}
			break;
		case NSCGSU: //Scoreboard Update
			{	//Ease scope
				int ColumnNumber=m_packet.Read1();
				int NumberPlayers=m_packet.Read1();
				CString ColumnData;
				int i;
				switch (ColumnNumber)
				{
				case NSSB_NAMES:
					ColumnData = "Names\n";
					for (i=0; i<NumberPlayers; ++i)
					{
						unsigned int k = m_packet.Read1();
						if ( k < m_PlayerNames.size() )
							ColumnData += m_PlayerNames[k] + "\n";
					}
					break;
				case NSSB_COMBO:
					ColumnData = "Combo\n";
					for (i=0; i<NumberPlayers; ++i)
						ColumnData += ssprintf("%d\n",m_packet.Read2());
					break;
				case NSSB_GRADE:
					ColumnData = "Grade\n";
					for (i=0;i<NumberPlayers;i++)
						switch (m_packet.Read1())
						{
						case 0:
							ColumnData+="AAAA\n"; break;
						case 1:
							ColumnData+="AAA\n"; break;
						case 2:
							ColumnData+="AA\n"; break;
						case 3:
							ColumnData+="A\n"; break;
						case 4:
							ColumnData+="B\n"; break;
						case 5:
							ColumnData+="C\n"; break;
						case 6:
							ColumnData+="D\n"; break;
						case 7: 
							ColumnData+="E\n";	break;	//Is there a better way?
						}
					break;
				}
				m_Scoreboard[ColumnNumber] = ColumnData;
				m_scoreboardchange[ColumnNumber]=true;
			}
			break;
		case NSCSU:	//System message from server
			{
				CString SysMSG = m_packet.ReadNT();
				SCREENMAN->SystemMessage( SysMSG );
			}
			break;
		case NSCCM:	//Chat message from server					
			{
				m_sChatText += m_packet.ReadNT() + " \n ";
				//10000 chars backlog should be more than enough
				m_sChatText = m_sChatText.Right(10000);
				SCREENMAN->SendMessageToTopScreen( SM_AddToChat );
			}
			break;
		case NSCRSG: //Select Song/Play song
			{
				m_iSelectMode = m_packet.Read1();
				m_sMainTitle = m_packet.ReadNT();
				m_sArtist = m_packet.ReadNT();
				m_sSubTitle = m_packet.ReadNT();
				SCREENMAN->SendMessageToTopScreen( SM_ChangeSong );
			}
			break;
		case NSCUUL:
			{
				/*int ServerMaxPlayers=*/m_packet.Read1();
				int PlayersInThisPacket=m_packet.Read1();
				m_PlayerStatus.clear();
				m_PlayerNames.clear();
				m_ActivePlayers = 0;
				for (int i=0; i<PlayersInThisPacket; ++i)
				{
					int PStatus = m_packet.Read1();
					if ( PStatus > 0 )
					{
						m_ActivePlayers++;
						m_ActivePlayer.push_back( i );
					}
					m_PlayerStatus.push_back( PStatus );
					m_PlayerNames.push_back( m_packet.ReadNT() );
				}
			}
			break;
		case NSCSMS:
			{
				CString StyleName, GameName;
				GameName = m_packet.ReadNT();
				StyleName = m_packet.ReadNT();

				GAMESTATE->m_pCurGame = GAMEMAN->StringToGameType( GameName );
				GAMESTATE->m_pCurStyle = GAMEMAN->GameAndStringToStyle( GAMESTATE->m_pCurGame, StyleName );

				SCREENMAN->SetNewScreen( "ScreenNetSelectMusic" ); //Should this be metric'd out?
			}
			break;
		}
		m_packet.ClearPacket();
	}
}
コード例 #17
0
ファイル: smpackage.cpp プロジェクト: prappe/openitg
BOOL CSmpackageApp::InitInstance()
{
    // Make sure the current directory is the root program directory

    // change dir to path of the execuctable
    TCHAR szFullAppPath[MAX_PATH];
    GetModuleFileName(NULL, szFullAppPath, MAX_PATH);

    // strip off executable name
    LPSTR pLastBackslash = strrchr(szFullAppPath, '\\');
    *pLastBackslash = '\0';	// terminate the string

    /* If "Program" is the top-level directory, strip it off. */
    pLastBackslash = strrchr( szFullAppPath, '\\' );
    if( pLastBackslash && !stricmp(pLastBackslash, "\\Program") )
        *pLastBackslash = '\0';

    SetCurrentDirectory(szFullAppPath);

    if( DoesFileExist("Songs") )	// this is a SM or DWI program directory
    {
        // make sure it's in the list of install directories
        TCHAR szCurrentDirectory[MAX_PATH];
        GetCurrentDirectory( MAX_PATH, szCurrentDirectory );
        AddStepManiaInstallDir( szCurrentDirectory );
    }


    // check if there's a .smzip command line argument
    CStringArray arrayCommandLineBits;
    split( ::GetCommandLine(), "\"", arrayCommandLineBits );
    for( unsigned i=0; i<arrayCommandLineBits.size(); i++ )
    {
        CString sPath = arrayCommandLineBits[i];
        sPath.TrimLeft();
        sPath.TrimRight();
        CString sPathLower = sPath;
        sPathLower.MakeLower();

        // test to see if this is a smzip file
        if( sPathLower.Right(3) == "zip" )
        {
            if( !DoesFileExist(sPath) )
            {
                AfxMessageBox( ssprintf("The file '%s' does not exist.  Aborting installation.",sPath), MB_ICONERROR );
                exit(0);
            }

            // We found a zip package.  Prompt the user to install it!
            CSMPackageInstallDlg dlg( sPath );
            int nResponse = dlg.DoModal();
            if( nResponse == IDOK )
            {
                CSmpackageExportDlg dlg;
                int nResponse = dlg.DoModal();
                // Since the dialog has been closed, return FALSE so that we exit the
                //  application, rather than start the application's message pump.
                return FALSE;
            }
            else if (nResponse == IDCANCEL)
            {
                // the user cancelled.  Don't fall through to the Manager.
                exit(0);
            }
        }
    }


    // Show the Manager Dialog
    MainMenuDlg dlg;
    int nResponse = dlg.DoModal();
//	if (nResponse == IDOK)


    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}
コード例 #18
0
ファイル: screen.cpp プロジェクト: Zabanya/warzone2100
/* Initialise the double buffered display */
bool screenInitialise()
{
	GLint glMaxTUs;
	GLenum err;

	err = glewInit();
	if (GLEW_OK != err)
	{
		debug(LOG_FATAL, "Error: %s", glewGetErrorString(err));
		exit(1);
	}

	/* Dump general information about OpenGL implementation to the console and the dump file */
	ssprintf(opengl.vendor, "OpenGL Vendor: %s", glGetString(GL_VENDOR));
	addDumpInfo(opengl.vendor);
	debug(LOG_3D, "%s", opengl.vendor);
	ssprintf(opengl.renderer, "OpenGL Renderer: %s", glGetString(GL_RENDERER));
	addDumpInfo(opengl.renderer);
	debug(LOG_3D, "%s", opengl.renderer);
	ssprintf(opengl.version, "OpenGL Version: %s", glGetString(GL_VERSION));
	addDumpInfo(opengl.version);
	debug(LOG_3D, "%s", opengl.version);
	ssprintf(opengl.GLEWversion, "GLEW Version: %s", glewGetString(GLEW_VERSION));
	if (strncmp(opengl.GLEWversion, "1.9.", 4) == 0) // work around known bug with KHR_debug extension support in this release
	{
		debug(LOG_WARNING, "Your version of GLEW is old and buggy, please upgrade to at least version 1.10.");
		khr_debug = false;
	}
	else
	{
		khr_debug = GLEW_KHR_debug;
	}
	addDumpInfo(opengl.GLEWversion);
	debug(LOG_3D, "%s", opengl.GLEWversion);

	GLubyte const *extensionsBegin = glGetString(GL_EXTENSIONS);
	if (extensionsBegin == nullptr)
	{
		static GLubyte const emptyString[] = "";
		extensionsBegin = emptyString;
	}
	GLubyte const *extensionsEnd = extensionsBegin + strlen((char const *)extensionsBegin);
	std::vector<std::string> glExtensions;
	for (GLubyte const *i = extensionsBegin; i < extensionsEnd;)
	{
		GLubyte const *j = std::find(i, extensionsEnd, ' ');
		glExtensions.push_back(std::string(i, j));
		i = j + 1;
	}

	/* Dump extended information about OpenGL implementation to the console */

	std::string line;
	for (unsigned n = 0; n < glExtensions.size(); ++n)
	{
		std::string word = " ";
		word += glExtensions[n];
		if (n + 1 != glExtensions.size())
		{
			word += ',';
		}
		if (line.size() + word.size() > 160)
		{
			debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
			line.clear();
		}
		line += word;
	}
	debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
	debug(LOG_3D, "Notable OpenGL features:");
	debug(LOG_3D, "  * OpenGL 1.2 %s supported!", GLEW_VERSION_1_2 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.3 %s supported!", GLEW_VERSION_1_3 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.4 %s supported!", GLEW_VERSION_1_4 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.5 %s supported!", GLEW_VERSION_1_5 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.0 %s supported!", GLEW_VERSION_2_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.1 %s supported!", GLEW_VERSION_2_1 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 3.0 %s supported!", GLEW_VERSION_3_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * Texture compression %s supported.", GLEW_ARB_texture_compression ? "is" : "is NOT");
	debug(LOG_3D, "  * Two side stencil %s supported.", GLEW_EXT_stencil_two_side ? "is" : "is NOT");
	debug(LOG_3D, "  * ATI separate stencil is%s supported.", GLEW_ATI_separate_stencil ? "" : " NOT");
	debug(LOG_3D, "  * Stencil wrap %s supported.", GLEW_EXT_stencil_wrap ? "is" : "is NOT");
	debug(LOG_3D, "  * Anisotropic filtering %s supported.", GLEW_EXT_texture_filter_anisotropic ? "is" : "is NOT");
	debug(LOG_3D, "  * Rectangular texture %s supported.", GLEW_ARB_texture_rectangle ? "is" : "is NOT");
	debug(LOG_3D, "  * FrameBuffer Object (FBO) %s supported.", GLEW_EXT_framebuffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * ARB Vertex Buffer Object (VBO) %s supported.", GLEW_ARB_vertex_buffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * NPOT %s supported.", GLEW_ARB_texture_non_power_of_two ? "is" : "is NOT");
	debug(LOG_3D, "  * texture cube_map %s supported.", GLEW_ARB_texture_cube_map ? "is" : "is NOT");
	glGetIntegerv(GL_MAX_TEXTURE_UNITS, &glMaxTUs);
	debug(LOG_3D, "  * Total number of Texture Units (TUs) supported is %d.", (int) glMaxTUs);
	debug(LOG_3D, "  * GL_ARB_timer_query %s supported!", GLEW_ARB_timer_query ? "is" : "is NOT");
	debug(LOG_3D, "  * KHR_DEBUG support %s detected", khr_debug ? "was" : "was NOT");

	if (!GLEW_VERSION_2_0)
	{
		debug(LOG_FATAL, "OpenGL 2.0 not supported! Please upgrade your drivers.");
		return false;
	}

	screenWidth = MAX(screenWidth, 640);
	screenHeight = MAX(screenHeight, 480);

	std::pair<int, int> glslVersion(0, 0);
	sscanf((char const *)glGetString(GL_SHADING_LANGUAGE_VERSION), "%d.%d", &glslVersion.first, &glslVersion.second);

	/* Dump information about OpenGL 2.0+ implementation to the console and the dump file */
	GLint glMaxTIUs, glMaxTCs, glMaxTIUAs, glmaxSamples, glmaxSamplesbuf;

	debug(LOG_3D, "  * OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	ssprintf(opengl.GLSLversion, "OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	addDumpInfo(opengl.GLSLversion);

	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &glMaxTIUs);
	debug(LOG_3D, "  * Total number of Texture Image Units (TIUs) supported is %d.", (int) glMaxTIUs);
	glGetIntegerv(GL_MAX_TEXTURE_COORDS, &glMaxTCs);
	debug(LOG_3D, "  * Total number of Texture Coords (TCs) supported is %d.", (int) glMaxTCs);
	glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &glMaxTIUAs);
	debug(LOG_3D, "  * Total number of Texture Image Units ARB(TIUAs) supported is %d.", (int) glMaxTIUAs);
	glGetIntegerv(GL_SAMPLE_BUFFERS, &glmaxSamplesbuf);
	debug(LOG_3D, "  * (current) Max Sample buffer is %d.", (int) glmaxSamplesbuf);
	glGetIntegerv(GL_SAMPLES, &glmaxSamples);
	debug(LOG_3D, "  * (current) Max Sample level is %d.", (int) glmaxSamples);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

	pie_Skybox_Init();

	// Generate backdrop render
	backdropGfx = new GFX(GFX_TEXTURE, GL_TRIANGLE_STRIP, 2);

	if (GLEW_ARB_timer_query)
	{
		glGenQueries(PERF_COUNT, perfpos);
	}

	if (khr_debug)
	{
		glDebugMessageCallback((GLDEBUGPROC)khr_callback, NULL);
		glEnable(GL_DEBUG_OUTPUT);
		// Do not want to output notifications. Some drivers spam them too much.
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
		debug(LOG_3D, "Enabling KHR_debug message callback");
	}

	return true;
}
コード例 #19
0
/* Set the video mode. */
CString RageDisplay_D3D::TryVideoMode( VideoModeParams p, bool &bNewDeviceOut )
{
	if( FindBackBufferType( p.windowed, p.bpp ) == D3DFMT_UNKNOWN )	// no possible back buffer formats
		return ssprintf( "FindBackBufferType(%i,%i) failed", p.windowed, p.bpp );	// failed to set mode

#if !defined(XBOX)
	if( GraphicsWindow::GetHwnd() == NULL )
		GraphicsWindow::CreateGraphicsWindow( p );
#else
	p.windowed = false;
#endif

	/* Set up and display the window before setting up D3D.  If we don't do this,
	 * then setting up a fullscreen window (when we're not coming from windowed)
	 * causes all other windows on the system to be resized to the new resolution. */
	GraphicsWindow::ConfigureGraphicsWindow( p );

	ZeroMemory( &g_d3dpp, sizeof(g_d3dpp) );

	g_d3dpp.BackBufferWidth			=	p.width;
	g_d3dpp.BackBufferHeight		=	p.height;
	g_d3dpp.BackBufferFormat		=	FindBackBufferType( p.windowed, p.bpp );
	g_d3dpp.BackBufferCount			=	1;
	g_d3dpp.MultiSampleType			=	D3DMULTISAMPLE_NONE;
	g_d3dpp.SwapEffect				=	D3DSWAPEFFECT_DISCARD;
#if !defined(XBOX)
	g_d3dpp.hDeviceWindow			=	GraphicsWindow::GetHwnd();
#else
	g_d3dpp.hDeviceWindow			=	NULL;
#endif
	g_d3dpp.Windowed				=	p.windowed;
	g_d3dpp.EnableAutoDepthStencil	=	TRUE;
	g_d3dpp.AutoDepthStencilFormat	=	D3DFMT_D16;

	if(p.windowed)
		g_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
	else
		g_d3dpp.FullScreen_PresentationInterval = p.vsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;

#if !defined(XBOX)
	g_d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
	if( !p.windowed && p.rate != REFRESH_DEFAULT )
		g_d3dpp.FullScreen_RefreshRateInHz = p.rate;
#else
	if( XGetVideoStandard() == XC_VIDEO_STANDARD_PAL_I )
	{
		/* Get supported video flags. */
		DWORD VideoFlags = XGetVideoFlags();
		
		/* Set pal60 if available. */
		if( VideoFlags & XC_VIDEO_FLAGS_PAL_60Hz )
			g_d3dpp.FullScreen_RefreshRateInHz = 60;
		else
			g_d3dpp.FullScreen_RefreshRateInHz = 50;
	}
	else
		g_d3dpp.FullScreen_RefreshRateInHz = 60;
#endif

	g_d3dpp.Flags					=	0;

	LOG->Trace( "Present Parameters: %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d", 
		g_d3dpp.BackBufferWidth, g_d3dpp.BackBufferHeight, g_d3dpp.BackBufferFormat,
		g_d3dpp.BackBufferCount,
		g_d3dpp.MultiSampleType, g_d3dpp.SwapEffect, g_d3dpp.hDeviceWindow,
		g_d3dpp.Windowed, g_d3dpp.EnableAutoDepthStencil, g_d3dpp.AutoDepthStencilFormat,
		g_d3dpp.Flags, g_d3dpp.FullScreen_RefreshRateInHz,
		g_d3dpp.FullScreen_PresentationInterval
	);

#if defined(XBOX)
	if( D3D__pDevice )
		g_pd3dDevice = D3D__pDevice;
#endif

	/* Display the window immediately, so we don't display the desktop ... */

	while( 1 )
	{
		/* Try the video mode. */
		CString sErr = SetD3DParams( bNewDeviceOut );
		if( sErr.empty() )
			break;

		/* It failed.  We're probably selecting a video mode that isn't supported.
		 * If we're fullscreen, search the mode list and find the nearest lower
		 * mode. */
		if( p.windowed || !D3DReduceParams( &g_d3dpp ) )
			return sErr;

		/* Store the new settings we're about to try. */
		p.height = g_d3dpp.BackBufferHeight;
		p.width = g_d3dpp.BackBufferWidth;
		if( g_d3dpp.FullScreen_RefreshRateInHz == D3DPRESENT_RATE_DEFAULT )
			p.rate = REFRESH_DEFAULT;
		else
			p.rate = g_d3dpp.FullScreen_RefreshRateInHz;
	}

	/* Call this again after changing the display mode.  If we're going to a window
	 * from fullscreen, the first call can't set a larger window than the old fullscreen
	 * resolution or set the window position. */
	GraphicsWindow::ConfigureGraphicsWindow( p );

	GraphicsWindow::SetVideoModeParams( p );

	ResolutionChanged();

	this->SetDefaultRenderStates();
	
	/* Palettes were lost by Reset(), so mark them unloaded. */
	g_TexResourceToPaletteIndex.clear();

	return "";	// mode change successful
}
コード例 #20
0
void ScreenHowToPlay::Init()
{
	ScreenAttract::Init();

	if( (bool)USE_PAD && DoesFileExist( GetAnimPath(ANIM_DANCE_PAD) ) )
	{
		m_pmDancePad = new Model;
		m_pmDancePad->SetName( "Pad" );
		m_pmDancePad->LoadMilkshapeAscii( GetAnimPath(ANIM_DANCE_PAD) );
		m_pmDancePad->SetRotationX( 35 );
		LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( m_pmDancePad );
	}
	
	// Display random character
	vector<Character*> vpCharacters;
	CHARMAN->GetCharacters( vpCharacters );
	if( (bool)USE_CHARACTER && vpCharacters.size() && HaveAllCharAnimations() )
	{
		Character* rndchar = CHARMAN->GetRandomCharacter();

		RString sModelPath = rndchar->GetModelPath();
		if( sModelPath != "" )
		{
			m_pmCharacter = new Model;
			m_pmCharacter->SetName( "Character" );
			m_pmCharacter->LoadMilkshapeAscii( rndchar->GetModelPath() );
			m_pmCharacter->LoadMilkshapeAsciiBones( "Step-LEFT", GetAnimPath( ANIM_LEFT ) );
			m_pmCharacter->LoadMilkshapeAsciiBones( "Step-DOWN", GetAnimPath( ANIM_DOWN ) );
			m_pmCharacter->LoadMilkshapeAsciiBones( "Step-UP", GetAnimPath( ANIM_UP ) );
			m_pmCharacter->LoadMilkshapeAsciiBones( "Step-RIGHT", GetAnimPath( ANIM_RIGHT ) );
			m_pmCharacter->LoadMilkshapeAsciiBones( "Step-JUMPLR", GetAnimPath( ANIM_JUMPLR ) );
			RString sRestFile = rndchar->GetRestAnimationPath();
			ASSERT( !sRestFile.empty() );
			m_pmCharacter->LoadMilkshapeAsciiBones( "rest",rndchar->GetRestAnimationPath() );
			m_pmCharacter->SetDefaultAnimation( "rest" );
			m_pmCharacter->PlayAnimation( "rest" );				// Stay bouncing after a step has finished animating.
			
			m_pmCharacter->SetRotationX( 40 );
			m_pmCharacter->SetCullMode( CULL_NONE );	// many of the models floating around have the vertex order flipped
			LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( m_pmCharacter );
		}
	}
	
	GAMESTATE->SetCurrentStyle( GAMEMAN->GetHowToPlayStyleForGame(GAMESTATE->m_pCurGame) );

	if( USE_PLAYER )
	{
		m_pLifeMeterBar = new LifeMeterBar;
		m_pLifeMeterBar->SetName("LifeMeterBar");
		m_pLifeMeterBar->Load( GAMESTATE->m_pPlayerState[PLAYER_1], &STATSMAN->m_CurStageStats.m_player[PLAYER_1] );
		LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( m_pLifeMeterBar );
		m_pLifeMeterBar->FillForHowToPlay( NUM_W2S, NUM_MISSES );


		SMLoader::LoadFromSMFile( THEME->GetPathO(m_sName, "steps"), m_Song, false );
		m_Song.AddAutoGenNotes();

		const Style* pStyle = GAMESTATE->GetCurrentStyle();
		
		Steps *pSteps = SongUtil::GetStepsByDescription( &m_Song, pStyle->m_StepsType, "" );
		ASSERT_M( pSteps != NULL, ssprintf("%i", pStyle->m_StepsType) );

		NoteData tempNoteData;
		pSteps->GetNoteData( tempNoteData );
		pStyle->GetTransformedNoteDataForStyle( PLAYER_1, tempNoteData, m_NoteData );

		GAMESTATE->m_pCurSong.Set( &m_Song );
		GAMESTATE->m_bGameplayLeadIn.Set( false );
		GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerController = PC_AUTOPLAY;

		m_Player->Init( 
			"Player",
			GAMESTATE->m_pPlayerState[PLAYER_1], 
			NULL,
			m_pLifeMeterBar, 
			NULL, 
			NULL, 
			NULL, 
			NULL, 
			NULL, 
			NULL );
		m_Player.Load( m_NoteData );
		m_Player->SetName( "Player" );
		this->AddChild( m_Player );
		LOAD_ALL_COMMANDS_AND_SET_XY_AND_ON_COMMAND( m_Player );

		// Don't show judgement
		PO_GROUP_ASSIGN( GAMESTATE->m_pPlayerState[PLAYER_1]->m_PlayerOptions, ModsLevel_Stage, m_fBlind, 1.0f );
		GAMESTATE->m_MasterPlayerNumber = PLAYER_1;
		GAMESTATE->m_bDemonstrationOrJukebox = true;
	}

	// deferred until after the player, so the notes go under it
	if( m_pLifeMeterBar )
		this->AddChild( m_pLifeMeterBar );
	if( m_pmDancePad )
		this->AddChild( m_pmDancePad );
	if( m_pmCharacter )
		this->AddChild( m_pmCharacter );

	m_fFakeSecondsIntoSong = 0;

	this->MoveToTail( &m_In );
	this->MoveToTail( &m_Out );
}
コード例 #21
0
ファイル: NotesWriterDWI.cpp プロジェクト: goofwear/stepmania
bool NotesWriterDWI::Write( RString sPath, const Song &out )
{
	RageFile f;
	if( !f.Open( sPath, RageFile::WRITE ) )
	{
		LOG->UserLog( "Song file", sPath, "couldn't be opened for writing: %s", f.GetError().c_str() );
		return false;
	}

	/* Write transliterations, if we have them, since DWI doesn't support UTF-8. */
	f.PutLine( ssprintf("#TITLE:%s;", DwiEscape(out.GetTranslitFullTitle()).c_str()) );
	f.PutLine( ssprintf("#ARTIST:%s;", DwiEscape(out.GetTranslitArtist()).c_str()) );
	ASSERT( out.m_Timing.m_BPMSegments[0].m_iStartRow == 0 );
	f.PutLine( ssprintf("#FILE:%s;", DwiEscape(out.m_sMusicFile).c_str()) );
	f.PutLine( ssprintf("#BPM:%.3f;", out.m_Timing.m_BPMSegments[0].GetBPM()) );
	f.PutLine( ssprintf("#GAP:%ld;", -lrintf( out.m_Timing.m_fBeat0OffsetInSeconds*1000 )) );
	f.PutLine( ssprintf("#SAMPLESTART:%.3f;", out.m_fMusicSampleStartSeconds) );
	f.PutLine( ssprintf("#SAMPLELENGTH:%.3f;", out.m_fMusicSampleLengthSeconds) );
	if( out.m_sCDTitleFile.size() )
		f.PutLine( ssprintf("#CDTITLE:%s;", DwiEscape(out.m_sCDTitleFile).c_str()) );
	switch( out.m_DisplayBPMType )
	{
	case Song::DISPLAY_ACTUAL:
		// write nothing
		break;
	case Song::DISPLAY_SPECIFIED:
		if( out.m_fSpecifiedBPMMin == out.m_fSpecifiedBPMMax )
			f.PutLine( ssprintf("#DISPLAYBPM:%i;\n", (int) out.m_fSpecifiedBPMMin) );
		else
			f.PutLine( ssprintf("#DISPLAYBPM:%i..%i;\n", (int) out.m_fSpecifiedBPMMin, (int) out.m_fSpecifiedBPMMax) );
		break;
	case Song::DISPLAY_RANDOM:
		f.PutLine( "#DISPLAYBPM:*" );
		break;
	}

	if( !out.m_Timing.m_StopSegments.empty() )
	{
		f.Write( "#FREEZE:" );

		for( unsigned i=0; i<out.m_Timing.m_StopSegments.size(); i++ )
		{
			const StopSegment &fs = out.m_Timing.m_StopSegments[i];
			f.Write( ssprintf("%.3f=%.3f", fs.m_iStartRow * 4.0f / ROWS_PER_BEAT,
				roundf(fs.m_fStopSeconds*1000)) );
			if( i != out.m_Timing.m_StopSegments.size()-1 )
				f.Write( "," );
		}
		f.PutLine( ";" );
	}

	if( out.m_Timing.m_BPMSegments.size() > 1)
	{
		f.Write( "#CHANGEBPM:" );
		for( unsigned i=1; i<out.m_Timing.m_BPMSegments.size(); i++ )
		{
			const BPMSegment &bs = out.m_Timing.m_BPMSegments[i];
			f.Write( ssprintf("%.3f=%.3f", bs.m_iStartRow * 4.0f / ROWS_PER_BEAT, bs.GetBPM() ) );
			if( i != out.m_Timing.m_BPMSegments.size()-1 )
				f.Write( "," );
		}
		f.PutLine( ";" );
	}

	const vector<Steps*>& vpSteps = out.GetAllSteps();
	for( unsigned i=0; i<vpSteps.size(); i++ ) 
	{
		const Steps* pSteps = vpSteps[i];
		if( pSteps->IsAutogen() )
			continue;	// don't save autogen notes

		if( !WriteDWINotesTag( f, *pSteps ))
			continue;

		WriteDWINotesField( f, *pSteps, 0 );
		if( pSteps->m_StepsType==StepsType_dance_double ||
		    pSteps->m_StepsType==StepsType_dance_couple )
		{
			f.PutLine( ":" );
			WriteDWINotesField( f, *pSteps, 4 );
		}

		f.PutLine( ";" );
	}
	
	return true;
}
コード例 #22
0
Actor *ActorUtil::LoadFromNode( const XNode* _pNode, Actor *pParentActor )
{
    ASSERT( _pNode != NULL );

    XNode node = *_pNode;

    // Remove this in favor of using conditionals in Lua. -Chris
    // There are a number of themes out there that depend on this (including
    // sm-ssc default). Probably for the best to leave this in. -aj
    {
        bool bCond;
        if( node.GetAttrValue("Condition", bCond) && !bCond )
            return NULL;
    }

    RString sClass;
    bool bHasClass = node.GetAttrValue( "Class", sClass );
    if( !bHasClass )
        bHasClass = node.GetAttrValue( "Type", sClass );

    bool bLegacy = (node.GetAttr( "_LegacyXml" ) != NULL);
    if( !bHasClass && bLegacy )
        sClass = GetLegacyActorClass( &node );

    map<RString,CreateActorFn>::iterator iter = g_pmapRegistrees->find( sClass );
    if( iter == g_pmapRegistrees->end() )
    {
        RString sFile;
        if (bLegacy && node.GetAttrValue("File", sFile) && sFile != "")
        {
            RString sPath;
            // Handle absolute paths correctly
            if (sFile.Left(1) == "/")
                sPath = sFile;
            else
                sPath = Dirname(GetSourcePath(&node)) + sFile;
            if (ResolvePath(sPath, GetWhere(&node)))
            {
                Actor *pNewActor = MakeActor(sPath, pParentActor);
                if (pNewActor == NULL)
                    return NULL;
                if (pParentActor)
                    pNewActor->SetParent(pParentActor);
                pNewActor->LoadFromNode(&node);
                return pNewActor;
            }
        }

        // sClass is invalid
        RString sError = ssprintf( "%s: invalid Class \"%s\"",
                                   ActorUtil::GetWhere(&node).c_str(), sClass.c_str() );
        Dialog::OK( sError );
        return new Actor;	// Return a dummy object so that we don't crash in AutoActor later.
    }

    const CreateActorFn &pfn = iter->second;
    Actor *pRet = pfn();

    if( pParentActor )
        pRet->SetParent( pParentActor );

    pRet->LoadFromNode( &node );
    return pRet;
}
コード例 #23
0
void MovieTexture_FFMpeg::DiscardFrame()
{
	ASSERT_M( m_ImageWaiting == FRAME_DECODED, ssprintf("%i", m_ImageWaiting) );
	m_ImageWaiting = FRAME_NONE;
}
コード例 #24
0
/* Resolves actor paths a la LoadActor("..."), with autowildcarding and .redir
 * files.  Returns a path *within* the Rage filesystem, unlike the FILEMAN
 * function of the same name. */
bool ActorUtil::ResolvePath( RString &sPath, const RString &sName )
{
    CollapsePath( sPath );

    // If we know this is an exact match, don't bother with the GetDirListing,
    // so "foo" doesn't partial match "foobar" if "foo" exists.
    RageFileManager::FileType ft = FILEMAN->GetFileType( sPath );
    if( ft != RageFileManager::TYPE_FILE && ft != RageFileManager::TYPE_DIR )
    {
        vector<RString> asPaths;
        GetDirListing( sPath + "*", asPaths, false, true );	// return path too

        if( asPaths.empty() )
        {
            RString sError = ssprintf( "%s: references a file \"%s\" which doesn't exist", sName.c_str(), sPath.c_str() );
            switch(LuaHelpers::ReportScriptError(sError, "BROKEN_FILE_REFERENCE", true))
            {
            case Dialog::abort:
                RageException::Throw( "%s", sError.c_str() );
                break;
            case Dialog::retry:
                FILEMAN->FlushDirCache();
                return ResolvePath( sPath, sName );
            case Dialog::ignore:
                return false;
            default:
                FAIL_M("Invalid response to Abort/Retry/Ignore dialog");
            }
        }

        THEME->FilterFileLanguages( asPaths );

        if( asPaths.size() > 1 )
        {
            RString sError = ssprintf( "%s: references a file \"%s\" which has multiple matches", sName.c_str(), sPath.c_str() );
            sError += "\n" + join( "\n", asPaths );
            switch(LuaHelpers::ReportScriptError(sError, "BROKEN_FILE_REFERENCE", true))
            {
            case Dialog::abort:
                RageException::Throw( "%s", sError.c_str() );
                break;
            case Dialog::retry:
                FILEMAN->FlushDirCache();
                return ResolvePath( sPath, sName );
            case Dialog::ignore:
                asPaths.erase( asPaths.begin()+1, asPaths.end() );
                break;
            default:
                FAIL_M("Invalid response to Abort/Retry/Ignore dialog");
            }
        }

        sPath = asPaths[0];
    }

    if( ft == RageFileManager::TYPE_DIR )
    {
        RString sLuaPath = sPath + "/default.lua";
        if( DoesFileExist(sLuaPath) )
        {
            sPath = sLuaPath;
            return true;
        }
    }

    sPath = DerefRedir( sPath );
    return true;
}
コード例 #25
0
static void posixExceptionHandler(int signum)
#endif
{
	static sig_atomic_t allreadyRunning = 0;
	// XXXXXX will be converted into random characters by mkstemp(3)
	static const char gdmpFile[] = "warzone2100.gdmp-XXXXXX";
	char gdmpPath[PATH_MAX] = {'\0'};
	char dumpFilename[PATH_MAX];
	int dumpFile;
	const char *signal;
# if defined(__GLIBC__)
	void *btBuffer[MAX_BACKTRACE] = {NULL};
	uint32_t btSize = backtrace(btBuffer, MAX_BACKTRACE);
# endif

	if (allreadyRunning)
	{
		raise(signum);
	}
	allreadyRunning = 1;
	// we use our write directory (which is the only directory that wz should have access to)
	// and stuff it into our logs directory (same as on windows)
	ssprintf(gdmpPath, "%slogs/%s", WritePath, gdmpFile);
	sstrcpy(dumpFilename, gdmpPath);

	dumpFile = mkstemp(dumpFilename);

	if (dumpFile == -1)
	{
		printf("Failed to create dump file '%s'", dumpFilename);
		return;
	}

	// Dump a generic info header
	dbgDumpHeader(dumpFile);

#ifdef SA_SIGINFO
	write(dumpFile, "Dump caused by signal: ", strlen("Dump caused by signal: "));

	signal = wz_strsignal(siginfo->si_signo, siginfo->si_code);
	write(dumpFile, signal, strlen(signal));
	write(dumpFile, "\n\n", 2);
#endif

	dbgDumpLog(dumpFile); // dump out the last several log calls

# if defined(__GLIBC__)
	// Dump raw backtrace in case GDB is not available or fails
	write(dumpFile, "GLIBC raw backtrace:\n", strlen("GLIBC raw backtrace:\n"));
	backtrace_symbols_fd(btBuffer, btSize, dumpFile);
	write(dumpFile, "\n", 1);
# else
	write(dumpFile, "GLIBC not available, no raw backtrace dumped\n\n",
	      strlen("GLIBC not available, no raw backtrace dumped\n\n"));
# endif


	// Make sure everything is written before letting GDB write to it
	fsync(dumpFile);

	// Use 'gdb' to provide an "extended" backtrace
#ifdef SA_SIGINFO
	gdbExtendedBacktrace(dumpFile, (ucontext_t *)sigcontext);
#else
	gdbExtendedBacktrace(dumpFile);
#endif

	printf("Saved dump file to '%s'\n"
	       "If you create a bugreport regarding this crash, please include this file.\n", dumpFilename);
	close(dumpFile);


	sigaction(signum, &oldAction[signum], NULL);
	raise(signum);
}
コード例 #26
0
ファイル: BeginnerHelper.cpp プロジェクト: AratnitY/stepmania
bool BeginnerHelper::Init( int iDancePadType )
{
	ASSERT( !m_bInitialized );
	if( !CanUse(PLAYER_INVALID) )
		return false;

	// If no players were successfully added, bail.
	{
		bool bAnyLoaded = false;
		for( int pn=0; pn<NUM_PLAYERS; pn++ )
			if( m_bPlayerEnabled[pn] )
				bAnyLoaded = true;

		if( !bAnyLoaded )
			return false;
	}

	// Load the Background and flash. Flash only shows if the BG does.
	if( m_bShowBackground )
	{
		m_sBackground.Load( THEME->GetPathG("BeginnerHelper","background") );
		this->AddChild( m_sBackground );
		//m_sBackground.SetXY( 1, 1 );

		m_sFlash.Load( THEME->GetPathG("BeginnerHelper","flash") );
		m_sFlash.SetXY( 0, 0 );
		m_sFlash.SetDiffuseAlpha( 0 );
	}

	// Load StepCircle graphics
	for( int lsc=0; lsc<NUM_PLAYERS; lsc++ )
	{
		for( int lsce=0; lsce<4; lsce++ )
		{
			m_sStepCircle[lsc][lsce].Load( THEME->GetPathG("BeginnerHelper","stepcircle") );
			m_sStepCircle[lsc][lsce].SetZoom( 0 );	// Hide until needed.
			this->AddChild(&m_sStepCircle[lsc][lsce]);

			// Set StepCircle coordinates
			switch( lsce )
			{
			case 0: m_sStepCircle[lsc][lsce].SetXY((HELPER_X+PLAYER_X(lsc)-80),HELPER_Y);	break;	// Left
			case 1: m_sStepCircle[lsc][lsce].SetXY((HELPER_X+PLAYER_X(lsc)+80),HELPER_Y);	break;	// Right
			case 2: m_sStepCircle[lsc][lsce].SetXY((HELPER_X+PLAYER_X(lsc)),(HELPER_Y-60));	break;	// Up
			case 3: m_sStepCircle[lsc][lsce].SetXY((HELPER_X+PLAYER_X(lsc)),(HELPER_Y+60));	break;	// Down
			}
		}
	}

	SHOW_DANCE_PAD.Load( "BeginnerHelper","ShowDancePad" );
	// Load the DancePad
	if( SHOW_DANCE_PAD )
	{
		switch( iDancePadType )
		{
		case 0: break; // No pad
		case 1: m_pDancePad->LoadMilkshapeAscii(GetAnimPath(ANIM_DANCE_PAD)); break;
		case 2: m_pDancePad->LoadMilkshapeAscii(GetAnimPath(ANIM_DANCE_PADS)); break;
		}

		m_pDancePad->SetName("DancePad");
		m_pDancePad->SetX( HELPER_X );
		m_pDancePad->SetY( HELPER_Y );
		ActorUtil::LoadAllCommands( m_pDancePad, "BeginnerHelper" );
	}

	for( int pl=0; pl<NUM_PLAYERS; pl++ )	// Load players
	{
		// Skip if not enabled
		if( !m_bPlayerEnabled[pl] )
			continue;

		// Load character data
		const Character *Character = GAMESTATE->m_pCurCharacters[pl];
		ASSERT( Character != NULL );

		m_pDancer[pl]->SetName( ssprintf("PlayerP%d",pl+1) );

		// Load textures
		m_pDancer[pl]->LoadMilkshapeAscii( Character->GetModelPath() );

		// Load needed animations
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "Step-LEFT",	GetAnimPath(ANIM_LEFT) );
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "Step-DOWN",	GetAnimPath(ANIM_DOWN) );
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "Step-UP", 	GetAnimPath(ANIM_UP) );
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "Step-RIGHT", 	GetAnimPath(ANIM_RIGHT) );
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "Step-JUMPLR", 	GetAnimPath(ANIM_JUMPLR) );
		m_pDancer[pl]->LoadMilkshapeAsciiBones( "rest",		Character->GetRestAnimationPath() );
		m_pDancer[pl]->SetDefaultAnimation( "rest" );		// Stay bouncing after a step has finished animating
		m_pDancer[pl]->PlayAnimation( "rest" );
		m_pDancer[pl]->SetX( HELPER_X+PLAYER_X(pl) );
		m_pDancer[pl]->SetY( HELPER_Y+10 );
		ActorUtil::LoadAllCommandsAndOnCommand( m_pDancer[pl], "BeginnerHelper" );
		// many of the models floating around have the vertex order flipped, so force this.
		m_pDancer[pl]->SetCullMode( CULL_NONE );
	}

	m_bInitialized = true;
	return true;
}
コード例 #27
0
static void MemoryCardOsMountPointInit( size_t /*PlayerNumber*/ i, RString &sNameOut, RString &defaultValueOut )
{
	sNameOut = ssprintf( "MemoryCardOsMountPointP%d", int(i+1) );
	defaultValueOut = "";
}
コード例 #28
0
ファイル: GraphicsWindow.cpp プロジェクト: goofwear/stepmania
static LRESULT CALLBACK GraphicsWindow_WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	CHECKPOINT_M( ssprintf("%p, %u, %08x, %08x", hWnd, msg, wParam, lParam) );

	/* Suppress autorun. */
	if( msg == g_iQueryCancelAutoPlayMessage )
		return true;

	switch( msg )
	{
	case WM_ACTIVATE:
	{
		const bool bInactive = (LOWORD(wParam) == WA_INACTIVE);
		const bool bMinimized = (HIWORD(wParam) != 0);
		const bool bHadFocus = g_bHasFocus;
		g_bHasFocus = !bInactive && !bMinimized;
		LOG->Trace( "WM_ACTIVATE (%i, %i): %s", bInactive, bMinimized, g_bHasFocus? "has focus":"doesn't have focus" );
		if( !g_bHasFocus )
		{
			RString sName = GetNewWindow();
			static set<RString> sLostFocusTo;
			sLostFocusTo.insert( sName );
			RString sStr;
			for( set<RString>::const_iterator it = sLostFocusTo.begin(); it != sLostFocusTo.end(); ++it )
				sStr += (sStr.size()?", ":"") + *it;

			LOG->MapLog( "LOST_FOCUS", "Lost focus to: %s", sStr.c_str() );
		}

		if( !g_bD3D && !g_CurrentParams.windowed && !g_bRecreatingVideoMode )
		{
			/* In OpenGL (not D3D), it's our job to unset and reset the full-screen video mode
			 * when we focus changes, and to hide and show the window.  Hiding is done in WM_KILLFOCUS,
			 * because that's where most other apps seem to do it. */
			if( g_bHasFocus && !bHadFocus )
			{
				ChangeDisplaySettings( &g_FullScreenDevMode, CDS_FULLSCREEN );
				ShowWindow( g_hWndMain, SW_SHOWNORMAL );
			}
			else if( !g_bHasFocus && bHadFocus )
			{
				ChangeDisplaySettings( NULL, 0 );
			}
		}

		return 0;
	}
	case WM_KILLFOCUS:
		if( !g_bD3D && !g_CurrentParams.windowed && !g_bRecreatingVideoMode )
			ShowWindow( g_hWndMain, SW_SHOWMINNOACTIVE );
		break;

	/* Is there any reason we should care what size the user resizes the window to? */
//	case WM_GETMINMAXINFO:

	case WM_SETCURSOR:
		if( !g_CurrentParams.windowed )
		{
			SetCursor( NULL );
			return 1;
		}
		break;

	case WM_SYSCOMMAND:
		switch( wParam&0xFFF0 )
		{
		case SC_MONITORPOWER:
		case SC_SCREENSAVE:
			return 0;
		}
		break;

	case WM_POWERBROADCAST:
		if(wParam==PBT_APMPOWERSTATUSCHANGE) {
			SYSTEM_POWER_STATUS powerstatus;
			GetSystemPowerStatus(&powerstatus);
			Message msg("PowerSupplyChange");
			switch(powerstatus.ACLineStatus) {
				case 0:
					msg.SetParam( "Online",false);
				break;

				case 1:
					msg.SetParam( "Online",true);
				break;

				default:
				case 255:
					msg.SetParam( "Online",false);
				break;
			}

			if(powerstatus.BatteryFlag & 8) {
				msg.SetParam( "Charging", true);
			} else {
				msg.SetParam( "Charging", false);
			}

			msg.SetParam( "BatteryExists", (powerstatus.BatteryFlag & 128) != 128);

			msg.SetParam( "BatteryCharge", (int)powerstatus.BatteryLifePercent);
			msg.SetParam( "BatteryLifetime", (int)powerstatus.BatteryLifeTime);
			msg.SetParam( "BatteryFullLifetime", (int)powerstatus.BatteryFullLifeTime);

			MESSAGEMAN->Broadcast( msg );
		}
		break;

	case WM_PAINT:
	{
		PAINTSTRUCT ps;
		BeginPaint( hWnd, &ps );
		EndPaint( hWnd, &ps );
		break;
	}

	case WM_KEYDOWN:
	case WM_KEYUP:
	case WM_SYSKEYDOWN:
	case WM_SYSKEYUP:
		/* We handle all input ourself, via DirectInput. */
		return 0;

	case WM_CLOSE:
		LOG->Trace("WM_CLOSE: shutting down");
		ArchHooks::SetUserQuit();
		return 0;

	case WM_WINDOWPOSCHANGED:
	{
		/* If we're fullscreen and don't have focus, our window is hidden, so GetClientRect
		 * isn't meaningful. */
		if( !g_CurrentParams.windowed && !g_bHasFocus )
			break;

		RECT rect;
		GetClientRect( hWnd, &rect );

		int iWidth = rect.right - rect.left;
		int iHeight = rect.bottom - rect.top;
		if( g_CurrentParams.width != iWidth || g_CurrentParams.height != iHeight )
		{
			g_CurrentParams.width = iWidth;
			g_CurrentParams.height = iHeight;
			g_bResolutionChanged = true;
		}
		break;
	}
	}

	CHECKPOINT_M( ssprintf("%p, %u, %08x, %08x", hWnd, msg, wParam, lParam) );

	if( m_bWideWindowClass )
		return DefWindowProcW( hWnd, msg, wParam, lParam );
	else
		return DefWindowProcA( hWnd, msg, wParam, lParam );
}
コード例 #29
0
ファイル: OptionRow.cpp プロジェクト: BitMax/openitg
CString ITEMS_LONG_ROW_X_NAME( size_t p )		{ return ssprintf("ItemsLongRowP%dX",int(p+1)); }
コード例 #30
0
void ScreenPackages::EnterURL( const CString & sURL )
{
	CString Proto;
	CString Server;
	int Port=80;
	CString sAddress;

	if( !ParseHTTPAddress( sURL, Proto, Server, Port, sAddress ) )
	{
		m_sStatus = "Invalid URL.";
		UpdateProgress();
		return;
	}

	//Determine if this is a website, or a package?
	//Criteria: does it end with *zip?
	if( sAddress.Right(3).CompareNoCase("zip") == 0 )
		m_bIsPackage=true;
	else
		m_bIsPackage = false;

	m_sBaseAddress = "http://" + Server;
	if( Port != 80 )
		m_sBaseAddress += ssprintf( ":%d", Port );
	m_sBaseAddress += "/";

	if( sAddress.Right(1) != "/" )
	{
		m_sEndName = Basename( sAddress );
		m_sBaseAddress += Dirname( sAddress );
	}
	else
	{
		m_sEndName = "";
	}

	//Open the file...

	//First find out if a file by this name already exists
	//if so, then we gotta ditch out.
	//XXX: This should be fixed by a prompt or something?

	//if we are not talking about a file, let's not worry
	if( m_sEndName != "" && m_bIsPackage )
	{
		CStringArray AddTo;
		GetDirListing( "Packages/"+m_sEndName, AddTo, false, false );
		if ( AddTo.size() > 0 )
		{
			m_sStatus = "File Already Exists";
			UpdateProgress();
			return;
		}

		if( !m_fOutputFile.Open( "Packages/"+m_sEndName, RageFile::WRITE | RageFile::STREAMED ) )
		{
			m_sStatus = m_fOutputFile.GetError();
			UpdateProgress();
			return;
		}
	}
	//Continue...

	sAddress = URLEncode( sAddress );

	if ( sAddress != "/" )
		sAddress = "/" + sAddress;

	m_wSocket.close();
	m_wSocket.create();

	m_wSocket.blocking = true;

	if( !m_wSocket.connect( Server, (short) Port ) )
	{
		m_sStatus = "Failed to connect.";
		UpdateProgress();
		return;
	}
	
	//Produce HTTP header

	CString Header="";

	Header = "GET "+sAddress+" HTTP/1.0\r\n";
	Header+= "Host: " + Server + "\r\n";
	Header+= "Connection: closed\r\n\r\n";

	m_wSocket.SendData( Header.c_str(), Header.length() );
	m_sStatus = "Header Sent.";
	m_wSocket.blocking = false;
	m_bIsDownloading = true;
	m_sBUFFER = "";
	m_bGotHeader = false;
	UpdateProgress();
	return;
}