Esempio n. 1
0
void SetupConfigDir(void)
{
	const char *cfg_p = GetConfigFilePath("");

	LOG(LM_MAIN, LL_INFO, "Creating config dir %s... ", cfg_p);

	if (mkdir_deep(cfg_p))
	{
		if (errno != EEXIST) LOG(LM_MAIN, LL_INFO, "Config dir created.");
		else LOG(LM_MAIN, LL_INFO, "Config dir already exists.");
	}
	else
	{
		switch (errno)
		{
			case EACCES:
				LOG(LM_MAIN, LL_WARN, "Permission denied");
				break;
			default:
				perror("Error creating config directory:");
				break;
		}
	}

	return;
}
Esempio n. 2
0
/*
 * LoadImgedConfig - get configuration from a profile file
 */
void LoadImgedConfig( void )
{
    settings_info       info;
    HINI                handle_inifile;

#ifdef __NT__
    GetConfigFilePath( iniPath, sizeof( iniPath ) );
    strcat( iniPath, "\\" WATCOM_INI );
#endif
    setDefaultValues( &info );

    /*
     * Image editor will ALWAYS maintain this setting ... which determines
     * whether or not all other settings will be saved.  Note that the
     * PM version opens the configuration file and the Windows version stores
     * the information in some kind of cache.
     */
    handle_inifile = _wpi_openinifile( Instance, iniPath );
    info.settings = _wpi_getprivateprofileint( handle_inifile, imgedSection,
                                               "profile", info.settings, iniPath );

    if( info.settings & SET_SAVE_POS ) {
        loadPositionValues( handle_inifile );
    }

    if( info.settings & SET_SAVE_SET ) {
        loadSettings( &info, handle_inifile );
    }
    _wpi_closeinifile( handle_inifile );
    SetSettingsDlg( &info );
    SetInitialOpenDir( info.opendir );
    SetInitialSaveDir( info.savedir );
    SetInitScreenColor( atol( info.color ) );

} /* LoadImgedConfig */
Esempio n. 3
0
/*
 * ReadConfig - read the configuration information
 */
void ReadConfig( void )
{
    char        msgfilter[MFILTER_LAST_MSG - MFILTER_FIRST_MSG + 2];
    char        cbfilter[CFILTER_LAST_MSG - CFILTER_FIRST_MSG + 2];
    char        buf[10];
    WORD        i;

    GetConfigFilePath( iniPath, sizeof( iniPath ) );
    strcat( iniPath, "\\" WATCOM_INI );

    setGlobalDefault();
    SetTrackWndDefault();
    SetMainWndDefault();

    Monitoring[MON_SENT_IND] = GetPrivateProfileInt( SECT_NAME, MONSENT, TRUE, iniPath );
    Monitoring[MON_POST_IND] = GetPrivateProfileInt( SECT_NAME, MONPOST, TRUE, iniPath );
    Monitoring[MON_CB_IND] = GetPrivateProfileInt( SECT_NAME, MONCB, TRUE, iniPath );
    Monitoring[MON_STR_IND] = GetPrivateProfileInt( SECT_NAME, MONSTR, TRUE, iniPath );
    Monitoring[MON_ERR_IND] = GetPrivateProfileInt( SECT_NAME, MONERR, TRUE, iniPath );
    Monitoring[MON_LNK_IND] = GetPrivateProfileInt( SECT_NAME, MONLNK, TRUE, iniPath );
    Monitoring[MON_CONV_IND] = GetPrivateProfileInt( SECT_NAME, MONCONV, TRUE, iniPath );

    /* global settings */

    ConfigInfo.scroll = GetPrivateProfileInt( SECT_NAME, CFG_SCROLL,
                                              ConfigInfo.scroll, iniPath );
    ConfigInfo.alias = GetPrivateProfileInt( SECT_NAME, CFG_ALIAS,
                                             ConfigInfo.alias, iniPath );
    ConfigInfo.screen_out = GetPrivateProfileInt( SECT_NAME, CFG_SCREEN,
                                                  ConfigInfo.screen_out, iniPath );
    ConfigInfo.show_tb = GetPrivateProfileInt( SECT_NAME, CFG_SHOW_TB,
                                               ConfigInfo.show_tb, iniPath );
    ConfigInfo.show_hints = GetPrivateProfileInt( SECT_NAME, CFG_SHOW_HINTS,
                                                  ConfigInfo.show_hints, iniPath );
    ConfigInfo.on_top = GetPrivateProfileInt( SECT_NAME, CFG_ON_TOP,
                                              ConfigInfo.on_top, iniPath );

    /* window size/pos info */
    for( i = 0; i < NO_TRK_WND; i++ ) {
        itoa( i, buf, 10 );
        readWindowInfo( Tracking + i, buf );
    }
    readWindowInfo( &MainWndConfig, MAIN_WND_EXT );

    /* filter info */
    memset( msgfilter, '1', sizeof( msgfilter ) );
    msgfilter[MFILTER_LAST_MSG - MFILTER_FIRST_MSG + 1] = '\0';
    memset( cbfilter, '1', sizeof( cbfilter ) );
    cbfilter[CFILTER_LAST_MSG - CFILTER_FIRST_MSG + 1] = '\0';
    GetPrivateProfileString( SECT_NAME, MSGFLTER, msgfilter, msgfilter,
                             MFILTER_LAST_MSG - MFILTER_FIRST_MSG + 2, iniPath );
    GetPrivateProfileString( SECT_NAME, CBFLTER, cbfilter, cbfilter,
                             CFILTER_LAST_MSG - CFILTER_FIRST_MSG + 2, iniPath );
    SetFilter( msgfilter, cbfilter );

    /* logging info */
    LoadLogConfig( iniPath, SECT_NAME );
    InitMonoFont( SECT_NAME, iniPath, SYSTEM_FIXED_FONT, Instance );

} /* ReadConfig */
Esempio n. 4
0
void LoadTemplates(void)
{
	FILE *f;
	int i, count;

	f = fopen(GetConfigFilePath("players.cnf"), "r");
	if (f) {
		int fscanfres;
		i = 0;
		fscanfres = fscanf(f, "%d\n", &count);
		if (fscanfres < 1) {
			printf("Error reading players.cnf count\n");
			fclose(f);
			return;
		}
		while (i < MAX_TEMPLATE && i < count) {
			fscanfres = fscanf(f, "[%[^]]] %d %d %d %d %d %d\n",
					   templates[i].name,
					   &templates[i].head,
					   &templates[i].body,
					   &templates[i].arms,
					   &templates[i].legs,
					   &templates[i].skin,
					   &templates[i].hair);
			if (fscanfres < 7)
			{
				printf("Error reading player %d\n", i);
				fclose(f);
				return;
			}
			i++;
		}
		fclose(f);
	}
}
int CTestClientServer::RunAlgorithm()
{
  try
  {
    int response = ImportInputData();
    RETURN_ASSERT_IF(!PinUpCustomData(), aiUnexpected);
    RETURN_ASSERT_IF(response != aiOk, response);

    // Initialize client
    int port;
    CAutoIGClient client;
    if (IsDebugExport())
      client.SetDebugExportPath(GetOutputPath());
    gml::Ref<Dashboard::IProgressBar> progress(new CDummyProgressBar());
    client.SetProgressBar(*progress);
    client.SetProjectInfo(*GetProject());
    RETURN_ASSERT_IF(!client.InitClient(port), aiUnexpected);

    // Try to start server
    if(CAutoIGServer::StartServerProcess(
      port, GetConfigFilePath(), false))
    {
      return client.PerformAllocation();
    }
    else
      return aiUnexpected;

    return aiOk; 
  }
  catch (CMemoryException* )
  {
    return aiOutOfMemory;
  };
};
Esempio n. 6
0
void SaveConfig(void)
{
	FILE *f;

	debug(D_NORMAL, "begin\n");

	f = fopen(GetConfigFilePath("options.cnf"), "w");

	if (f) {
		fprintf(f, "%d %d %d %d %d %d %d %d %d\n",
			gOptions.displayFPS,
			gOptions.displayTime,
			gOptions.playersHurt,
			gOptions.copyMode,
			gOptions.brightness,
			gOptions.swapButtonsJoy1,
			gOptions.swapButtonsJoy2,
			gOptions.xSplit, gOptions.ySplit);
		fprintf(f, "%d\n%d %d %d %d %d %d\n",
			gPlayer1Data.controls,
			gPlayer1Data.keys[0],
			gPlayer1Data.keys[1],
			gPlayer1Data.keys[2],
			gPlayer1Data.keys[3],
			gPlayer1Data.keys[4], gPlayer1Data.keys[5]);
		fprintf(f, "%d\n%d %d %d %d %d %d\n",
			gPlayer2Data.controls,
			gPlayer2Data.keys[0],
			gPlayer2Data.keys[1],
			gPlayer2Data.keys[2],
			gPlayer2Data.keys[3],
			gPlayer2Data.keys[4], gPlayer2Data.keys[5]);
		fprintf(f, "%d\n", gOptions.mapKey);
		fprintf(f, "%d %d %d %d\n",
			FXVolume(),
			MusicVolume(), FXChannels(), MinMusicChannels());
		fprintf(f, "%d\n", 0); // DynamicInterrupts
		fprintf(f, "%s\n", ModuleDirectory());
		fprintf(f, "%u\n", gCampaign.seed);
		fprintf(f, "%d %d\n", gOptions.difficulty,
			gOptions.slowmotion);
		fprintf(f, "%d\n", gOptions.density);
		fprintf(f, "%d\n", gOptions.npcHp);
		fprintf(f, "%d\n", gOptions.playerHp);
		fprintf(f, "%dx%d:%d:%d\n",
		       		Gfx_GetHint(HINT_WIDTH),
				Gfx_GetHint(HINT_HEIGHT),
				Gfx_GetHint(HINT_FULLSCREEN),
				Gfx_GetHint(HINT_SCALEFACTOR)
				);
		fclose(f);

		debug(D_NORMAL, "saved config\n");
	}

	return;
}
Esempio n. 7
0
void WREInitOpts( void )
{
    WRECurrentState = WREDefaultState;
    GetConfigFilePath( WREProfileName, sizeof( WREProfileName ) );
    strcat( WREProfileName, "\\" WATCOM_INI );
    WREReadOpts( &WRECurrentState );
    if( WRECurrentState.last_dir != NULL ) {
        WRESetInitialDir( WRECurrentState.last_dir );
    }
    WRESetFileFilter( WRECurrentState.last_filter );
}
Esempio n. 8
0
void LoadHighScores(void)
{
	int magic;
	FILE *f;
	int y, m, d;
	time_t t;
	struct tm *tp;

	debug(D_NORMAL, "Reading hi-scores...\n");

	memset(allTimeHigh, 0, sizeof(allTimeHigh));
	memset(todaysHigh, 0, sizeof(todaysHigh));

	f = fopen(GetConfigFilePath(SCORES_FILE), "rb");
	if (f != NULL) {
		size_t elementsRead;
	#define CHECK_FREAD(count)\
		if (elementsRead != count) {\
			debug(D_NORMAL, "Error reading scores file\n");\
			fclose(f);\
			return;\
		}
		elementsRead = fread(&magic, sizeof(magic), 1, f);
		CHECK_FREAD(1)
		if (magic != MAGIC) {
			debug(D_NORMAL, "Scores file magic doesn't match!\n");
			fclose(f);
			return;
		}
		
		//for (i = 0; i < MAX_ENTRY; i++) {
		elementsRead = fread(allTimeHigh, sizeof(allTimeHigh), 1, f);
		CHECK_FREAD(1)
		//}

		t = time(NULL);
		tp = localtime(&t);
		elementsRead = fread(&y, sizeof(y), 1, f);
		CHECK_FREAD(1)
		elementsRead = fread(&m, sizeof(m), 1, f);
		CHECK_FREAD(1)
		elementsRead = fread(&d, sizeof(d), 1, f);
		CHECK_FREAD(1)
		debug(D_NORMAL, "scores time, y: %d m: %d d: %d\n", y, m, d);	


		if (tp->tm_year == y && tp->tm_mon == m && tp->tm_mday == d) {
			elementsRead = fread(todaysHigh, sizeof(todaysHigh), 1, f);
			CHECK_FREAD(1)
			debug(D_NORMAL, "reading today's high: %d\n", todaysHigh[0].score);
		}

		fclose(f);
	} else {
Esempio n. 9
0
void WdeInitOpts( void )
{
    WdeCurrentState = WdeDefaultState;
    GetConfigFilePath( WdeProfileName, sizeof( WdeProfileName ) );
    strcat( WdeProfileName, "\\" WATCOM_INI );
    WdeReadOpts( &WdeCurrentState );
    if( WdeCurrentState.last_directory ) {
        WdeSetInitialDir( WdeCurrentState.last_directory );
    }
    WdeSetFileFilter( WdeCurrentState.last_file_filter );
}
Esempio n. 10
0
bool ScreenMissionSummary(CampaignOptions *c, struct MissionOptions *m)
{
	// Save password
	MissionSave ms;
	MissionSaveInit(&ms);
	ms.Campaign = c->Entry;
	// Don't make password for next level if there is none
	int passwordIndex = m->index + 1;
	if (passwordIndex == c->Entry.NumMissions)
	{
		passwordIndex--;
	}
	strcpy(ms.Password, MakePassword(passwordIndex, 0));
	ms.MissionsCompleted = m->index + 1;
	AutosaveAddMission(&gAutosave, &ms, ms.Campaign.BuiltinIndex);
	AutosaveSave(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));

	// Calculate bonus scores
	// Bonuses only apply if at least one player has lived
	if (AreAnySurvived())
	{
		int bonus = 0;
		// Objective bonuses
		for (int i = 0; i < (int)m->missionData->Objectives.size; i++)
		{
			const struct Objective *o = CArrayGet(&m->Objectives, i);
			const MissionObjective *mo = CArrayGet(&m->missionData->Objectives, i);
			if (o->done == mo->Count && o->done > mo->Required)
			{
				// Perfect
				bonus += PERFECT_BONUS;
			}
		}
		bonus += GetAccessBonus(m);
		bonus += GetTimeBonus(m, NULL);

		for (int i = 0; i < (int)gPlayerDatas.size; i++)
		{
			PlayerData *p = CArrayGet(&gPlayerDatas, i);
			ApplyBonuses(p, bonus);
		}
	}
	GameLoopWaitForAnyKeyOrButtonData wData;
	GameLoopData gData = GameLoopDataNew(
		&wData, GameLoopWaitForAnyKeyOrButtonFunc,
		m, MissionSummaryDraw);
	GameLoop(&gData);
	if (wData.IsOK)
	{
		SoundPlay(&gSoundDevice, StrSound("mg"));
	}
	return wData.IsOK;
}
Esempio n. 11
0
    void Conf::save()
    {
        gchar *file = GetConfigFilePath();
        GError *err = NULL;

        g_key_file_save_to_file(keys, file, &err);

        if (err != NULL)
            fprintf(stderr, "Error while saving config file: %d: %s\n", err->code, err->message);

        g_free(file);
    }
Esempio n. 12
0
    Conf::Conf()
    {
        gchar *file = GetConfigFilePath();
        GError *err = NULL;

        keys = g_key_file_new();

        g_key_file_load_from_file(keys, file, G_KEY_FILE_KEEP_COMMENTS, &err);

        if (err != NULL)
            fprintf(stderr, "Error while loading config file: %d: %s", err->code, err->message);

        g_free(file);

        /* set defualt values */
        #define GK_SET_DEFAULT_INT(g, k, d) if (!g_key_file_has_key(keys, g, k, NULL)) g_key_file_set_integer(keys, g, k, d)
        #define GK_SET_DEFAULT_BOOL(g, k, d) if (!g_key_file_has_key(keys, g, k, NULL)) g_key_file_set_boolean(keys, g, k, d)
        
        GK_SET_DEFAULT_INT("Game", "game-speed", 1);
        GK_SET_DEFAULT_INT("Game", "difficulty", 1);

        GK_SET_DEFAULT_BOOL("Game", "floating-jump",  false);
        GK_SET_DEFAULT_BOOL("Game", "show-text",      false);
        GK_SET_DEFAULT_BOOL("Game", "show-points",    false);
        GK_SET_DEFAULT_BOOL("Game", "immediate-mode", false);
        GK_SET_DEFAULT_BOOL("Game", "debug",          false);

        GK_SET_DEFAULT_INT("Display", "width",          800);
        GK_SET_DEFAULT_INT("Display", "height",         600);
        GK_SET_DEFAULT_INT("Display", "detail",         1  );
        GK_SET_DEFAULT_INT("Display", "decals",         0  );
        GK_SET_DEFAULT_INT("Display", "blood",          0  );
        GK_SET_DEFAULT_INT("Display", "damage-effects", 0  );
        GK_SET_DEFAULT_INT("Display", "velocity-blur",  0  );

        GK_SET_DEFAULT_BOOL("Display", "auto-slow-motion", true );
        GK_SET_DEFAULT_BOOL("Display", "trilinear",        false);
        GK_SET_DEFAULT_BOOL("Display", "vsync",            true );
        GK_SET_DEFAULT_BOOL("Display", "show-foliage",     true);
        GK_SET_DEFAULT_BOOL("Display", "always-blur",      false);
        GK_SET_DEFAULT_BOOL("Display", "motion-blur",      false);

        GK_SET_DEFAULT_INT("Sound", "volume", 80);

        GK_SET_DEFAULT_BOOL("Sound", "music",   true);
        GK_SET_DEFAULT_BOOL("Sound", "ambient", true);

        GK_SET_DEFAULT_INT("Mouse", "mouse-speed", 5);
        
        GK_SET_DEFAULT_BOOL("Mouse", "mouse-invert", false);
        GK_SET_DEFAULT_BOOL("Mouse", "mouse-jump",   false);
    }
Esempio n. 13
0
void loadOption(HWND nppHandle, StruOptions& struOptions)
{
    loadDefaultOption(struOptions);
    tstring tsConfigFilePath = GetConfigFilePath(nppHandle);

    IniFileProcessor processor(tsConfigFilePath);
    IniFileProcessor::IniMap map;

    map = processor.GetInfo(true);
    IniFileProcessor::IniMap::iterator itrEnd = map.end();

    if(map.find(keyPutCR) != itrEnd)
    {
        if(!map[keyPutCR].GetStrValue().compare("0"))
            struOptions.bPutCR = false;
    }

    if(map.find(keyChIndent) != itrEnd)
    {
        string strIndent = map[keyChIndent].GetStrValue();
        if(!strIndent.compare("tab"))
            struOptions.chIndent = '\t';
        else if(!strIndent.compare("space"))
            struOptions.chIndent = ' ';
    }

    if(map.find(keyChPerInd) != itrEnd)
    {
        struOptions.nChPerInd = atoi(map[keyChPerInd].GetStrValue().c_str());
    }

    if(map.find(keyNLBracket) != itrEnd)
    {
        if(!map[keyNLBracket].GetStrValue().compare("1"))
            struOptions.bNLBracket = true;
    }

    if(map.find(keyKeepTopComt) != itrEnd)
    {
        if(!map[keyKeepTopComt].GetStrValue().compare("1"))
            struOptions.bKeepTopComt = true;
    }

    if(map.find(keyIndentInEmpty) != itrEnd)
    {
        if(!map[keyIndentInEmpty].GetStrValue().compare("1"))
            struOptions.bIndentInEmpty = true;
    }
}
Esempio n. 14
0
void LoadPlayerTemplates(
	CArray *templates, const CharacterClasses *classes, const char *filename)
{
	// Note: not used, but included in function to express dependency
	CASSERT(classes->Classes.size > 0,
		"cannot load player templates without character classes");
	json_t *root = NULL;
	int version = 1;

	// initialise templates
	CArrayInit(templates, sizeof(PlayerTemplate));
	FILE *f = fopen(GetConfigFilePath(filename), "r");
	if (!f)
	{
		printf("Error loading player templates '%s'\n", filename);
		goto bail;
	}

	if (json_stream_parse(f, &root) != JSON_OK)
	{
		printf("Error parsing player templates '%s'\n", filename);
		goto bail;
	}

	LoadInt(&version, root, "Version");

	if (json_find_first_label(root, "PlayerTemplates") == NULL)
	{
		printf("Error: unknown player templates format\n");
		goto bail;
	}
	json_t *child = json_find_first_label(root, "PlayerTemplates")->child->child;
	while (child != NULL)
	{
		PlayerTemplate t;
		LoadPlayerTemplate(&t, child, version);
		child = child->next;
		CArrayPushBack(templates, &t);
	}

bail:
	json_free_value(&root);
	if (f != NULL)
	{
		fclose(f);
	}
}
Esempio n. 15
0
void LoadHighScores(void)
{
	int magic;
	FILE *f;
	int y, m, d;
	time_t t;
	struct tm *tp;

	debug(D_NORMAL, "Reading hi-scores...\n");

	memset(allTimeHigh, 0, sizeof(allTimeHigh));
	memset(todaysHigh, 0, sizeof(todaysHigh));

	f = fopen(GetConfigFilePath(SCORES_FILE), "rb");
	if (f != NULL) {
		fread(&magic, sizeof(magic), 1, f);
		if (magic != MAGIC) {
			debug(D_NORMAL, "Scores file magic doesn't match!\n");
			fclose(f);
			return;
		}
		
		//for (i = 0; i < MAX_ENTRY; i++) {
		fread(allTimeHigh, sizeof(allTimeHigh), 1, f);
		//}

		t = time(NULL);
		tp = localtime(&t);
		fread(&y, sizeof(y), 1, f);
		fread(&m, sizeof(m), 1, f);
		fread(&d, sizeof(d), 1, f);
		debug(D_NORMAL, "scores time, y: %d m: %d d: %d\n", y, m, d);	


		if (tp->tm_year == y && tp->tm_mon == m && tp->tm_mday == d) {
			fread(todaysHigh, sizeof(todaysHigh), 1, f);
			debug(D_NORMAL, "reading today's high: %d\n", todaysHigh[0].score);
		}

		fclose(f);
	} else {
		printf("Unable to open %s\n", SCORES_FILE);
	}
}
Esempio n. 16
0
Bool WInit( HINSTANCE inst )
{
    Bool ok;

    ok = (inst != (HINSTANCE)NULL);

    if( ok ) {
        WCtl3DInit( inst );
        ok = JDialogInit();
    }

    if( ok ) {
        ok = WRegisterMainClass( inst );
    }

    if( ok ) {
        ok = WRegisterPrevClass( inst );
    }

    if( ok ) {
        ok = WInitStatusLines( inst );
    }

    if( ok ) {
        WClipbdFormat = RegisterClipboardFormat( WR_CLIPBD_MENU );
        ok = (WClipbdFormat != 0);
    }

    if( ok ) {
        WItemClipbdFormat = RegisterClipboardFormat( WItemClipbdFmt );
        ok = (WItemClipbdFormat != 0);
    }

    if( ok ) {
        GetConfigFilePath( WProfileName, sizeof( WProfileName ) );
        strcat( WProfileName, "\\" WATCOM_INI );
        WInitOpts( WProfileName, WSectionName );
        WInitEditWindows( inst );
        ok = WInitRibbons( inst );
    }

    return( ok );
}
Esempio n. 17
0
static void loadSampleConfiguration(void)
{
	int i;
	FILE *f;


	f = fopen(GetConfigFilePath("sound_fx.cfg"), "r");
	if (!f)
		return;

	printf("Reading SOUND_FX.CFG\n");
	for (i = 0; i < SND_COUNT; i++) {
		memset(snd[i].name, 0, sizeof(snd[i].name));
		fscanf(f, "%80s %d\n", snd[i].name, &snd[i].freq);
		printf("%2d. File:'%s' at %dHz\n", i, snd[i].name,
		       snd[i].freq);
	}
	fclose(f);
}
Esempio n. 18
0
void saveOption(HWND nppHandle, StruOptions struOptions)
{
    tstring tsConfigFilePath = GetConfigFilePath(nppHandle);

    IniFileProcessor processor(tsConfigFilePath);
    IniFileProcessor::IniMap map;

    map[keyPutCR] = IniValue(struOptions.bPutCR ? string("1") : string("0"));
    map[keyChIndent] = IniValue(struOptions.chIndent == '\t' ? string("tab") : string("space"));
    char buffer[256];
    itoa(struOptions.nChPerInd, buffer, 10);
    map[keyChPerInd] = IniValue(string(buffer));
    map[keyNLBracket] = IniValue(struOptions.bNLBracket ? string("1") : string("0"));
    map[keyKeepTopComt] = IniValue(struOptions.bKeepTopComt ? string("1") : string("0"));
    map[keyIndentInEmpty] = IniValue(struOptions.bIndentInEmpty ? string("1") : string("0"));

    processor.SetMap(map);

    processor.Save();
}
Esempio n. 19
0
void LoadPlayerTemplates(CArray *templates, const char *filename)
{
	json_t *root = NULL;

	// initialise templates
	CArrayInit(templates, sizeof(PlayerTemplate));
	FILE *f = fopen(GetConfigFilePath(filename), "r");
	if (!f)
	{
		printf("Error loading player templates '%s'\n", filename);
		goto bail;
	}

	if (json_stream_parse(f, &root) != JSON_OK)
	{
		printf("Error parsing player templates '%s'\n", filename);
		goto bail;
	}

	if (json_find_first_label(root, "PlayerTemplates") == NULL)
	{
		printf("Error: unknown player templates format\n");
		goto bail;
	}
	json_t *child = json_find_first_label(root, "PlayerTemplates")->child->child;
	while (child != NULL)
	{
		PlayerTemplate t;
		LoadPlayerTemplate(&t, child);
		child = child->next;
		CArrayPushBack(templates, &t);
	}

bail:
	json_free_value(&root);
	if (f != NULL)
	{
		fclose(f);
	}
}
Esempio n. 20
0
void LoadTemplates(void)
{
	FILE *f;
	int i, count;

	f = fopen(GetConfigFilePath("players.cnf"), "r");
	if (f) {
		i = 0;
		fscanf(f, "%d\n", &count);
		while (i < MAX_TEMPLATE && i < count) {
			fscanf(f, "[%[^]]] %d %d %d %d %d %d\n",
			       templates[i].name,
			       &templates[i].head,
			       &templates[i].body,
			       &templates[i].arms,
			       &templates[i].legs,
			       &templates[i].skin, &templates[i].hair);
			i++;
		}
		fclose(f);
	}
}
Esempio n. 21
0
void SetupConfigDir(void)
{
	const char *cfg_p = GetConfigFilePath("");

	printf("Creating Config dir... ");

	if (mkdir_deep(cfg_p) == 0)
	{
		if (errno != EEXIST)
			printf("Config dir created.\n");
		else
			printf("No need. Already exists!\n");
	} else {
		switch (errno) {
			case EACCES:
				printf("Permission denied!\n");
				break;
			default:
				perror("Error creating config directory:");
		}
	}

	return;
}
Esempio n. 22
0
void SaveHighScores(void)
{
	int magic;
	FILE *f;
	time_t t;
	struct tm *tp;

	debug(D_NORMAL, "begin\n");

	f = fopen(GetConfigFilePath(SCORES_FILE), "wb");
	if (f != NULL) {
		magic = MAGIC;

		fwrite(&magic, sizeof(magic), 1, f);
		fwrite(allTimeHigh, sizeof(allTimeHigh), 1, f);

		t = time(NULL);
		tp = localtime(&t);
		debug(D_NORMAL, "time now, y: %d m: %d d: %d\n", tp->tm_year, tp->tm_mon, tp->tm_mday);

		magic = tp->tm_year;
		fwrite(&magic, sizeof(magic), 1, f);
		magic = tp->tm_mon;
		fwrite(&magic, sizeof(magic), 1, f);
		magic = tp->tm_mday;
		fwrite(&magic, sizeof(magic), 1, f);

		debug(D_NORMAL, "writing today's high: %d\n", todaysHigh[0].score);
		fwrite(todaysHigh, sizeof(todaysHigh), 1, f);

		fclose(f);

		debug(D_NORMAL, "saved high scores\n");
	} else
		printf("Unable to open %s\n", SCORES_FILE);
}
Esempio n. 23
0
void SaveTemplates(void)
{
	FILE *f;
	int i;

	debug(D_NORMAL, "begin\n");

	f = fopen(GetConfigFilePath("players.cnf"), "w");
	if (f) {
		fprintf(f, "%d\n", MAX_TEMPLATE);
		for (i = 0; i < MAX_TEMPLATE; i++) {
			fprintf(f, "[%s] %d %d %d %d %d %d\n",
				templates[i].name,
				templates[i].head,
				templates[i].body,
				templates[i].arms,
				templates[i].legs,
				templates[i].skin, templates[i].hair);
		}
		fclose(f);

		debug(D_NORMAL, "saved templates\n");
	}
}
Esempio n. 24
0
bool ScreenMissionSummary(
	CampaignOptions *c, struct MissionOptions *m, const bool completed)
{
	if (completed)
	{
		// Save password
		MissionSave ms;
		MissionSaveInit(&ms);
		ms.Campaign = c->Entry;
		// Don't make password for next level if there is none
		int passwordIndex = m->index + 1;
		if (passwordIndex == c->Entry.NumMissions)
		{
			passwordIndex--;
		}
		strcpy(ms.Password, MakePassword(passwordIndex, 0));
		ms.MissionsCompleted = m->index + 1;
		AutosaveAddMission(&gAutosave, &ms);
		AutosaveSave(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));
	}

	// Calculate bonus scores
	// Bonuses only apply if at least one player has lived
	if (AreAnySurvived())
	{
		int bonus = 0;
		// Objective bonuses
		CA_FOREACH(const Objective, o, m->missionData->Objectives)
			if (ObjectiveIsPerfect(o))
			{
				bonus += PERFECT_BONUS;
			}
		CA_FOREACH_END()
		bonus += GetAccessBonus(m);
		bonus += GetTimeBonus(m, NULL);

		CA_FOREACH(PlayerData, p, gPlayerDatas)
			ApplyBonuses(p, bonus);
		CA_FOREACH_END()
	}
	MenuSystem ms;
	const int h = FontH() * 10;
	MenuSystemInit(
		&ms, &gEventHandlers, &gGraphicsDevice,
		Vec2iNew(0, gGraphicsDevice.cachedConfig.Res.y - h),
		Vec2iNew(gGraphicsDevice.cachedConfig.Res.x, h));
	ms.current = ms.root = MenuCreateNormal("", "", MENU_TYPE_NORMAL, 0);
	// Use return code 0 for whether to continue the game
	if (completed)
	{
		MenuAddSubmenu(ms.root, MenuCreateReturn("Continue", 0));
	}
	else
	{
		MenuAddSubmenu(ms.root, MenuCreateReturn("Replay mission", 0));
		MenuAddSubmenu(ms.root, MenuCreateReturn("Back to menu", 1));
	}
	ms.allowAborts = true;
	MenuAddExitType(&ms, MENU_TYPE_RETURN);
	MenuSystemAddCustomDisplay(&ms, MissionSummaryDraw, m);
	MenuLoop(&ms);
	return ms.current->u.returnCode == 0;
}
Esempio n. 25
0
int main(int argc, char *argv[])
{
	int i;
	int loaded = 0;

	printf("C-Dogs SDL Editor\n");

	debug(D_NORMAL, "Initialising SDL...\n");
	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO) != 0)
	{
		printf("Failed to start SDL!\n");
		return -1;
	}
	SDL_EnableUNICODE(SDL_ENABLE);

	printf("Data directory:\t\t%s\n",	GetDataFilePath(""));
	printf("Config directory:\t%s\n\n",	GetConfigFilePath(""));

	EditorBrushInit(&brush);

	ConfigLoadDefault(&gConfig);
	ConfigLoad(&gConfig, GetConfigFilePath(CONFIG_FILE));
	gConfig.Graphics.IsEditor = 1;
	if (!PicManagerTryInit(
		&gPicManager, "graphics/cdogs.px", "graphics/cdogs2.px"))
	{
		exit(0);
	}
	memcpy(origPalette, gPicManager.palette, sizeof origPalette);
	BuildTranslationTables(gPicManager.palette);
	TextManagerInit(&gTextManager, GetDataFilePath("graphics/font.px"));
	GraphicsInit(&gGraphicsDevice);
	// Hardcode config settings
	gConfig.Graphics.ScaleMode = SCALE_MODE_NN;
	gConfig.Graphics.ScaleFactor = 2;
	gConfig.Graphics.Res.x = 400;
	gConfig.Graphics.Res.y = 300;
	GraphicsInitialize(
		&gGraphicsDevice, &gConfig.Graphics, gPicManager.palette, 0);
	if (!gGraphicsDevice.IsInitialized)
	{
		printf("Video didn't init!\n");
		exit(EXIT_FAILURE);
	}
	TextManagerGenerateOldPics(&gTextManager, &gGraphicsDevice);
	PicManagerLoadDir(&gPicManager, GetDataFilePath("graphics"));

	BulletInitialize();
	WeaponInitialize(&gGunDescriptions, GetDataFilePath("guns.json"));
	CampaignInit(&gCampaign);
	MissionInit(&lastMission);
	MissionInit(&currentMission);

	PlayerDataInitialize();
	MapInit(&gMap);

	// initialise UI collections
	// Note: must do this after text init since positions depend on text height
	sObjs = CreateMainObjs(&gCampaign, &brush, Vec2iNew(320, 240));
	memset(&sDrawObjs, 0, sizeof sDrawObjs);
	DrawBufferInit(&sDrawBuffer, Vec2iNew(X_TILES, Y_TILES), &gGraphicsDevice);

	// Reset campaign (graphics init may have created dummy campaigns)
	CampaignSettingTerminate(&gCampaign.Setting);
	CampaignSettingInit(&gCampaign.Setting);

	EventInit(&gEventHandlers, NULL, false);

	for (i = 1; i < argc; i++)
	{
		if (!loaded)
		{
			debug(D_NORMAL, "Loading map %s\n", argv[i]);
			memset(lastFile, 0, sizeof(lastFile));
			strncpy(lastFile, argv[i], sizeof(lastFile) - 1);
			if (strchr(lastFile, '.') == NULL &&
				sizeof lastFile - strlen(lastFile) > 3)
			{
				strcat(lastFile, ".CPN");
			}
			if (MapNewLoad(lastFile, &gCampaign.Setting) == 0)
			{
				loaded = 1;
			}
			debug(D_NORMAL, "Loaded map %s\n", argv[i]);
		}
	}

	debug(D_NORMAL, "Starting editor\n");
	EditCampaign();

	MapTerminate(&gMap);
	WeaponTerminate(&gGunDescriptions);
	CampaignTerminate(&gCampaign);
	MissionTerminate(&lastMission);
	MissionTerminate(&currentMission);

	DrawBufferTerminate(&sDrawBuffer);
	GraphicsTerminate(&gGraphicsDevice);
	PicManagerTerminate(&gPicManager);
	TextManagerTerminate(&gTextManager);

	UIObjectDestroy(sObjs);
	CArrayTerminate(&sDrawObjs);
	EditorBrushTerminate(&brush);

	SDL_Quit();

	exit(EXIT_SUCCESS);
}
Esempio n. 26
0
bool GameOptions(const GameMode gm)
{
	// Create selection menus
	const int w = gGraphicsDevice.cachedConfig.Res.x;
	const int h = gGraphicsDevice.cachedConfig.Res.y;
	MenuSystem ms;
	MenuSystemInit(
		&ms, &gEventHandlers, &gGraphicsDevice,
		Vec2iZero(), Vec2iNew(w, h));
	ms.align = MENU_ALIGN_CENTER;
	ms.allowAborts = true;
	AllowedWeaponsData awData;
	AllowedWeaponsDataInit(&awData, &gMission.Weapons);
	switch (gm)
	{
	case GAME_MODE_DEATHMATCH:
		ms.root = ms.current = MenuCreateNormal(
			"",
			"",
			MENU_TYPE_OPTIONS,
			0);
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Game.PlayerHP"));
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Deathmatch.Lives"));
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Game.HealthPickups"));
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Game.Ammo"));
		MenuAddSubmenu(ms.current,
			MenuCreateAllowedWeapons("Weapons...", &awData));
		MenuAddSubmenu(ms.current, MenuCreateSeparator(""));
		MenuAddSubmenu(ms.current, MenuCreateReturn("Done", 0));
		break;
	case GAME_MODE_DOGFIGHT:
		ms.root = ms.current = MenuCreateNormal(
			"",
			"",
			MENU_TYPE_OPTIONS,
			0);
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Dogfight.PlayerHP"));
		MenuAddConfigOptionsItem(
			ms.current, ConfigGet(&gConfig, "Dogfight.FirstTo"));
		MenuAddSubmenu(ms.current,
			MenuCreateAllowedWeapons("Weapons...", &awData));
		MenuAddSubmenu(ms.current, MenuCreateSeparator(""));
		MenuAddSubmenu(ms.current, MenuCreateReturn("Done", 0));
		break;
	default:
		CASSERT(false, "unknown game mode");
		break;
	}
	MenuAddExitType(&ms, MENU_TYPE_RETURN);

	MenuLoop(&ms);

	const bool ok = !ms.hasAbort;
	if (ok)
	{
		ConfigApply(&gConfig);

		// Save options for later
		ConfigSave(&gConfig, GetConfigFilePath(CONFIG_FILE));

		// Set allowed weapons
		// First check if the player has unwittingly disabled all weapons
		// if so, enable all weapons
		bool allDisabled = true;
		for (int i = 0, j = 0; i < (int)awData.allowed.size; i++, j++)
		{
			const bool *allowed = CArrayGet(&awData.allowed, i);
			if (*allowed)
			{
				allDisabled = false;
				break;
			}
		}
		if (!allDisabled)
		{
			for (int i = 0, j = 0; i < (int)awData.allowed.size; i++, j++)
			{
				const bool *allowed = CArrayGet(&awData.allowed, i);
				if (!*allowed)
				{
					CArrayDelete(&gMission.Weapons, j);
					j--;
				}
			}
		}
	}
	AllowedWeaponsDataTerminate(&awData);
	MenuSystemTerminate(&ms);
	return ok;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
	UNUSED(argc);
	UNUSED(argv);

	if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) != 0)
	{
		fprintf(stderr, "Could not initialise SDL: %s\n", SDL_GetError());
		return -1;
	}
	if (SDLNet_Init() == -1)
	{
		fprintf(stderr, "SDLNet_Init: %s\n", SDLNet_GetError());
		exit(EXIT_FAILURE);
	}
	if (!SDL_SetVideoMode(320, 200, 0, 0))
	{
		fprintf(stderr, "Could not set video mode: %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	ConfigLoadDefault(&gConfig);
	ConfigLoad(&gConfig, GetConfigFilePath(CONFIG_FILE));
	EventInit(&gEventHandlers, NULL, false);

	NetInputClient client;
	NetInputClientInit(&client);
	NetInputClientConnect(&client, 0x7F000001);	// localhost

	printf("Press esc to exit\n");

	Uint32 ticksNow = SDL_GetTicks();
	Uint32 ticksElapsed = 0;
	for (;;)
	{
		Uint32 ticksThen = ticksNow;
		ticksNow = SDL_GetTicks();
		ticksElapsed += ticksNow - ticksThen;
		if (ticksElapsed < 1000 / FPS_FRAMELIMIT)
		{
			SDL_Delay(1);
			debug(D_VERBOSE, "Delaying 1 ticksNow %u elapsed %u\n", ticksNow, ticksElapsed);
			continue;
		}
		EventPoll(&gEventHandlers, SDL_GetTicks());
		int cmd = GetOnePlayerCmd(
			&gEventHandlers,
			&gConfig.Input.PlayerKeys[0],
			false,
			INPUT_DEVICE_KEYBOARD,
			0);
		if (cmd)
		{
			printf("Sending %s + %s\n",
				CmdStr(cmd & (CMD_LEFT | CMD_RIGHT | CMD_UP | CMD_DOWN)),
				CmdStr(cmd & (CMD_BUTTON1 | CMD_BUTTON2 | CMD_BUTTON3 | CMD_BUTTON4 | CMD_ESC)));
			NetInputClientSend(&client, cmd);
		}

		// Check keyboard escape
		if (KeyIsPressed(&gEventHandlers.keyboard, SDLK_ESCAPE))
		{
			break;
		}

		ticksElapsed -= 1000 / FPS_FRAMELIMIT;
	}

	NetInputClientTerminate(&client);
	EventTerminate(&gEventHandlers);
	SDLNet_Quit();
	SDL_Quit();
	return 0;
}
Esempio n. 28
0
int main(void)
{
	char config_file[MAX_PATH];
	MediaSniffer ms;
	Config cfg;
	
	char errbuf[PCAP_ERRBUF_SIZE];
	pcap_if_t *alldevs;
	pcap_if_t *d;
	pcap_addr_t *a;
	int inum;
	int i;

	GetConfigFilePath( "mediasniffer.ini", config_file );
	if( !LoadConfig( config_file, &cfg ) )
		{
		if( pcap_findalldevs( &alldevs, errbuf ) == -1 )
			{
			printf( "Error in pcap_findalldevs: %s\n", errbuf );
			return -1;
			}//end if

		// show adapter list
		for( i = 0, d = alldevs; d != NULL; d = d->next, ++i )
			{
			for( a = d->addresses; a != NULL; a = a->next )
				{
				if( a->addr->sa_family == AF_INET )
					{
					break;
					}//end if
				}//end for
			printf( "%d. %s %s\n\t", i + 1,
				(a != NULL) ? inet_ntoa( reinterpret_cast<struct sockaddr_in*>(a->addr)->sin_addr ) : "N/A",
				d->name );
			if( d->description != NULL )
				{
				printf( "(%s)\n", d->description );
				}
			else{
				puts( "(No description available)" );
				}//end if
			}//end for
		
		if( i == 0 )
			{
			printf(
#ifdef OS_IS_LINUX
				"Be sure to run as root!\n"
#else // Windows
				"No interfaces found! Make sure WinPcap is installed.\n"
#endif
				);
			return -1;
			}//end if

		// let the user choose an adapter
		printf( "Enter the interface number (1 ~ %d): ", i );
		scanf( "%d", &inum );
		getchar();
		
		if( inum < 1 || inum > i )
			{
			printf("\nInterface number out of range.\n");
			/* Free the device list */
			pcap_freealldevs( alldevs );
			return -1;
			}//end if

		// jump to it
		for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);

		strcpy( cfg.adapter, d->name );
		SaveConfig( config_file, &cfg );
		}//end if

	ms.set_show_rec( Record, NULL );

	if( ms.StartSniff( cfg.adapter, cfg.dst_port, cfg.filterwords, cfg.filteridurl ) )
		{
		puts( "Sniff start. Press ENTER to exit" );
		getchar();
		ms.StopSniff();
		}
	else{
		puts( "Failed to start sniff!" );
		}//end if

	return 0;
}//end main
Esempio n. 29
0
/*
 * LoadSpyConfig - get configuration from a profile file
 */
void LoadSpyConfig( char *fname )
{
    char        *str, *vals;
    int         i, j, k;
    int         x, y;
    int         check;

    str = alloca( TotalMessageArraySize + 1 );
    vals = alloca( TotalMessageArraySize + 1 );
    for( i = 0; i < FILTER_ENTRIES; i++ ) {
        Filters[i].flag[M_WATCH] = TRUE;
        Filters[i].flag[M_STOPON] = FALSE;
    }
    if( fname == NULL ) {
        GetConfigFilePath( iniPath, sizeof( iniPath ) );
        strcat( iniPath, "\\" WATCOM_INI );
        fname = iniPath;
        LoadLogConfig( fname, spyApp );
        InitMonoFont( spyApp, fname, SYSTEM_FIXED_FONT, Instance );

        x = GetSystemMetrics( SM_CXSCREEN );
        y = GetSystemMetrics( SM_CYSCREEN );

        /* set defaults */
        SpyMainWndInfo.xpos = x / 8 - x / 16;
        SpyMainWndInfo.ypos = y / 8;
        SpyMainWndInfo.xsize = 3 * (x / 4) + x / 8;
        SpyMainWndInfo.ysize = 3 * (y / 4);
        SpyMainWndInfo.on_top = false;
        SpyMainWndInfo.show_hints = true;
        SpyMainWndInfo.show_toolbar = true;

        /* load configured values */
        SpyMainWndInfo.xpos = GetPrivateProfileInt( spyApp, "wnd_xpos",
                                                    SpyMainWndInfo.xpos, fname );
        SpyMainWndInfo.ypos = GetPrivateProfileInt( spyApp, "wnd_ypos",
                                                    SpyMainWndInfo.ypos, fname );
        SpyMainWndInfo.xsize = GetPrivateProfileInt( spyApp, "wnd_xsize",
                                                     SpyMainWndInfo.xsize, fname );
        SpyMainWndInfo.ysize = GetPrivateProfileInt( spyApp, "wnd_ysize",
                                                     SpyMainWndInfo.ysize, fname );
        SpyMainWndInfo.on_top = GetPrivateProfileInt( spyApp, "wnd_topmost", SpyMainWndInfo.on_top, fname ) != 0;
        SpyMainWndInfo.show_hints = GetPrivateProfileInt( spyApp, "show_hint", SpyMainWndInfo.show_hints, fname ) != 0;
        SpyMainWndInfo.show_toolbar = GetPrivateProfileInt( spyApp, "show_toolbar", SpyMainWndInfo.show_toolbar, fname ) != 0;
    }

    /*
     * what specific messages to watch
     */
    memset( vals, '1', TotalMessageArraySize );
    vals[TotalMessageArraySize] = 0;
    GetPrivateProfileString( spyApp, "watch", vals, str,
                             TotalMessageArraySize + 1, fname );

    for( j = 0, i = 0; j < ClassMessagesSize; j++ ) {
        for( k = 0; k < ClassMessages[j].message_array_size; k++ ) {
            ClassMessages[j].message_array[k].bits[M_WATCH] = ( str[i++]  != '0');
        }
    }

    /*
     * what specific messages to stop on
     */
    memset( vals, '0', TotalMessageArraySize );
    GetPrivateProfileString( spyApp, "stopon", vals, str,
                             TotalMessageArraySize + 1, fname );
    for( j = 0, i = 0; j < ClassMessagesSize; j++ ) {
        for( k = 0; k < ClassMessages[j].message_array_size; k++ ) {
            ClassMessages[j].message_array[k].bits[M_STOPON] = ( str[i++]  == '1');
        }
    }

    /*
     * what message classes to watch
     */
    memset( vals, '1', FILTER_ENTRIES );
    vals[FILTER_ENTRIES] = 0;
    GetPrivateProfileString( spyApp, "watchclasses", vals, str,
                             FILTER_ENTRIES + 1, fname );
    for( i = 0; i < FILTER_ENTRIES; i++ ) {
        Filters[i].flag[M_WATCH] = ( str[i]  != '0');
    }

    /*
     * what message classes to stopon
     */
    memset( vals, '0', FILTER_ENTRIES );
    GetPrivateProfileString( spyApp, "stoponclasses", vals, str,
                             FILTER_ENTRIES + 1, fname );
    for( i = 0; i < FILTER_ENTRIES; i++ ) {
        Filters[i].flag[M_STOPON] = ( str[i] == '1' );
    }

    /*
     * get misc info
     */
    vals[0] = '1';
    vals[1] = 0;
    GetPrivateProfileString( spyApp, "autosavecfg", vals, str, 2, fname );
    AutoSaveConfig = ( str[0]  != '0');
    if( AutoSaveConfig ) {
        check = MF_CHECKED;
    } else {
        check = MF_UNCHECKED;
    }
    CheckMenuItem( SpyMenu, SPY_MESSAGES_ASCFG, check );

} /* LoadSpyConfig */
Esempio n. 30
0
int main(int argc, char *argv[])
{
	int wait = 0;
	int controllerFlag = SDL_INIT_GAMECONTROLLER;
	credits_displayer_t creditsDisplayer;
	memset(&creditsDisplayer, 0, sizeof creditsDisplayer);
	custom_campaigns_t campaigns;
	memset(&campaigns, 0, sizeof campaigns);
	int forceResolution = 0;
	int err = 0;
	const char *loadCampaign = NULL;
	ENetAddress connectAddr;
	memset(&connectAddr, 0, sizeof connectAddr);

	srand((unsigned int)time(NULL));
	LogInit();

	PrintTitle();

	if (getenv("DEBUG") != NULL)
	{
		debug = true;
		char *dbg;
		if ((dbg = getenv("DEBUG_LEVEL")) != NULL)
		{
			debug_level = CLAMP(atoi(dbg), D_NORMAL, D_MAX);
		}
	}

	SetupConfigDir();
	gConfig = ConfigLoad(GetConfigFilePath(CONFIG_FILE));
	LoadCredits(&creditsDisplayer, colorPurple, colorDarker);
	AutosaveInit(&gAutosave);
	AutosaveLoad(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));

	if (enet_initialize() != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "An error occurred while initializing ENet.");
		err = EXIT_FAILURE;
		goto bail;
	}
	NetClientInit(&gNetClient);

	// Print command line
	char buf[CDOGS_PATH_MAX];
	buf[0] = '\0';
	for (int i = 0; i < argc; i++)
	{
		strcat(buf, " ");
		// HACK: for OS X, blank out the -psn_XXXX argument so that it doesn't
		// break arg parsing
	#ifdef __APPLE__
		if (strncmp(argv[i], "-psn", strlen("-psn")) == 0)
		{
			argv[i] = "";
		}
	#endif
		strcat(buf, argv[i]);
	}
	LOG(LM_MAIN, LL_INFO, "Command line (%d args):%s", argc, buf);
	{
		struct option longopts[] =
		{
			{"fullscreen",	no_argument,		NULL,	'f'},
			{"scale",		required_argument,	NULL,	's'},
			{"screen",		required_argument,	NULL,	'c'},
			{"forcemode",	no_argument,		NULL,	'o'},
			{"nosound",		no_argument,		NULL,	'n'},
			{"nojoystick",	no_argument,		NULL,	'j'},
			{"wait",		no_argument,		NULL,	'w'},
			{"shakemult",	required_argument,	NULL,	'm'},
			{"connect",		required_argument,	NULL,	'x'},
			{"debug",		required_argument,	NULL,	'd'},
			{"log",			required_argument,	NULL,	1000},
			{"help",		no_argument,		NULL,	'h'},
			{0,				0,					NULL,	0}
		};
		int opt = 0;
		int idx = 0;
		while ((opt = getopt_long(argc, argv, "fs:c:onjwm:xd\0h", longopts, &idx)) != -1)
		{
			switch (opt)
			{
			case 'f':
				ConfigGet(&gConfig, "Graphics.Fullscreen")->u.Bool.Value = true;
				break;
			case 's':
				ConfigSetInt(&gConfig, "Graphics.ScaleFactor", atoi(optarg));
				break;
			case 'c':
				sscanf(optarg, "%dx%d",
					&ConfigGet(&gConfig, "Graphics.ResolutionWidth")->u.Int.Value,
					&ConfigGet(&gConfig, "Graphics.ResolutionHeight")->u.Int.Value);
				LOG(LM_MAIN, LL_DEBUG, "Video mode %dx%d set...",
					ConfigGetInt(&gConfig, "Graphics.ResolutionWidth"),
					ConfigGetInt(&gConfig, "Graphics.ResolutionHeight"));
				break;
			case 'o':
				forceResolution = 1;
				break;
			case 'n':
				LOG(LM_MAIN, LL_INFO, "Sound to 0 volume");
				ConfigGet(&gConfig, "Sound.SoundVolume")->u.Int.Value = 0;
				ConfigGet(&gConfig, "Sound.MusicVolume")->u.Int.Value = 0;
				break;
			case 'j':
				debug(D_NORMAL, "nojoystick\n");
				controllerFlag = 0;
				break;
			case 'w':
				wait = 1;
				break;
			case 'm':
				{
					ConfigGet(&gConfig, "Graphics.ShakeMultiplier")->u.Int.Value =
						MAX(atoi(optarg), 0);
					printf("Shake multiplier: %d\n",
						ConfigGetInt(&gConfig, "Graphics.ShakeMultiplier"));
				}
				break;
			case 'h':
				PrintHelp();
				goto bail;
			case 'd':
				// Set debug level
				debug = true;
				debug_level = CLAMP(atoi(optarg), D_NORMAL, D_MAX);
				break;
			case 1000:
				{
					char *comma = strchr(optarg, ',');
					if (comma)
					{
						// Set logging level for a single module
						// The module and level are comma separated
						*comma = '\0';
						const LogLevel ll = StrLogLevel(comma + 1);
						LogModuleSetLevel(StrLogModule(optarg), ll);
						printf("Logging %s at %s\n", optarg, LogLevelName(ll));
					}
					else
					{
						// Set logging level for all modules
						const LogLevel ll = StrLogLevel(optarg);
						for (int i = 0; i < (int)LM_COUNT; i++)
						{
							LogModuleSetLevel((LogModule)i, ll);
						}
						printf("Logging everything at %s\n", LogLevelName(ll));
					}
				}
				break;
			case 'x':
				if (enet_address_set_host(&connectAddr, optarg) != 0)
				{
					printf("Error: unknown host %s\n", optarg);
				}
				break;
			default:
				PrintHelp();
				// Ignore unknown arguments
				break;
			}
		}
		if (optind < argc)
		{
			// non-option ARGV-elements
			for (; optind < argc; optind++)
			{
				// Load campaign
				loadCampaign = argv[optind];
			}
		}
	}

	debug(D_NORMAL, "Initialising SDL...\n");
	const int sdlFlags =
		SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_HAPTIC;
	if (SDL_Init(sdlFlags | controllerFlag) != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "Could not initialise SDL: %s", SDL_GetError());
		err = EXIT_FAILURE;
		goto bail;
	}
	if (SDLJBN_Init() != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "Could not initialise SDLJBN: %s",
			SDLJBN_GetError());
		err = EXIT_FAILURE;
		goto bail;
	}
	SDL_EventState(SDL_DROPFILE, SDL_DISABLE);

	GetDataFilePath(buf, "");
	LOG(LM_MAIN, LL_INFO, "data dir(%s)", buf);
	LOG(LM_MAIN, LL_INFO, "config dir(%s)", GetConfigFilePath(""));

	SoundInitialize(&gSoundDevice, "sounds");
	if (!gSoundDevice.isInitialised)
	{
		LOG(LM_MAIN, LL_ERROR, "Sound initialization failed!");
	}

	LoadHighScores();

	debug(D_NORMAL, "Loading song lists...\n");
	LoadSongs();

	MusicPlayMenu(&gSoundDevice);

	EventInit(&gEventHandlers, NULL, NULL, true);
	NetServerInit(&gNetServer);

	if (wait)
	{
		printf("Press the enter key to continue...\n");
		getchar();
	}
	if (!PicManagerTryInit(
		&gPicManager, "graphics/cdogs.px", "graphics/cdogs2.px"))
	{
		LOG(LM_MAIN, LL_ERROR, "Failed to initialize graphics");
		err = EXIT_FAILURE;
		goto bail;
	}
	memcpy(origPalette, gPicManager.palette, sizeof(origPalette));
	GraphicsInit(&gGraphicsDevice, &gConfig);
	GraphicsInitialize(&gGraphicsDevice, forceResolution);
	if (!gGraphicsDevice.IsInitialized)
	{
		LOG(LM_MAIN, LL_WARN, "Cannot initialise video; trying default config");
		ConfigResetDefault(ConfigGet(&gConfig, "Graphics"));
		GraphicsInit(&gGraphicsDevice, &gConfig);
		GraphicsInitialize(&gGraphicsDevice, forceResolution);
	}
	if (!gGraphicsDevice.IsInitialized)
	{
		LOG(LM_MAIN, LL_ERROR, "Video didn't init!");
		err = EXIT_FAILURE;
		goto bail;
	}
	FontLoadFromJSON(&gFont, "graphics/font.png", "graphics/font.json");
	PicManagerLoadDir(&gPicManager, "graphics");

	ParticleClassesInit(&gParticleClasses, "data/particles.json");
	AmmoInitialize(&gAmmo, "data/ammo.json");
	BulletAndWeaponInitialize(
		&gBulletClasses, &gGunDescriptions,
		"data/bullets.json", "data/guns.json");
	CharacterClassesInitialize(&gCharacterClasses, "data/character_classes.json");
	LoadPlayerTemplates(
		&gPlayerTemplates, &gCharacterClasses, PLAYER_TEMPLATE_FILE);
	PickupClassesInit(
		&gPickupClasses, "data/pickups.json", &gAmmo, &gGunDescriptions);
	MapObjectsInit(&gMapObjects, "data/map_objects.json");
	CollisionSystemInit(&gCollisionSystem);
	CampaignInit(&gCampaign);
	LoadAllCampaigns(&campaigns);
	PlayerDataInit(&gPlayerDatas);

	GrafxMakeRandomBackground(
		&gGraphicsDevice, &gCampaign, &gMission, &gMap);

	debug(D_NORMAL, ">> Entering main loop\n");
	// Attempt to pre-load campaign if requested
	if (loadCampaign != NULL)
	{
		LOG(LM_MAIN, LL_INFO, "Loading campaign %s...", loadCampaign);
		gCampaign.Entry.Mode =
			strstr(loadCampaign, "/" CDOGS_DOGFIGHT_DIR "/") != NULL ?
			GAME_MODE_DOGFIGHT : GAME_MODE_NORMAL;
		CampaignEntry entry;
		if (!CampaignEntryTryLoad(&entry, loadCampaign, GAME_MODE_NORMAL) ||
			!CampaignLoad(&gCampaign, &entry))
		{
			LOG(LM_MAIN, LL_ERROR, "Failed to load campaign %s", loadCampaign);
		}
	}
	else if (connectAddr.host != 0)
	{
		if (NetClientTryScanAndConnect(&gNetClient, connectAddr.host))
		{
			ScreenWaitForCampaignDef();
		}
		else
		{
			printf("Failed to connect\n");
		}
	}
	LOG(LM_MAIN, LL_INFO, "Starting game");
	MainLoop(&creditsDisplayer, &campaigns);

bail:
	debug(D_NORMAL, ">> Shutting down...\n");
	MapTerminate(&gMap);
	PlayerDataTerminate(&gPlayerDatas);
	MapObjectsTerminate(&gMapObjects);
	PickupClassesTerminate(&gPickupClasses);
	ParticleClassesTerminate(&gParticleClasses);
	AmmoTerminate(&gAmmo);
	WeaponTerminate(&gGunDescriptions);
	BulletTerminate(&gBulletClasses);
	CharacterClassesTerminate(&gCharacterClasses);
	MissionOptionsTerminate(&gMission);
	NetClientTerminate(&gNetClient);
	atexit(enet_deinitialize);
	EventTerminate(&gEventHandlers);
	GraphicsTerminate(&gGraphicsDevice);

	PicManagerTerminate(&gPicManager);
	FontTerminate(&gFont);
	AutosaveSave(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));
	AutosaveTerminate(&gAutosave);
	ConfigSave(&gConfig, GetConfigFilePath(CONFIG_FILE));
	SavePlayerTemplates(&gPlayerTemplates, PLAYER_TEMPLATE_FILE);
	CArrayTerminate(&gPlayerTemplates);
	FreeSongs(&gMenuSongs);
	FreeSongs(&gGameSongs);
	SaveHighScores();
	UnloadCredits(&creditsDisplayer);
	UnloadAllCampaigns(&campaigns);
	CampaignTerminate(&gCampaign);
	SoundTerminate(&gSoundDevice, true);
	ConfigDestroy(&gConfig);

	SDLJBN_Quit();
	SDL_Quit();

	return err;
}