コード例 #1
0
ファイル: client.cpp プロジェクト: xinderuila1/speed-dream
void NetClient::ReadRaceSetupPacket(ENetPacket *pPacket)
{
    GfLogTrace("\nRecieving race setup\n");

    SetRaceInfoChanged(true);
}
コード例 #2
0
void
RmNetworkClientMenu(void * /* dummy */)
{
	GfLogTrace("Entering Network Client menu.\n");
	
	ShowWaitingToConnectScreen();
	
	if (!NetGetClient())
	{
		NetSetServer(false);
		NetSetClient(true);

		NetDriver driver;
		GetHumanDriver(driver,1);
		driver.client = true;
		driver.active = true;
		strcpy(driver.name,g_strDriver.c_str());
		if (!NetGetClient()->ConnectToServer((char*)g_strHostIP.c_str(),SPEEDDREAMSPORT,&driver))
		{
			//failed so back to connect menu
			NetworkClientConnectMenu(NULL);
			return;
		}

		//NetGetClient()->SendDriverInfoPacket(&driver);
	}

	if (racemanMenuHdle)
		GfuiScreenRelease(racemanMenuHdle);

	racemanMenuHdle = GfuiScreenCreate(NULL,  NULL, (tfuiCallback)OnActivateNetworkClient, 
									   NULL, (tfuiCallback)NULL, 1);

	void *mparam = GfuiMenuLoad("networkclientmenu.xml");
	GfuiMenuCreateStaticControls(racemanMenuHdle, mparam);

	GfuiMenuDefaultKeysAdd(racemanMenuHdle);

	RmSetRacemanMenuHandle(racemanMenuHdle);

	g_trackHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"trackname");

	g_lapsHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"lapcountname");
	g_catHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"carcatname");

	g_OutlineId = GfuiMenuCreateStaticImageControl(racemanMenuHdle,mparam,"outlineimage");
	
	//Show players
	for (int i = 0; i < MAXNETWORKPLAYERS; i++) 
	{
		char buf[1024];
		sprintf(buf,"ready%i",i);
		g_readystatus[i] = GfuiMenuCreateStaticImageControl(racemanMenuHdle,mparam,buf);
		GfuiVisibilitySet(racemanMenuHdle,g_readystatus[i],false);

		sprintf(buf,"driver%i",i);
		g_playerNames[i] = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,buf);
		GfuiLabelSetText(racemanMenuHdle,g_playerNames[i],"");

		sprintf(buf,"car%i",i);
		g_carNames[i] =  GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,buf);
		GfuiLabelSetText(racemanMenuHdle,g_carNames[i],"");
	}

	g_ReadyCheckboxId =
		GfuiMenuCreateCheckboxControl(racemanMenuHdle, mparam, "playerreadycheckbox",
									  NULL, onClientPlayerReady);
	g_CarSetupButtonId =
		GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "garage",
									racemanMenuHdle, rmCarSettingsMenu);

	g_DisconnectButtonId =
		GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "disconnect",
									NULL,rmNetworkClientDisconnect);

	GfParmReleaseHandle(mparam);

	UpdateNetworkPlayers();
	
	GfuiScreenActivate(racemanMenuHdle);
	
	GfuiApp().eventLoop().setRecomputeCB(ClientIdle);
}
コード例 #3
0
ファイル: racetrack.cpp プロジェクト: 702nADOS/speed-dreams
/** Dump the track segments on screen
    @param  track track to dump
    @param  verbose if set to 1 all the segments are described (long)
    @ingroup  racemantools
 */
static void
reTrackDump(const tTrack *track, int verbose)
{
	char buf[128];
	
	snprintf(buf, sizeof(buf), "  by %s (%.0f m long, %.0f m wide) ...", 
			 track->authors, track->length, track->width);
	ReUI().addLoadingMessage(buf);

	GfLogInfo("++++++++++++ Track ++++++++++++\n");
	GfLogInfo("Name     = %s\n", track->name);
	GfLogInfo("Authors  = %s\n", track->authors);
	GfLogInfo("Filename = %s\n", track->filename);
	GfLogInfo("NSeg     = %d\n", track->nseg);
	GfLogInfo("Version  = %d\n", track->version);
	GfLogInfo("Length   = %f m\n", track->length);
	GfLogInfo("Width    = %f m\n", track->width);
	GfLogInfo("XSize    = %f m\n", track->max.x);
	GfLogInfo("YSize    = %f m\n", track->max.y);
	GfLogInfo("ZSize    = %f m\n", track->max.z);
  
	switch (track->pits.type) {
		case TR_PIT_NONE:
			GfLogInfo("Pits     = none\n");
			break;
      
		case TR_PIT_ON_TRACK_SIDE:
			GfLogInfo("Pits     = present on track side\n");
			break;
      
		case TR_PIT_ON_SEPARATE_PATH:
			GfLogInfo("Pits     = present on separate path\n");
			break;

		case TR_PIT_NO_BUILDING:
			GfLogInfo("Pits     = present, no building style\n");
			break;
    }//switch pits.type

	const int seconds = (int)track->local.timeofday;
	GfLogInfo("TimeOfDay= %02d:%02d:%02d\n", seconds / 3600, (seconds % 3600) / 60, seconds % 60);
	GfLogInfo("Sun asc. = %.1f d\n", RAD2DEG(track->local.sunascension));
	GfLogInfo("Clouds   = %d (0=none, 1=few, 2=scarce, 3=many, 4=full)\n", track->local.clouds);
	GfLogInfo("Rain     = %d (0=none, 1=little, 2=medium, 3=heavy)\n", track->local.rain);
	GfLogInfo("Water    = %d (0=none, 1=some, 2=more, 3=swampy)\n", track->local.water);

	if (verbose) {
		int i;
		tTrackSeg *seg;
#ifdef SD_DEBUG
		const char  *stype[4] = { "", "RGT", "LFT", "STR" };
#endif

		for (i = 0, seg = track->seg->next; i < track->nseg; i++, seg = seg->next) {
			GfLogTrace("  segment %d -------------- \n", seg->id);
#ifdef SD_DEBUG
			GfLogTrace("        type    %s\n", stype[seg->type]);
#endif
			GfLogTrace("        length  %f m\n", seg->length);
			GfLogTrace("  radius  %f m\n", seg->radius);
			GfLogTrace("  arc %f d Zs %f d Ze %f d Zcs %f d\n", RAD2DEG(seg->arc),
					   RAD2DEG(seg->angle[TR_ZS]),
					   RAD2DEG(seg->angle[TR_ZE]),
					   RAD2DEG(seg->angle[TR_CS]));
			GfLogTrace(" Za  %f d\n", RAD2DEG(seg->angle[TR_ZS]));
			GfLogTrace("  vertices: %-8.8f %-8.8f %-8.8f ++++ ",
					   seg->vertex[TR_SR].x,
					   seg->vertex[TR_SR].y,
					   seg->vertex[TR_SR].z);
			GfLogTrace("%-8.8f %-8.8f %-8.8f\n",
					   seg->vertex[TR_SL].x,
					   seg->vertex[TR_SL].y,
					   seg->vertex[TR_SL].z);
			GfLogTrace("  vertices: %-8.8f %-8.8f %-8.8f ++++ ",
					   seg->vertex[TR_ER].x,
					   seg->vertex[TR_ER].y,
					   seg->vertex[TR_ER].z);
			GfLogTrace("%-8.8f %-8.8f %-8.8f\n",
					   seg->vertex[TR_EL].x,
					   seg->vertex[TR_EL].y,
					   seg->vertex[TR_EL].z);
			GfLogTrace("  prev    %d\n", seg->prev->id);
			GfLogTrace("  next    %d\n", seg->next->id);
		}//for i
		GfLogTrace("From Last To First\n");
		GfLogTrace("Dx = %-8.8f  Dy = %-8.8f Dz = %-8.8f\n",
				   track->seg->next->vertex[TR_SR].x - track->seg->vertex[TR_ER].x,
				   track->seg->next->vertex[TR_SR].y - track->seg->vertex[TR_ER].y,
				   track->seg->next->vertex[TR_SR].z - track->seg->vertex[TR_ER].z);
    }//if verbose
}//reTrackDump
コード例 #4
0
ファイル: client.cpp プロジェクト: xinderuila1/speed-dream
void NetClient::ReadPlayerAcceptedPacket(ENetPacket *pPacket)
{
    m_eClientAccepted = CLIENTACCEPTED;
    GfLogTrace ("Server accepted connection.\n");
}
コード例 #5
0
/** 
 * RmShowStandings
 * 
 * Shows a results page, with optional prev/next results page buttons
 * 
 * @param prevHdle	handle for previous results page
 * @param info	race results information
 * @param start	page number
*/
void
RmShowStandings(void *prevHdle, tRmInfo *info, int start)
{
	int			i;
	static char		buf[256];
	static char		path[512];
	void		*results = info->results;

	GfLogTrace("Entering Standings menu\n");

    // Create screen, load menu XML descriptor and create static controls.
	rmScrHdle = GfuiScreenCreate();
	void *hmenu = GfuiMenuLoad("standingsmenu.xml");
	GfuiMenuCreateStaticControls(rmScrHdle, hmenu);

    // Create variable title label (with group info for the Career mode).
	const int titleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Title");
	GfRaceManager* pRaceMan = LmRaceEngine().race()->getManager();
	if (pRaceMan->hasSubFiles())
	{
		const char* pszGroup = GfParmGetStr(info->params, RM_SECT_HEADER, RM_ATTR_NAME, "<no group>");
		snprintf(buf, sizeof(buf), "%s - %s", info->_reName, pszGroup);
	}
	else
		snprintf(buf, sizeof(buf), "%s", info->_reName);
	GfuiLabelSetText(rmScrHdle, titleId, buf);

    // Create variable subtitle label.
	const char* pszSessionName;
	const char* pszTrackName;
	if (pRaceMan->hasSubFiles())
	{
		// Career mode : Can't rely on GfRaceManager/GfRace, they don't support Career mode yet.
		pszSessionName = info->_reRaceName;
		const int curTrackIdx =
			(int)GfParmGetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_TRACK, NULL, 1) - 1;
		snprintf(path, sizeof(path), "%s/%d", RM_SECT_TRACKS, curTrackIdx);
		pszTrackName = GfParmGetStr(info->params, path, RM_ATTR_NAME, "<unkown track>");
	}
	else
	{
		// Non-Career mode : The session is the _last_ one ; the track is the _previous_ one.
		const unsigned nCurrEventIndex =
			(unsigned)GfParmGetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_TRACK, NULL, 1);
		pszSessionName =
			pRaceMan->getSessionName(pRaceMan->getSessionCount() - 1).c_str();
		pszTrackName =
			pRaceMan->getPreviousEventTrack(nCurrEventIndex - 1)->getName().c_str();
	}
	snprintf(buf, sizeof(buf), "%s at %s", pszSessionName, pszTrackName);
	const int subTitleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "SubTitle");
	GfuiLabelSetText(rmScrHdle, subTitleId, buf);

	// Get layout properties.
    const int nMaxLines = (int)GfuiMenuGetNumProperty(hmenu, "nMaxResultLines", 15);
    const int yTopLine = (int)GfuiMenuGetNumProperty(hmenu, "yTopLine", 400);
    const int yLineShift = (int)GfuiMenuGetNumProperty(hmenu, "yLineShift", 20);

	// List results line by line, paginated
	int y = yTopLine;
	const int nbCars = (int)GfParmGetEltNb(results, RE_SECT_STANDINGS);
	for (i = start; i < MIN(start + nMaxLines, nbCars); i++) {
		snprintf(path, sizeof(path), "%s/%d", RE_SECT_STANDINGS, i + 1);

        //Rank
        snprintf(buf, sizeof(buf), "%d", i+1);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Rank", true, // From template.
								   buf, GFUI_TPL_X, y);

        //Driver short name
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverName", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_SNAME, ""), GFUI_TPL_X, y);

        //Driver type
        const std::string strModName = GfParmGetStr(results, path, RE_ATTR_MODULE, "");
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverType", true, // From template.
								   GfDriver::getType(strModName).c_str(), GFUI_TPL_X, y);

        //Car
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "CarModel", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_CAR, ""), GFUI_TPL_X, y);


		//Points
		snprintf(buf, sizeof(buf), "%d", (int)GfParmGetNum(results, path, RE_ATTR_POINTS, NULL, 0));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Points", true, // From template.
								   buf, GFUI_TPL_X, y);

		// Next line.
		y -= yLineShift;	//Next line
	}//for i

	// If not on first page, show 'previous results' button on the bottom left
	if (start > 0) {
		RmPrevRace.prevHdle = prevHdle;
		RmPrevRace.info     = info;
		RmPrevRace.start    = start - nMaxLines;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "PreviousPageArrow",
				    (void*)&RmPrevRace, rmChgStandingScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEUP, "Previous Results", (void*)&RmPrevRace, rmChgStandingScreen, NULL);
	}//if start

	// Add "Continue" button in the bottom left
	GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "ContinueButton", prevHdle, GfuiScreenReplace);
    
	// Add "save" button in the bottom right, but disable it when Career mode.
	rmSaveButtonId = GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "SaveButton", info, rmSaveRes);
	if (LmRaceEngine().race()->getManager()->hasSubFiles())
		GfuiEnable(rmScrHdle, rmSaveButtonId, GFUI_DISABLE);

	// If there is a next page, show 'next results' button on the bottom extreme right
	if (i < nbCars) {
		RmNextRace.prevHdle = prevHdle;
		RmNextRace.info     = info;
		RmNextRace.start    = start + nMaxLines;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "NextPageArrow",
				    (void*)&RmNextRace, rmChgStandingScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEDOWN, "Next Results", (void*)&RmNextRace, rmChgStandingScreen, NULL);
	}//if i

    GfuiAddKey(rmScrHdle, GFUIK_ESCAPE, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_RETURN, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F1, "Help", rmScrHdle, GfuiHelpScreen, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F12, "Take a Screen Shot", NULL, GfuiScreenShot, NULL);

    GfuiScreenActivate(rmScrHdle);
}//RmShowStandings
コード例 #6
0
int
RePreRace(void)
{
	char path[128];
	const char *raceName;
	const char *raceType;
	void *params = ReInfo->params;
	void *results = ReInfo->results;
	int curRaceIdx;
	int timedLapsReplacement = 0;
	char *prevRaceName;
	
	raceName = ReInfo->_reRaceName = ReGetCurrentRaceName();
	
	GfParmRemoveVariable (params, "/", "humanInGroup");
	GfParmRemoveVariable (params, "/", "eventNb");
	GfParmSetVariable (params, "/", "humanInGroup", ReHumanInGroup() ? 1.0f : 0.0f);
	GfParmSetVariable (params, "/", "eventNb", GfParmGetNum (ReInfo->results, RE_SECT_CURRENT, RE_ATTR_CUR_TRACK, NULL, 1.0 ) );
	if (!raceName) {
		return RM_ERROR;
	}

	if (strcmp(GfParmGetStr(params, raceName, RM_ATTR_ENABLED, RM_VAL_YES), RM_VAL_NO) == 0) {
		GfLogTrace( "Race %s disabled\n",  raceName);
		curRaceIdx = (int)GfParmGetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_RACE, NULL, 1);
		if (curRaceIdx < GfParmGetEltNb(params, RM_SECT_RACES)) {
			curRaceIdx++;
			GfLogTrace( "Race %s is not the last one, but the #%d\n",  raceName, curRaceIdx);
			GfParmSetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_RACE, NULL, (tdble)curRaceIdx);
	
			return RM_SYNC | RM_NEXT_RACE;
		}
	
		GfParmSetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_RACE, NULL, 1);
		return RM_SYNC | RM_NEXT_RACE | RM_NEXT_STEP;
	}

	// Get session max dammages.
	ReInfo->s->_maxDammage = (int)GfParmGetNum(params, raceName, RM_ATTR_MAX_DMG, NULL, 10000);

	// Get session type (race, qualification or practice).
	raceType = GfParmGetStr(params, raceName, RM_ATTR_TYPE, RM_VAL_RACE);
	if (!strcmp(raceType, RM_VAL_RACE)) {
		ReInfo->s->_raceType = RM_TYPE_RACE;
	} else if (!strcmp(raceType, RM_VAL_QUALIF)) {
		ReInfo->s->_raceType = RM_TYPE_QUALIF;
	} else if (!strcmp(raceType, RM_VAL_PRACTICE)) {
		ReInfo->s->_raceType = RM_TYPE_PRACTICE;
	}

	// Get session duration (defaults to "All sessions" one, or else -60).
	ReInfo->s->_totTime = GfParmGetNum(params, raceName, RM_ATTR_SESSIONTIME, NULL, -1);
	if (ReInfo->s->_totTime < 0)
		ReInfo->s->_totTime = GfParmGetNum(params, RM_VAL_ANYRACE, RM_ATTR_SESSIONTIME, NULL, -60.0f);

	// Determine the actual session duration and/or number of laps.
	ReInfo->s->_extraLaps = 0; // TODO: Does this is ever needed ?
	ReInfo->s->_totLaps = 0; // Make sure it is initialized

	if (ReInfo->s->_totTime > 0 && !(ReInfo->s->_features & RM_FEATURE_TIMEDSESSION)) {
		// Timed session not supported: add 1 km for every minute in parctise or qualifying,
		// and 150 km for every hour (2.5 km for every minute) in race
		if (ReInfo->s->_raceType == RM_TYPE_RACE) {
			ReInfo->s->_totLaps = (int)floor(ReInfo->s->_totTime * 2500.0f / 60.0f / ReInfo->track->length + 0.5f);
		} else {
			ReInfo->s->_totLaps = (int)floor(ReInfo->s->_totTime * 1000.0f / 60.0f / ReInfo->track->length + 0.5f);
		}
		timedLapsReplacement = ReInfo->s->_totLaps;
		ReInfo->s->_totTime = -60.0f;
	}
	
	// Timed session doesn't exclude additional laps after the time finishes
	// Make sure that if no time set, we set far below zero
	if(ReInfo->s->_totTime <= 0.0f )
		ReInfo->s->_totTime = -60.0f;
		
	// Get session distance (defaults to "All sessions" one, or else 0).
	tdble dist = GfParmGetNum(params, raceName, RM_ATTR_DISTANCE, NULL, -1);
	if (dist < 0)
		dist = GfParmGetNum(params, RM_VAL_ANYRACE, RM_ATTR_DISTANCE, NULL, 0);
	
	// If a (> 0) session distance was specified, deduce the number of laps
	// in case the race settings don't specify it, and it is not a timed race.
	if ( (dist >= 0.001) && (ReInfo->s->_totTime < 0.0f) ) { // Why not 'if (dist > 0)' ???
		ReInfo->s->_totLaps = (int)(dist / ReInfo->track->length) + 1;
		ReInfo->s->_extraLaps = ReInfo->s->_totLaps; // Extralaps are used to find out how many laps there are after the time is up in timed sessions
	} else {dist = -1;}
	
	// Get the number of laps (defaults to "All sessions" one,
	// or else the already computed one from the session distance, or 0).
	int laps = (int)GfParmGetNum(params, raceName, RM_ATTR_LAPS, NULL, -1);
	if (laps < 0)
		laps = (int)GfParmGetNum(params, RM_VAL_ANYRACE, RM_ATTR_LAPS, NULL, 0);

	// Use lap number only when race distance is not in use.
	if ( (laps > 0) && (dist <= 0.0) && (timedLapsReplacement <= 0) ) {
		ReInfo->s->_totLaps = laps;
		ReInfo->s->_extraLaps = ReInfo->s->_totLaps; //Extralaps are used to find out how many laps there are after the time is up in timed sessions
	}

	// Make sure we have at least 1 lap race length.
	if ( (laps <= 0) && (dist <=0) && (ReInfo->s->_totTime < 0) ) {
		ReInfo->s->_totLaps = 1;
		ReInfo->s->_extraLaps = ReInfo->s->_totLaps; //Extralaps are used to find out how many laps there are after the time is up in timed sessions
	}

	// Correct extra laps (possible laps run after the winner arrived ?) :
	// during timed practice or qualification, there are none.
	if (ReInfo->s->_raceType != RM_TYPE_RACE && ReInfo->s->_totTime > 0) {
		ReInfo->s->_extraLaps = 0; //Extralaps are used to find out how many laps there are after the time is up in timed sessions
		ReInfo->s->_totLaps = 0;
	}

	GfLogInfo("Race length : time=%.0fs, laps=%d (extra=%d)\n",
			  ReInfo->s->_totTime, ReInfo->s->_totLaps, ReInfo->s->_extraLaps);
	
	// Initialize race state.
	ReInfo->s->_raceState = 0;

	// Cleanup results
	snprintf(path, sizeof(path), "%s/%s/%s", ReInfo->track->name, RE_SECT_RESULTS, raceName);
	GfParmListClean(results, path);

	// Drivers starting order
	// The starting order is decided here,
	// then car indexes are stored in ReStartingOrderIdx, in the starting order.
	// The actual grid is assembled in ReRaceStart().
	// In case of a race, when all cars start at the same time,
	// cars are simply added to the starting list in the order stored in ReStartingOrderIdx.
	// If only one car is at the track at a time (not timed session qualifying or practice),
	// the race is divided into many sub-races.
	// For a sub-race, only the car pointed by results/RE_ATTR_CUR_DRIVER
	// is added to the starting grid.
	// RE_ATTR_CUR_DRIVER is refreshed after every sub-race in ReRaceEnd().
	ReCurrDriverNr = 0;
	int nCars = GfParmGetEltNb(params, RM_SECT_DRIVERS);
	GfParmListClean(params, RM_SECT_DRIVERS_RACING);
	if (nCars == 0)
	{
		// This may happen, when playing with the text-only mode,
		// and forgetting that human are automatically excluded then,
		// or when getting back to the GUI mode, and not reconfiguring the competitors list.
		GfLogError("No competitor in this race : cancelled.\n");
		return RM_ERROR;
	}
	else
	{
		ReUI().addLoadingMessage("Determining Starting Order ...");

		const char* gridType =
			GfParmGetStr(params, raceName, RM_ATTR_START_ORDER, RM_VAL_DRV_LIST_ORDER);
		
		int maxCars = (int)GfParmGetNum(params, raceName, RM_ATTR_MAX_DRV, NULL, 100);
		nCars = MIN(nCars, maxCars);
		
		tReGridPart *GridList = NULL;
		int nGridList = 0;
		
		// Initialize the array of car indexes for starting order
		if (ReStartingOrderIdx != NULL) {
			delete[] ReStartingOrderIdx;
			ReStartingOrderIdx = NULL;
		}
		ReStartingOrderIdx = new int[nCars];
		for (int i = 0; i < nCars; i++) {
			ReStartingOrderIdx[i] = -1;
		}
		
		// Starting grid in the arrival order of the previous race (or qualification session)
		if (!strcmp(gridType, RM_VAL_LAST_RACE_ORDER))
		{
			GfLogTrace("Starting grid in the order of the last race\n");
			
			prevRaceName = ReGetPrevRaceName(/* bLoop = */false);
			if (!prevRaceName) {
				return RM_ERROR;
			}

			for (int i = 1; i < nCars + 1; i++) {
				snprintf(path, sizeof(path), "%s/%s/%s/%s/%d",
						 ReInfo->track->name, RE_SECT_RESULTS, prevRaceName, RE_SECT_RANK, i);
				ReStartingOrderIdx[i-1] = 
					ReFindDriverIdx (GfParmGetStr(results, path, RE_ATTR_MODULE, ""),
									(int)GfParmGetNum(results, path, RE_ATTR_IDX, NULL, 0));
			}
		}
		
		// Starting grid in the reversed arrival order of the previous race
		else if (!strcmp(gridType, RM_VAL_LAST_RACE_RORDER))
		{
			GfLogTrace("Starting grid in the reverse order of the last race\n");

			prevRaceName = ReGetPrevRaceName(/* bLoop = */false);
			if (!prevRaceName) {
				return RM_ERROR;
			}

			for (int i = 1; i < nCars + 1; i++) {
				snprintf(path, sizeof(path), "%s/%s/%s/%s/%d",
						ReInfo->track->name, RE_SECT_RESULTS, prevRaceName, RE_SECT_RANK, nCars - i + 1);
				ReStartingOrderIdx[i-1] = 
					ReFindDriverIdx (GfParmGetStr(results, path, RE_ATTR_MODULE, ""),
									(int)GfParmGetNum(results, path, RE_ATTR_IDX, NULL, 0));
			}
		}

		// Starting grid as a mix from the results of earlier sessions
		else if (ReParseStartingOrder(gridType, &GridList, nCars, nGridList))
		{
			GfLogTrace("Starting grid as a mix from the results of earlier sessions\n");
			
			int idx;
			int gridpos = 1;
			int carnr;
			const char *modulename;
			for (int i = 0; i < nGridList; i++) {
				if (gridpos > nCars) {break;}
				if (GridList[i].diffpos == -1) {//reversed
					for ( int j = GridList[i].startpos; j >= GridList[i].endpos; j--) {
						if (gridpos > nCars) {break;}
						snprintf(path, sizeof(path), "%s/%s/%s/%s/%d",
								ReInfo->track->name, RE_SECT_RESULTS, GridList[i].racename, RE_SECT_RANK, j);
						idx = (int)GfParmGetNum(results, path, RE_ATTR_IDX, NULL, 0);
						modulename = GfParmGetStr(results, path, RE_ATTR_MODULE, "");
						carnr = ReFindDriverIdx(modulename, idx);
						for (int k = 0; k < gridpos-1; k++) {
							if ( carnr == ReStartingOrderIdx[k] ) {
								//oops: same car twice
								GfLogWarning("The same car appears twice in the advanced grid!\n");
								carnr = -1;
								break;
							}
						}
						//adding car to the list
						if (carnr != -1) {
							ReStartingOrderIdx[gridpos-1] = carnr;
							gridpos++;
						}
					}
				} else if (GridList[i].diffpos == 1){//straight order
					for ( int j = GridList[i].startpos; j <= GridList[i].endpos; j++) {
						if (gridpos > nCars) {break;}
						snprintf(path, sizeof(path), "%s/%s/%s/%s/%d",
								ReInfo->track->name, RE_SECT_RESULTS, GridList[i].racename, RE_SECT_RANK, j);
						idx = (int)GfParmGetNum(results, path, RE_ATTR_IDX, NULL, 0);
						modulename = GfParmGetStr(results, path, RE_ATTR_MODULE, "");
						carnr = ReFindDriverIdx(modulename, idx);
						for (int k = 0; k < gridpos-1; k++) {
							if ( carnr == ReStartingOrderIdx[k] ) {
								//oops: same car twice
								GfLogWarning("The same car appears twice in the advanced grid!\n");
								carnr = -1;
								break;
							}
						}
						//adding car to the list
						if (carnr != -1) {
							ReStartingOrderIdx[gridpos-1] = carnr;
							gridpos++;
						}
					}
				}
			}
			//cleaning up memory
			if (nGridList > 0){delete[] GridList;}
		}

		// Starting grid in the drivers list order
		else
		{
			GfLogTrace("Starting grid in the order of the driver list\n");

			for (int i = 1; i < nCars + 1; i++) {
				snprintf(path, sizeof(path), "%s/%d", RM_SECT_DRIVERS, i);
				ReStartingOrderIdx[i-1] = 
					ReFindDriverIdx (GfParmGetStr(params, path, RE_ATTR_MODULE, ""),
									(int)GfParmGetNum(params, path, RE_ATTR_IDX, NULL, 0));
			}
		}
	}
	
	ReCurrDriverNr = 0;
	GfParmSetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_DRIVER, NULL,
				(tdble)ReStartingOrderIdx[ReCurrDriverNr]);

	return RM_SYNC | RM_NEXT_STEP;
}
コード例 #7
0
ファイル: glfeatures.cpp プロジェクト: 702nADOS/speed-dreams
// Best supported features detection for the given specs of the frame buffer.
bool GfglFeatures::detectBestSupport(int& nWidth, int& nHeight, int& nDepth,
                                     bool& bAlpha, bool& bFullScreen, bool& bBumpMapping, bool& bStereoVision, int &nAniFilt)
{
    GfLogInfo("Detecting best supported features for a %dx%dx%d%s frame buffer.\n",
              nWidth, nHeight, nDepth, bFullScreen ? " full-screen" : "");

    // I) Detection of the max possible values for requested features.
    //    (to do that, we need to try setting up the video modes for real).
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    SDL_Surface* pWinSurface = 0;

    int nAlphaChannel = bAlpha ? 1 : 0;
    int nCurrDepth = nDepth;
    int nFullScreen = bFullScreen ? 1 : 0;
    int nStereoVision = bStereoVision ? 1 : 0;

    while (!pWinSurface && nFullScreen >= 0)
    {
        GfLogTrace("Trying %s mode\n", nFullScreen ? "full-screen" : "windowed");
        const int bfVideoMode = SDL_OPENGL | (nFullScreen ? SDL_FULLSCREEN : 0);

        nAlphaChannel = bAlpha ? 1 : 0;
        while (!pWinSurface && nAlphaChannel >= 0)
        {
            GfLogTrace("Trying with%s alpha channel\n", nAlphaChannel ? "" : "out");
            nCurrDepth = nDepth;
            while (!pWinSurface && nCurrDepth >= 16)
            {
                GfLogTrace("Trying %d bits RVB+A color depth\n", nCurrDepth);
                SDL_GL_SetAttribute(SDL_GL_RED_SIZE, nCurrDepth/4);
                SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, nCurrDepth/4);
                SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, nCurrDepth/4);
                SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, (3*nCurrDepth)/4);
                SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, nAlphaChannel ? nCurrDepth/4 : 0);

                while (!pWinSurface && nStereoVision >= 0)
                {
                    GfLogTrace("Trying with%s stereo vision\n", nStereoVision ? "" : "out");
                    if (nStereoVision)
                        SDL_GL_SetAttribute(SDL_GL_STEREO, GL_TRUE);
                    else
                        SDL_GL_SetAttribute(SDL_GL_STEREO, GL_FALSE);

                    // Anti-aliasing : detect the max supported number of samples
                    // (assumed to be <= 32).
                    int nMaxMultiSamples = 32; // Hard coded max value for the moment.
                    while (!pWinSurface && nMaxMultiSamples > 1)
                    {
                        // Set the anti-aliasing attributes and setup the video mode.
                        GfLogTrace("Trying %dx anti-aliasing\n", nMaxMultiSamples);
                        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
                        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, nMaxMultiSamples);
                        pWinSurface = SDL_SetVideoMode(nWidth, nHeight, nCurrDepth, bfVideoMode);

                        // Now check if we have a video mode, and if it actually features
                        // what we specified.
                        int nActualSampleBuffers = 0;
                        int nActualMultiSamples = 0;
                        if (pWinSurface) {
                            SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &nActualSampleBuffers);
                            SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &nActualMultiSamples);
                        }
                        //GfLogDebug("nMaxMultiSamples=%d : nActualSampleBuffers=%d, nActualMultiSamples=%d\n",
                        //		   nMaxMultiSamples, nActualSampleBuffers, nActualMultiSamples);

                        // If not, try a lower number of samples.
                        if (nActualSampleBuffers == 0 || nActualMultiSamples != nMaxMultiSamples)
                            pWinSurface = 0;
                        if (!pWinSurface)
                        {
                            GfLogTrace("%d+%d bit %dx anti-aliased double-buffer not supported\n",
                                       3*nCurrDepth/4, nCurrDepth/4, nMaxMultiSamples);
                            nMaxMultiSamples /= 2;
                        }
                    }

                    // Failed : try without anti-aliasing.
                    if (!pWinSurface)
                    {
                        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
                        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
                        pWinSurface = SDL_SetVideoMode(nWidth, nHeight, nCurrDepth, bfVideoMode);
                        if (!pWinSurface)
                            GfLogTrace("%d+%d bit double-buffer not supported\n",
                                       3*nCurrDepth/4, nCurrDepth/4);
                    }

                    // Failed : try without StereoVision
                    if (!pWinSurface)
                        nStereoVision--;
                }

                // Failed : try with lower color depth.
                if (!pWinSurface)
                    nCurrDepth -= 8;
            }

            // Failed : try without alpha channel if not already done
            // (Note: it this really relevant ?).
            if (!pWinSurface)
                nAlphaChannel--;
        }

        // Failed : try a windowed mode if not already done.
        if (!pWinSurface)
            nFullScreen--;
    }

    // Failed : no more idea :-(
    if (!pWinSurface)
    {
        // Reset support data (will result in emptying the section when storing,
        // thus forcing new detection when checkSupport will be called again).
        _mapSupportedBool.clear();
        _mapSupportedInt.clear();

        GfLogError("No supported 'best' video mode found for a %dx%dx%d%s frame buffer.\n",
                   nWidth, nHeight, nDepth, bFullScreen ? " full-screen" : "");

        return false;
    }

    // II) Read-out what we have from the up-and-running frame buffer
    //     and set "supported" values accordingly.

    // 1) Standard features.
    detectStandardSupport();

    // 2) Multi-sampling = anti-aliasing
    int nValue;
    SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &nValue);
    _mapSupportedBool[MultiSampling] = nValue != 0;
    //GfLogDebug("SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS) = %d\n", nValue);
    if (nValue)
    {
        SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &nValue);
        //GfLogDebug("SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES) = %d\n", nValue);
        if (nValue > 1)
            _mapSupportedInt[MultiSamplingSamples] = nValue;
        else
            _mapSupportedBool[MultiSampling] = false;
    }

    // III) Return the updated frame buffer specs.
    //nWidth = nWidth; // Unchanged.
    //nHeight = nHeight; // Unchanged.
    nDepth = nCurrDepth;
    bFullScreen = nFullScreen ? true : false;
    bAlpha = nAlphaChannel ? true : false;

    return true;
}
コード例 #8
0
static void
rmRaceResults(void *prevHdle, tRmInfo *info, int start)
{
    void		*results = info->results;
    const char		*race = info->_reRaceName;
    static char		buf[256];
    static char		path[512];
    char		*str;
    
	GfLogTrace("Entering Race Results menu\n");

    // Create screen, load menu XML descriptor and create static controls.
    rmScrHdle = GfuiScreenCreate();
    void *hmenu = GfuiMenuLoad("raceresultsmenu.xml");
    GfuiMenuCreateStaticControls(rmScrHdle, hmenu);

    // Create variable title label.
    snprintf(buf, sizeof(buf), "%s at %s", race, info->track->name);
    const int titleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Title");
    GfuiLabelSetText(rmScrHdle, titleId, buf);
  
	// Get layout properties.
    const int nMaxLines = (int)GfuiMenuGetNumProperty(hmenu, "nMaxResultLines", 15);
    const int yTopLine = (int)GfuiMenuGetNumProperty(hmenu, "yTopLine", 400);
    const int yLineShift = (int)GfuiMenuGetNumProperty(hmenu, "yLineShift", 20);
	const GfuiColor cPlaceGain =
		GfuiColor::build(GfuiMenuGetStrProperty(hmenu, "colorGainedPlaces", "0x32CD32"));
	const float* acPlaceGain = cPlaceGain.toFloatRGBA();
	const GfuiColor cPlaceLoss =
		GfuiColor::build(GfuiMenuGetStrProperty(hmenu, "colorLostPlaces", "0xF28500"));
	const float* acPlaceLoss = cPlaceLoss.toFloatRGBA();

	// Never used : remove ?
    //Get total laps, winner time
    //snprintf(path, sizeof(path), "%s/%s/%s", info->track->name, RE_SECT_RESULTS, race);
    //int totLaps = (int)GfParmGetNum(results, path, RE_ATTR_LAPS, NULL, 0);
    //snprintf(path, sizeof(path), "%s/%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK, 1);
    //tdble refTime = GfParmGetNum(results, path, RE_ATTR_TIME, NULL, 0);

    //Get number of cars
    snprintf(path, sizeof(path), "%s/%s/%s/%s", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK);
    int nbCars = (int)GfParmGetEltNb(results, path);
    
	// Display the result table.
    int y = yTopLine;
	int i;
    for (i = start; i < MIN(start + nMaxLines, nbCars); i++) {
        snprintf(path, sizeof(path), "%s/%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK, i + 1);
        int laps = (int)GfParmGetNum(results, path, RE_ATTR_LAPS, NULL, 0);//Laps covered

        //Rank
        snprintf(buf, sizeof(buf), "%d", i+1);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Rank", true, // From template.
								   buf, GFUI_TPL_X, y);

        //Advance (The num.attrib 'index' holds the starting position)
        int advance = (int)(GfParmGetNum(results, path, RE_ATTR_INDEX, NULL, 0)) - i;
        snprintf(buf, sizeof(buf), "%d", advance);
        const float *aColor =
			advance > 0 ? acPlaceGain : (advance < 0 ? acPlaceLoss : GFUI_TPL_COLOR);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Advance", true, // From template.
								   buf, GFUI_TPL_X, y, GFUI_TPL_FONTID, GFUI_TPL_WIDTH,
								   GFUI_TPL_ALIGN, GFUI_TPL_MAXLEN, aColor);

        //Driver short name
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverName", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_SNAME, ""), GFUI_TPL_X, y);

        //Driver type
        const std::string strModName = GfParmGetStr(results, path, RE_ATTR_MODULE, "");
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverType", true, // From template.
								   GfDriver::getType(strModName).c_str(), GFUI_TPL_X, y);

        //Car
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "CarModel", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_CAR, ""), GFUI_TPL_X, y);

        //Total Time 
        str = GfTime2Str(GfParmGetNum(results, path, RE_ATTR_TIME, NULL, 0), 0, false, 3); 
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "TotalTime", true, // From template.
								   str, GFUI_TPL_X, y);
        free(str);
        
        //Best lap
        str = GfTime2Str(GfParmGetNum(results, path, RE_ATTR_BEST_LAP_TIME, NULL, 0), 0, false, 3);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "BestLapTime", true, // From template.
								   str, GFUI_TPL_X, y);
        free(str);
        
        //Laps covered
        snprintf(buf, sizeof(buf), "%d", laps);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Laps", true, // From template.
								   buf, GFUI_TPL_X, y);
        
        //Top speed
        snprintf(buf, sizeof(buf), "%3.1f", (GfParmGetNum(results, path, RE_ATTR_TOP_SPEED, NULL, 0) * 3.6));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "TopSpeed", true, // From template.
								   buf, GFUI_TPL_X, y);
        
        //Damage
        snprintf(buf, sizeof(buf), "%d", (int)(GfParmGetNum(results, path, RE_ATTR_DAMMAGES, NULL, 0)));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Damages", true, // From template.
								   buf, GFUI_TPL_X, y);
        
        //Pitstops
        snprintf(buf, sizeof(buf), "%d", (int)(GfParmGetNum(results, path, RE_ATTR_NB_PIT_STOPS, NULL, 0)));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Pits", true, // From template.
								   buf, GFUI_TPL_X, y);

        y -= yLineShift;  //Line feed
    }//for i

    //If it is not the first screen of the results, show a 'Prev' button
    if (start > 0) {
        RmPrevRace.prevHdle = prevHdle;
        RmPrevRace.info     = info;
        RmPrevRace.start    = start - nMaxLines;
        GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "PreviousPageArrow",
          (void*)&RmPrevRace, rmChgRaceScreen);
        GfuiAddKey(rmScrHdle, GFUIK_PAGEUP,   "Previous Results", (void*)&RmPrevRace, rmChgRaceScreen, NULL);
    }//if start

    // Add "Continue" button
    GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "ContinueButton", prevHdle, GfuiScreenReplace);
    
    //Create 'save' button in the bottom right
    //rmSaveButtonId = GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "SaveButton", info, rmSaveRes);

    //If we did not display all the results yet, let's show a 'Next' button
    if (i < nbCars) {
        RmNextRace.prevHdle = prevHdle;
        RmNextRace.info     = info;
        RmNextRace.start    = start + nMaxLines;
        GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "NextPageArrow", (void*)&RmNextRace, rmChgRaceScreen);
        GfuiAddKey(rmScrHdle, GFUIK_PAGEDOWN, "Next Results", (void*)&RmNextRace, rmChgRaceScreen, NULL);
    }//if i

    //Link key handlers
    GfuiAddKey(rmScrHdle, GFUIK_ESCAPE, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_RETURN, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F12, "Take a Screen Shot", NULL, GfuiScreenShot, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F1, "Help", rmScrHdle, GfuiHelpScreen, NULL);

	//Show!
    GfuiScreenActivate(rmScrHdle);
}//rmRaceResults
コード例 #9
0
ファイル: guifont.cpp プロジェクト: rongzhou/speed-dreams
void gfuiLoadFonts(void)
{
	void *param;
	int	size;
	int	i;
	int nFontId;

	snprintf(buf, sizeof(buf), "%s%s", GfLocalDir(), GFSCR_CONF_FILE);
	param = GfParmReadFile(buf, GFPARM_RMODE_STD | GFPARM_RMODE_CREAT);

	snprintf(buf, sizeof(buf), "%sdata/fonts/%s", GfDataDir(),
			 GfParmGetStr(param, "Menu Font", "name", "b5.glf"));
	GfLogTrace("Loading font 'Menu Font' from %s : Sizes", buf);
	nFontId = GFUI_FONT_BIG;
	for(i = 0; i < 4; i++, nFontId++) {
		size = (int)GfParmGetNum(param, "Menu Font", keySize[i], (char*)NULL, 10.0);
		GfLogTrace(" %d,", size);
		gfuiFont[nFontId] = new GfuiFontClass(buf);
		gfuiFont[nFontId]->create(size);
	}
	GfLogTrace("\n");

	snprintf(buf, sizeof(buf), "%sdata/fonts/%s", GfDataDir(),
			 GfParmGetStr(param, "Console Font", "name", "b7.glf"));
	GfLogTrace("Loading font 'Console Font' from %s : Sizes", buf);
	nFontId = GFUI_FONT_BIG_C;
	for(i = 0; i < 4; i++, nFontId++) {
		size = (int)GfParmGetNum(param, "Console Font", keySize[i], (char*)NULL, 10.0);
		GfLogTrace(" %d,", size);
		gfuiFont[nFontId] = new GfuiFontClass(buf);
		gfuiFont[nFontId]->create(size);
	}
	GfLogTrace("\n");

	snprintf(buf, sizeof(buf), "%sdata/fonts/%s", GfDataDir(),
			 GfParmGetStr(param, "Text Font", "name", "b6.glf"));
	GfLogTrace("Loading font 'Text Font' from %s : Sizes", buf);
	nFontId = GFUI_FONT_BIG_T;
	for(i = 0; i < 4; i++, nFontId++) {
		size = (int)GfParmGetNum(param, "Text Font", keySize[i], (char*)NULL, 10.0);
		GfLogTrace(" %d,", size);
		gfuiFont[nFontId] = new GfuiFontClass(buf);
		gfuiFont[nFontId]->create(size);
	}
	GfLogTrace("\n");

	snprintf(buf, sizeof(buf), "%sdata/fonts/%s", GfDataDir(),
			 GfParmGetStr(param, "Digital Font", "name", "digital.glf"));
	GfLogTrace("Loading font 'Digital Font' from %s : Sizes", buf);
	nFontId = GFUI_FONT_DIGIT;
	size = (int)GfParmGetNum(param, "Digital Font", keySize[0], (char*)NULL, 8.0);
	GfLogTrace(" %d\n", size);
	gfuiFont[nFontId] = new GfuiFontClass(buf);
	gfuiFont[nFontId]->create(size);

	GfParmReleaseHandle(param);
}
コード例 #10
0
ファイル: linuxspec.cpp プロジェクト: 702nADOS/speed-dreams
/*
 * Function
 *	linuxModInfoDir
 *
 * Description
 *	Retrieve info about the modules whose shared library files are contained in a given directory
 *	(for each shared library, load it, retrieve info about the module (tModInfo struct),
 *	 and finally unload the library).
 *
 * Parameters
 *	dir	(in)     directory to search (relative)
 *	level   (in)     if 1, load any shared library contained in the subdirs of dir
 *	                 and whose name is the same as the containing subdir (ex: bt/bt.so)
 *	                 if 0, load any shared library contained in dir (ignore subdirs)
 *	modlist	(in/out) list of module description structure (may begin empty)
 *
 * Return
 *	>=0	number of modules loaded
 *	-1	error
 *
 * Remarks
 *	The loaded module info structures are added in the list according to each module's priority
 *	(NOT at the head of the list).
 *	
 */
static int
linuxModInfoDir(unsigned int /* gfid */, const char *dir, int level, tModList **modlist)
{
	char		 sopath[256];	/* path of the lib[x].so */
	tSOHandle		 handle;
	DIR			*dp;
	struct dirent	*ep;
	int			 modnb;		/* number on loaded modules */
	tModList		*curMod;
	
	modnb = 0;
	
	/* open the current directory */
	dp = opendir(dir);
	if (dp)
	{
		/* some files in it */
		while ((ep = readdir (dp)) != 0) 
		{
			if (((strlen(ep->d_name) > 4) && 
				 (strcmp(".so", ep->d_name+strlen(ep->d_name)-3) == 0)) /* xxxx.so */
				|| ((level == 1) && (ep->d_name[0] != '.')))
			{
				if (level == 1)
					sprintf(sopath, "%s/%s/%s.so", dir, ep->d_name, ep->d_name);
				else
					sprintf(sopath, "%s/%s", dir, ep->d_name);
				
				/* Try and avoid loading the same module twice (WARNING: Only checks sopath equality !) */
				if (!GfModIsInList(sopath, *modlist))
				{
					/* Load the shared library */
					GfLogTrace("Querying module %s\n", sopath);
					handle = dlopen(sopath, RTLD_LAZY);
					if (handle)
					{
						/* Initialize the module */
						if (GfModInitialize(handle, sopath, GfIdAny, &curMod) == 0)
						{
							if (curMod) /* Retained against gfid */
							{
								/* Get associated info */
								modnb++;
								GfModAddInList(curMod, modlist, /* priosort */ 1);
							}
							
							/* Terminate the module */
							GfModTerminate(handle, sopath);
						}
						
						/* Close the shared library */
						dlclose(handle);
					} 
					else 
					{
						GfLogError("linuxModInfoDir: ...  %s\n", dlerror());
					}
				}
			}
		}
		(void)closedir(dp);
	} 
	else 
	{
		GfLogError("linuxModInfoDir: ... Couldn't open the directory %s.\n", dir);
		return -1;
	}
	
	return modnb;
}
コード例 #11
0
void NetServer::ReadPacket(ENetEvent event)
{
	ENetPacket *pPacket = event.packet;
	assert(pPacket->dataLength>=1);
	unsigned char packetId = pPacket->data[0];
	//int datasize = pPacket->dataLength-1;
	
        switch (packetId)
        {
        case PLAYERINFO_PACKET:
                GfLogTrace("PlayerInfo Packet\n");
                ReadDriverInfoPacket(pPacket,event.peer);
                break;
        case CLIENTREADYTOSTART_PACKET:
                {
                        int l;
                        char name[256];
                        memset(&name[0],0,256);

                        PackedBuffer msg(pPacket->data, pPacket->dataLength);
                        GfLogTrace("ReadPacket: packed data length=%d\n",
                                msg.length());

                        try
                        {
                                msg.unpack_ubyte();
                                l = msg.unpack_int();
                                msg.unpack_string(name, l);
                        }
                        catch (PackedBufferException &e)
                        {
                                GfLogFatal("ReadPacket: packed buffer error\n");
                        }

                        std::vector<NetDriver>::iterator p;
                        p = m_vecWaitForPlayers.begin();
                        while(p!=m_vecWaitForPlayers.end())
                        {
                                if (strcmp(p->name,name)==0)
                                {
                                        GfLogTrace("%s ready to start\n",&name[0]);
                                        m_vecWaitForPlayers.erase(p);
                                        break;
                                }

                                p++;
                        }

                        if (m_vecWaitForPlayers.size()==0)
                                m_bBeginRace = true;

                }
                break;
        case SERVER_TIME_REQUEST_PACKET:
                SendTimePacket(pPacket,event.peer);
                break;
        case CARCONTROLS_PACKET:
                ReadCarControlsPacket(event.packet);
                break;
        case CARSTATUS_PACKET:
                ReadCarStatusPacket(event.packet);
                break;
        case LAPSTATUS_PACKET:
                ReadLapStatusPacket(event.packet);
                break;
        case DRIVERREADY_PACKET:
                ReadDriverReadyPacket(event.packet);
                break;

	default:
			GfLogTrace ("A packet of length %u containing %s was received from %s on channel %u.\n",
                    event.packet -> dataLength,
                    event.packet -> data,
                    (char*)event.peer -> data,
                    event.channelID);
	}

    enet_packet_destroy (event.packet);
}
コード例 #12
0
void NetServer::ReadDriverInfoPacket(ENetPacket *pPacket, ENetPeer * pPeer)
{
	NetDriver driver;

	char hostName[256];
	enet_address_get_host_ip (&driver.address,hostName,256);

    GfLogTrace ("Client Player Info connected from %s\n",hostName); 

        PackedBuffer msg(pPacket->data, pPacket->dataLength);
        GfLogTrace("ReadDriverInfoPacket: packed data length=%d\n",
                msg.length());

        try
        {
                msg.unpack_ubyte();
                driver.idx = msg.unpack_int();
                msg.unpack_string(driver.name, sizeof driver.name);
                msg.unpack_string(driver.car, sizeof driver.car);
                msg.unpack_string(driver.team, sizeof driver.team);
                msg.unpack_string(driver.author, sizeof driver.author);
                driver.racenumber = msg.unpack_int();
                msg.unpack_string(driver.skilllevel, sizeof driver.skilllevel);
                driver.red = msg.unpack_float();
                driver.green = msg.unpack_float();
                driver.blue = msg.unpack_float();
                msg.unpack_string(driver.module, sizeof driver.module);
                msg.unpack_string(driver.type, sizeof driver.type);
                driver.client = msg.unpack_int();
        }
        catch (PackedBufferException &e)
        {
                GfLogFatal("ReadDriverInfoPacket: packed buffer error\n");
        }

	GfLogTrace("ReadDriverInfoPacket: driver\n");
	GfLogTrace(".host=%d\n", driver.address.host);
	GfLogTrace(".port=%d\n", driver.address.port);
	GfLogTrace(".idx=%d\n", driver.idx);
	GfLogTrace(".name=%s\n", driver.name);
	GfLogTrace(".car=%s\n", driver.car);
	GfLogTrace(".team=%s\n", driver.team);
	GfLogTrace(".author=%s\n", driver.author);
	GfLogTrace(".racenumber=%d\n", driver.racenumber);
	GfLogTrace(".skilllevel=%s\n", driver.skilllevel);
	GfLogTrace(".red=%.1f\n", driver.red);
	GfLogTrace(".green=%.1f\n", driver.green);
	GfLogTrace(".blue=%.1f\n", driver.blue);
	GfLogTrace(".module=%s\n", driver.module);
	GfLogTrace(".type=%s\n", driver.type);
	GfLogTrace(".client=%d\n", driver.client);

	//Make sure player name is unique otherwise disconnect player
	NetServerMutexData *pSData = LockServerData();
	for(unsigned int i=0;i<pSData->m_vecNetworkPlayers.size();i++)
	{
		if (strcmp(driver.name,pSData->m_vecNetworkPlayers[i].name)==0)
		{
			SendPlayerRejectedPacket(pPeer,"Player name already used. Please choose a different name.");
			UnlockServerData();
			return;
		}
	}
	UnlockServerData();

	driver.address.host = pPeer->address.host;
	driver.hostPort = pPeer->address.port;

	SendPlayerAcceptedPacket(pPeer);
	UpdateDriver(driver);

	GfLogTrace("Reading Driver Info Packet:  Driver: %s,Car: %s\n",driver.name,driver.car);
}
コード例 #13
0
void NetServer::RemoveDriver(ENetEvent event)
{
	int playerStartIndex;
	ENetAddress address = event.peer->address;

	char hostName[256];
	enet_address_get_host_ip (&address,hostName,256);

    GfLogTrace ("Client Player Info disconnect from %s\n",hostName); 
	
	std::vector<NetDriver>::iterator p;

	if (m_vecWaitForPlayers.size()>0)
	{
		p = m_vecWaitForPlayers.begin();

		while(p!=m_vecWaitForPlayers.end())
		{

			if ((p->address.host == address.host)&&(p->hostPort == address.port))
			{
				m_vecWaitForPlayers.erase(p);
				break;
			}

			p++;
		}

		if (m_vecWaitForPlayers.size()==0)
			m_bBeginRace = true;
	}

	//look for driver id
	NetServerMutexData *pSData = LockServerData();
	for (p = pSData->m_vecNetworkPlayers.begin();p!=pSData->m_vecNetworkPlayers.end();p++)
	{
		if (p->client)
		{
			if ((p->address.host == address.host)&&(p->hostPort == address.port))
			{
				if(m_bRaceActive)
				{
					playerStartIndex = p->idx-1;
					pSData->m_vecNetworkPlayers.erase(p);
					RemovePlayerFromRace(playerStartIndex);
					GenerateDriversForXML();
					RobotXml rXml;
					rXml.CreateRobotFile("networkhuman",pSData->m_vecNetworkPlayers);
					SetRaceInfoChanged(true);
				}
				else
				{
					pSData->m_vecNetworkPlayers.erase(p);
					GenerateDriversForXML();
					RobotXml rXml;
					rXml.CreateRobotFile("networkhuman",pSData->m_vecNetworkPlayers);
					SetRaceInfoChanged(true);
				}

				UnlockServerData();
				return;
			}
		}
	}

	UnlockServerData();
}
コード例 #14
0
ファイル: raceinit.cpp プロジェクト: rongzhou/speed-dreams
static void
initPits(void)
{
  tTrackPitInfo *pits;
  int i, j;

  /*
  typedef std::map<std::string, int> tTeamsMap;
  typedef tTeamsMap::const_iterator tTeamsMapIterator;
  tTeamsMap teams;
  tTeamsMapIterator teamsIterator;

  // create a list with the teams, a pit can just be used by one team.
  for (i = 0; i < ReInfo->s->_ncars; i++) {
    tCarElt *car = &(ReInfo->carList[i]);
    teams[car->_teamname] = teams[car->_teamname] + 1; 
  } 

  for (teamsIterator = teams.begin(); teamsIterator != teams.end(); ++teamsIterator) {
    GfLogDebug("----------------- %s\t%d\n", (teamsIterator->first).c_str(), teamsIterator->second); 
  }
  */

  // How many cars are sharing a pit?
  int carsPerPit = (int) GfParmGetNum(ReInfo->params, ReInfo->_reRaceName, RM_ATTR_CARSPERPIT, NULL, 1.0f);
  if (carsPerPit < 1) {
    carsPerPit = 1;
  } else if (carsPerPit > TR_PIT_MAXCARPERPIT) {
    carsPerPit = TR_PIT_MAXCARPERPIT;
  }
  GfLogInfo("Cars per pit: %d\n", carsPerPit);

  switch (ReInfo->track->pits.type) {
    case TR_PIT_ON_TRACK_SIDE:
    case TR_PIT_NO_BUILDING:
      pits = &(ReInfo->track->pits);
      pits->driversPitsNb = ReInfo->s->_ncars;
      pits->carsPerPit = carsPerPit;

      // Initialize pit data for every pit, necessary because of restarts
      // (track gets not reloaded, no calloc).
      for (i = 0; i < pits->nMaxPits; i++) {
        tTrackOwnPit *pit = &(pits->driversPits[i]);
        pit->freeCarIndex = 0;
        pit->pitCarIndex = TR_PIT_STATE_FREE;
        for (j = 0; j < TR_PIT_MAXCARPERPIT; j++) {
          pit->car[j] = NULL;
        }
      }

      // Assign cars to pits. Inefficient (O(n*n)), but just at initialization, so do not care.
      // One pit can just host cars of one team (this matches with the reality)
      for (i = 0; i < ReInfo->s->_ncars; i++) {
        // Find pit for the cars team.
        tCarElt *car = &(ReInfo->carList[i]);
        for (j = 0; j < pits->nMaxPits; j++) {
          tTrackOwnPit *pit = &(pits->driversPits[j]);
          // Put car in this pit if the pit is unused or used by a teammate and there is
          // space left.
          if (pit->freeCarIndex <= 0 ||
            (strcmp(pit->car[0]->_teamname, car->_teamname) == 0 && pit->freeCarIndex < carsPerPit))
          {
            // Assign car to pit.
            pit->car[pit->freeCarIndex] = car;
            // If this is the first car, set up more pit values ; assumption: the whole team
            // uses the same car. If not met, it does not matter much, but the car might be
            // captured a bit too easy or too hard.
            if (pit->freeCarIndex == 0) {
              pit->pitCarIndex = TR_PIT_STATE_FREE;
              pit->lmin = pit->pos.seg->lgfromstart + pit->pos.toStart - pits->len / 2.0f + car->_dimension_x / 2.0f;
              if (pit->lmin > ReInfo->track->length) {
                pit->lmin -= ReInfo->track->length;
              }
              pit->lmax = pit->pos.seg->lgfromstart + pit->pos.toStart + pits->len / 2.0f - car->_dimension_x / 2.0f;
              if (pit->lmax > ReInfo->track->length) {
                pit->lmax -= ReInfo->track->length;
              }
            }
            (pit->freeCarIndex)++;
            ReInfo->carList[i]._pit = pit;
            // Assigned, continue with next car.
            break;
          }
        }
      }

      // Print out assignments.
      for (i = 0; i < pits->nMaxPits; i++) {
        tTrackOwnPit *pit = &(pits->driversPits[i]);
        for (j = 0; j < pit->freeCarIndex; j++) {
          if (j == 0) {
            GfLogTrace("Pit %d, Team: %s, ", i, pit->car[j]->_teamname); 
          }
          GfLogTrace("%d: %s ", j, pit->car[j]->_name);
        }
        if (j > 0) {
          GfOut("\n");
        }
      }

      break;
    case TR_PIT_ON_SEPARATE_PATH:
      break;
    case TR_PIT_NONE:
      break;
  }
}
コード例 #15
0
ファイル: glfeatures.cpp プロジェクト: 702nADOS/speed-dreams
bool GfglFeatures::loadSupport(int &nWidth, int &nHeight, int &nDepth,
                               bool &bAlpha, bool &bFullScreen, bool &bBump, bool &bStereo, int &nAniFilt,void* hparmConfig)
{
    // Clear support data.
    _mapSupportedBool.clear();
    _mapSupportedInt.clear();

    // Open the config file if not already done.
    void* hparm = hparmConfig ? hparmConfig : openConfigFile();

    // Load the frame buffer specs for the stored supported features.
    nWidth =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_WIN_X, pszNoUnit, 0);
    nHeight =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_WIN_Y, pszNoUnit, 0);
    nDepth =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_BPP, pszNoUnit, 0);
    nAniFilt =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_ANISOTROPICFILTERING, pszNoUnit, 0);
    bAlpha =
        std::string(GfParmGetStr(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_ALPHACHANNEL, GFSCR_VAL_NO))
        == GFSCR_VAL_YES;
    bFullScreen =
        std::string(GfParmGetStr(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_FSCR, GFSCR_VAL_NO))
        == GFSCR_VAL_YES;
    bStereo =
        std::string(GfParmGetStr(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_STEREOVISION, GFSCR_VAL_NO))
        == GFSCR_VAL_YES;
    bBump =
        std::string(GfParmGetStr(hparm, GFSCR_SECT_GLDETSPECS, GFSCR_ATT_BUMPMAPPING, GFSCR_VAL_NO))
        == GFSCR_VAL_YES;

    // Check that we have something supported, and return if not.
    if (nWidth == 0 || nHeight == 0 || nDepth == 0)
    {
        GfLogTrace("No info found about best supported features for these specs ; "
                   "will need a detection pass.\n");

        // Close config file if we open it.
        if (!hparmConfig)
            closeConfigFile(hparm);

        return false;
    }


    // Here, we only update _mapSupportedXXX only if something relevant in the config file
    // If there's nothing or something not expected, it means no support.

    // 1) Double-buffer.
    const std::string strDoubleBuffer =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_DOUBLEBUFFER, "");
    if (strDoubleBuffer == GFSCR_VAL_YES)
        _mapSupportedBool[DoubleBuffer] = true;
    else if (strDoubleBuffer == GFSCR_VAL_NO)
        _mapSupportedBool[DoubleBuffer] = false;

    // 2) Color buffer depth.
    const int nColorDepth =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_COLORDEPTH,
                          pszNoUnit, (tdble)0);
    if (nColorDepth > 0)
        _mapSupportedInt[ColorDepth] = nColorDepth;

    // 3) Alpha-channel depth.
    const int nAlphaDepth =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_ALPHADEPTH,
                          pszNoUnit, (tdble)-1);
    if (nAlphaDepth >= 0)
        _mapSupportedInt[AlphaDepth] = nAlphaDepth;

    // 4) Max texture size.
    const int nMaxTexSize =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_MAXTEXTURESIZE,
                          pszNoUnit, (tdble)0);
    if (nMaxTexSize > 0)
        _mapSupportedInt[TextureMaxSize] = nMaxTexSize;

    // 5) Texture compression.
    const std::string strTexComp =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_TEXTURECOMPRESSION, "");
    if (strTexComp == GFSCR_VAL_YES)
        _mapSupportedBool[TextureCompression] = true;
    else if (strTexComp == GFSCR_VAL_NO)
        _mapSupportedBool[TextureCompression] = false;

    // 6) Multi-texturing.
    const std::string strMultiTex =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_MULTITEXTURING, "");
    if (strMultiTex == GFSCR_VAL_YES)
        _mapSupportedBool[MultiTexturing] = true;
    else if (strMultiTex == GFSCR_VAL_NO)
        _mapSupportedBool[MultiTexturing] = false;

    const int nMultiTexUnits =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_MULTITEXTURINGUNITS,
                          pszNoUnit, (tdble)0);
    if (nMultiTexUnits > 0)
        _mapSupportedInt[MultiTexturingUnits] = nMultiTexUnits;

    // 7) Rectangle textures).
    const std::string strRectTex =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_RECTANGLETEXTURES, "");
    if (strRectTex == GFSCR_VAL_YES)
        _mapSupportedBool[TextureRectangle] = true;
    else if (strRectTex == GFSCR_VAL_NO)
        _mapSupportedBool[TextureRectangle] = false;

    // 8) Non-power-of-2 textures.
    const std::string strNonPoTTex =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_NONPOTTEXTURES, "");
    if (strNonPoTTex == GFSCR_VAL_YES)
        _mapSupportedBool[TextureNonPowerOf2] = true;
    else if (strNonPoTTex == GFSCR_VAL_NO)
        _mapSupportedBool[TextureNonPowerOf2] = false;

    // 9) Multi-sampling.
    const std::string strMultiSamp =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_MULTISAMPLING, "");
    if (strMultiSamp == GFSCR_VAL_YES)
        _mapSupportedBool[MultiSampling] = true;
    else if (strMultiSamp == GFSCR_VAL_NO)
        _mapSupportedBool[MultiSampling] = false;

    const int nMultiSampSamples =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_MULTISAMPLINGSAMPLES,
                          pszNoUnit, (tdble)0);
    if (nMultiSampSamples > 0)
        _mapSupportedInt[MultiSamplingSamples] = nMultiSampSamples;

    // 10) Stereo Vision
    const std::string strStereoVision =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_STEREOVISION, "");
    if (strStereoVision == GFSCR_VAL_YES)
        _mapSupportedBool[StereoVision] = true;
    else if (strStereoVision == GFSCR_VAL_NO)
        _mapSupportedBool[StereoVision] = false;

    // 11) Bump Mapping.
    const std::string strBumpMapping =
        GfParmGetStr(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_BUMPMAPPING, "");
    if (strTexComp == GFSCR_VAL_YES) //strTexComp ? Bug ?
        _mapSupportedBool[BumpMapping] = true;
    else if (strTexComp == GFSCR_VAL_NO)
        _mapSupportedBool[BumpMapping] = false;

    // 11) Anisotropic Filtering.
    const int nAF =
        (int)GfParmGetNum(hparm, GFSCR_SECT_GLDETFEATURES, GFSCR_ATT_ANISOTROPICFILTERING,
                          pszNoUnit, (tdble)0);
    if (nMaxTexSize > 0)
        _mapSupportedInt[AnisotropicFiltering] =nAF;


    // Close config file if we open it.
    if (!hparmConfig)
        closeConfigFile(hparm);

    // Trace best supported features.
    dumpSupport();

    return true;
}
コード例 #16
0
ファイル: raceinit.cpp プロジェクト: rongzhou/speed-dreams
/**
 * Function to load a car.
 *
 * @param carindex The index whichs will be used as car->index for the car.
 * @param listindex The listindex in RM_SECT_DRIVERS_RACING
 * @param modindex The index of the mod; must be MAX_MOD_ITF if normal_carname is FALSE.
 * @param robotIdx The index of the robot.
 * @param normal_carname If this member is TRUE, the car is treated as an ordinary car;
 *                       if this member is FALSE, then the car used is the one given
 *                       in the xml-file, and there is no restriction on the number of instances.
 * @param cardllname The dllname of the driver
 * @return A pointer to the newly created car if successfull; NULL otherwise
 */
static tCarElt* reLoadSingleCar( int carindex, int listindex, int modindex, int relativeRobotIdx, char normal_carname, char const *cardllname )
{
  tCarElt *elt;
  tMemoryPool oldPool;
  char path[256];
  char path2[256];
  char buf[256];
  char buf2[256];
  char const *str;
  char const *category;
  char const *subcategory;
  char const *teamname;
  std::string carname;
  tModInfoNC *curModInfo;
  tRobotItf *curRobot;
  void *robhdle;
  void *cathdle;
  void *carhdle;
  void *handle;
  int k;
  int xx;
  char isHuman;
  int robotIdx = relativeRobotIdx;

  /* good robot found */
  curModInfo = &((*(ReInfo->robModList))->modInfo[modindex]);

  subcategory = ReInfo->track->subcategory;

#if 0 //SDW
  if (replayReplay)
    GfLogInfo("Driver in car %d being driven by replay\n", carindex);
  else
#endif
    GfLogInfo("Driver's name: %s\n", curModInfo->name);

  isHuman = strcmp( cardllname, "human" ) == 0 || strcmp( cardllname, "networkhuman" ) == 0;

  /* Extended is forced for humans, so no need to increase robotIdx */
  if (!normal_carname && !isHuman) 
    robotIdx += curModInfo->index;

  /* Retrieve the driver interface (function pointers) */
  curRobot = (tRobotItf*)calloc(1, sizeof(tRobotItf));

  /* ... and initialize the driver */
#if 0 // SDW
  if (replayReplay) {
    // Register against the Replay driver (which does nothing)
    curModInfo->fctInit(carindex, (void*)(curRobot));
  } else if (!(ReInfo->_displayMode & RM_DISP_MODE_SIMU_SIMU)) {
#else
  if (!(ReInfo->_displayMode & RM_DISP_MODE_SIMU_SIMU)) {
#endif
    curModInfo->fctInit(robotIdx, (void*)(curRobot));
  } else {
    curRobot->rbNewTrack = NULL;
    curRobot->rbNewRace  = NULL;
    curRobot->rbResumeRace  = NULL;
    curRobot->rbDrive    = NULL;
    curRobot->rbPitCmd   = NULL;
    curRobot->rbEndRace  = NULL;
    curRobot->rbShutdown = NULL;
    curRobot->index      = 0;
  }

  /* Retrieve and load the robotXML file :
     1) from user settings dir (local dir)
     2) from installed data dir */
  snprintf(buf, sizeof(buf), "%sdrivers/%s/%s.xml", GfLocalDir(), cardllname, cardllname);
  robhdle = GfParmReadFile(buf, GFPARM_RMODE_STD);
  if (!robhdle) {
    snprintf(buf, sizeof(buf), "drivers/%s/%s.xml", cardllname, cardllname);
    robhdle = GfParmReadFile(buf, GFPARM_RMODE_STD);
  }

  if (normal_carname || isHuman)
    snprintf(path, sizeof(path), "%s/%s/%d", ROB_SECT_ROBOTS, ROB_LIST_INDEX, robotIdx);
  else
    snprintf(path, sizeof(path), "%s", ROB_SECT_ARBITRARY);
  
  /* Load car/driver info (in race engine data structure) */
  if (robhdle)
  {
    elt = &(ReInfo->carList[carindex]);
    GF_TAILQ_INIT(&(elt->_penaltyList));

    const std::string strDType = GfParmGetStr(robhdle, path, ROB_ATTR_TYPE, ROB_VAL_ROBOT);
    if (strDType == ROB_VAL_ROBOT){
      elt->_driverType = RM_DRV_ROBOT;
      elt->_networkPlayer = 0;
    } 
    else if (strDType == ROB_VAL_HUMAN)
    {
      elt->_driverType = RM_DRV_HUMAN;
      std::string strNetPlayer = GfParmGetStr(robhdle, path, "networkrace", "no");
      elt->_networkPlayer = (strNetPlayer == "yes") ? 1 : 0;
    }

    elt->index = carindex;
    elt->robot = curRobot;
    elt->_paramsHandle = robhdle;
    elt->_driverIndex = robotIdx;
    elt->_moduleIndex = relativeRobotIdx;
    strncpy(elt->_modName, cardllname, MAX_NAME_LEN - 1);
    elt->_modName[MAX_NAME_LEN - 1] = 0;

    //snprintf(path, sizeof(path), "%s/%s/%d", ROB_SECT_ROBOTS, ROB_LIST_INDEX, robotIdx);
    snprintf( path2, sizeof(path2), "%s/%s/%d/%d", RM_SECT_DRIVERINFO, elt->_modName, normal_carname ? 0 : 1, elt->_moduleIndex );
    if (normal_carname || elt->_driverType == RM_DRV_HUMAN) {
      strncpy(elt->_name, GfParmGetStr(robhdle, path, ROB_ATTR_NAME, "none"), MAX_NAME_LEN - 1);
      strncpy(elt->_sname, GfParmGetStr(robhdle, path, ROB_ATTR_SNAME, "none"), MAX_NAME_LEN - 1);
      strncpy(elt->_cname, GfParmGetStr(robhdle, path, ROB_ATTR_CODE, "---"), 3);
    } else {
      strncpy(elt->_name, GfParmGetStr(ReInfo->params, path2, ROB_ATTR_NAME, "none"), MAX_NAME_LEN - 1);
      strncpy(elt->_sname, GfParmGetStr(ReInfo->params, path2, ROB_ATTR_SNAME, "none"), MAX_NAME_LEN - 1);
      strncpy(elt->_cname, GfParmGetStr(ReInfo->params, path2, ROB_ATTR_CODE, "---"), 3);
    }
    elt->_name[MAX_NAME_LEN - 1] = 0;
    elt->_sname[MAX_NAME_LEN - 1] = 0;
    elt->_cname[3] = 0;

    teamname = GfParmGetStr(robhdle, path, ROB_ATTR_TEAM, "none");
    teamname = GfParmGetStr(ReInfo->params, path2, ROB_ATTR_TEAM, teamname ); //Use the name in params if it has a team name
    strncpy(elt->_teamname, teamname, MAX_NAME_LEN - 1);
    elt->_teamname[MAX_NAME_LEN - 1] = 0;

    elt->_driveSkill = GfParmGetNum(ReInfo->params, path2, RM_ATTR_SKILLLEVEL, NULL, -1.0f);

    if (normal_carname) /* Even if we get a normal_carname for humans we use it despite of forced extended mode*/
      strncpy(elt->_carName, GfParmGetStr(robhdle, path, ROB_ATTR_CAR, ""), MAX_NAME_LEN - 1);
    else
      strncpy(elt->_carName, GfParmGetStr(ReInfo->params, path2, RM_ATTR_CARNAME, ""), MAX_NAME_LEN - 1);
    elt->_carName[MAX_NAME_LEN - 1] = 0; /* XML file name */

    // Load custom skin name and targets from race info (if specified).
    snprintf(path2, sizeof(path2), "%s/%d", RM_SECT_DRIVERS_RACING, listindex);
    if (GfParmGetStr(ReInfo->params, path2, RM_ATTR_SKINNAME, 0))
    {
      strncpy(elt->_skinName, GfParmGetStr(ReInfo->params, path2, RM_ATTR_SKINNAME, ""), MAX_NAME_LEN - 1);
      elt->_skinName[MAX_NAME_LEN - 1] = 0; // Texture name
    }
	elt->_skinTargets = (int)GfParmGetNum(ReInfo->params, path2, RM_ATTR_SKINTARGETS, (char*)NULL, 0);
	
    // Load other data from robot descriptor.
    elt->_raceNumber = (int)GfParmGetNum(robhdle, path, ROB_ATTR_RACENUM, (char*)NULL, 0);
    if (!normal_carname && elt->_driverType != RM_DRV_HUMAN) // Increase racenumber if needed
      elt->_raceNumber += elt->_moduleIndex;
    elt->_skillLevel = 0;
    str = GfParmGetStr(robhdle, path, ROB_ATTR_LEVEL, ROB_VAL_SEMI_PRO);
    for(k = 0; k < NSkillLevels; k++) {
      if (strcmp(aPszSkillLevelNames[k], str) == 0) {
        elt->_skillLevel = k;
        break;
      }
    }
    elt->_startRank  = carindex;
    elt->_pos        = carindex+1;
    elt->_remainingLaps = ReInfo->s->_totLaps;

    elt->_newTrackMemPool = NULL;
    elt->_newRaceMemPool = NULL;
    elt->_endRaceMemPool = NULL;
    elt->_shutdownMemPool = NULL;

	carname = elt->_carName;

    GfLogTrace("Driver #%d(%d) : module='%s', name='%s', car='%s', cat='%s', skin='%s' on %x\n",
			   carindex, listindex, elt->_modName, elt->_name, elt->_carName,
			   elt->_category, elt->_skinName, elt->_skinTargets);

    if ((strncmp(carname.c_str(), "mpa1", 4) == 0))
	{
		if (strcmp(subcategory, "long") == 0)
			carname = carname+"-long";
		else if (strcmp(subcategory, "short") == 0)
			carname = carname+"-short";
		else 
			carname = carname+"-road";

		GfLogTrace("MPA... Category car = %s \n", carname.c_str());

		/* Retrieve and load car specs : merge car default specs,
		category specs and driver modifications (=> handle) */
		/* Read Car model specifications */
		snprintf(buf, sizeof(buf), "cars/models/%s/%s.xml", elt->_carName, carname.c_str());
		carhdle = GfParmReadFile(buf, GFPARM_RMODE_STD | GFPARM_RMODE_CREAT);

	}
	else
	{  
		/* Retrieve and load car specs : merge car default specs,
		category specs and driver modifications (=> handle) */
		/* Read Car model specifications */
		snprintf(buf, sizeof(buf), "cars/models/%s/%s.xml", elt->_carName, elt->_carName);
		carhdle = GfParmReadFile(buf, GFPARM_RMODE_STD | GFPARM_RMODE_CREAT);
	}

    category = GfParmGetStr(carhdle, SECT_CAR, PRM_CATEGORY, NULL);
    if (category)
    {
	  GfLogTrace("Checking/Merging %s specs into %s base setup for %s ...\n",
				 category, elt->_carName, curModInfo->name);
      strncpy(elt->_category, category, MAX_NAME_LEN - 1);
      elt->_category[MAX_NAME_LEN - 1] = 0;
      /* Read Car Category specifications */
      snprintf(buf2, sizeof(buf2), "cars/categories/%s.xml", elt->_category);
      cathdle = GfParmReadFile(buf2, GFPARM_RMODE_STD | GFPARM_RMODE_CREAT);
	  int errorcode = 0;

      if ((errorcode = GfParmCheckHandle(cathdle, carhdle))) 
	  {
        switch (errorcode)
		{
		  case -1:
            GfLogError("Car %s NOT in category %s (driver %s) !!!\n", elt->_carName, category, elt->_name);
		    break;

		  case -2:
            GfLogError("Parameters out of bound for car %s (driver %s)!!!\n",elt->_carName, elt->_name);
		    break;

		  case -3:
            GfLogError("Parameter not allowed for car %s (driver %s)!!!\n",elt->_carName, elt->_name);
		    break;

		  default:
            GfLogError("Unknown error for %s (driver %s)!!!\n",elt->_carName, elt->_name);
		    break;
	    } 
        return NULL;
      }

      carhdle = GfParmMergeHandles(cathdle, carhdle,
                                   GFPARM_MMODE_SRC | GFPARM_MMODE_DST | GFPARM_MMODE_RELSRC | GFPARM_MMODE_RELDST);
	  
      /* The code below stores the carnames to a separate xml-file
		 such that at newTrack it is known which car is used.
		 TODO: find a better method for this */
      snprintf (buf, sizeof(buf), "%sdrivers/curcarnames.xml", GfLocalDir());
      handle = GfParmReadFile(buf, GFPARM_RMODE_CREAT);
      if (handle) {
        snprintf(path, sizeof(path), "drivers/%s/%d", cardllname, elt->_driverIndex);
        GfParmSetStr (handle, path, RM_ATTR_CARNAME, elt->_carName);
        GfParmWriteFile (0, handle, "Car names");
        GfParmReleaseHandle (handle);
      }
      if (!(ReInfo->_displayMode & RM_DISP_MODE_SIMU_SIMU))
      {
        GfPoolMove(&elt->_newTrackMemPool, &oldPool);
        curRobot->rbNewTrack(elt->_driverIndex, ReInfo->track, carhdle, &handle, ReInfo->s);
        GfPoolFreePool( &oldPool );
      }
      else
        handle = NULL;
      if (handle && !replayReplay) {
		GfLogTrace("Checking/Merging %s specific setup into %s setup.\n",
				   curModInfo->name, elt->_carName);
        if (GfParmCheckHandle(carhdle, handle)) {
          GfLogError("Bad Car parameters for driver %s\n", elt->_name);
          return NULL;
        }
        handle = GfParmMergeHandles(carhdle, handle,
                                    GFPARM_MMODE_SRC | GFPARM_MMODE_DST | GFPARM_MMODE_RELSRC | GFPARM_MMODE_RELDST);
      } else {
		GfLogTrace("Keeping %s setup as is for %s (no specific setup).\n",
				   elt->_carName, curModInfo->name);
		handle = carhdle;
      }
      elt->_carHandle = handle;

      /* Initialize sectors */
      elt->_currentSector = 0;
      elt->_curSplitTime = (double*)malloc( sizeof(double) * ( ReInfo->track->numberOfSectors - 1 ) );
      elt->_bestSplitTime = (double*)malloc( sizeof(double) * ( ReInfo->track->numberOfSectors - 1 ) );
      for (xx = 0; xx < ReInfo->track->numberOfSectors - 1; ++xx)
      {
        elt->_curSplitTime[xx] = -1.0f;
        elt->_bestSplitTime[xx] = -1.0f;
      }
    } else {
      elt->_category[ 0 ] = '\0';
      GfLogError("Bad Car category for driver %s\n", elt->_name);
      return NULL;
    }

    return elt;
  } else {
    GfLogError("No description file for robot %s\n", cardllname);
  }
  return NULL;
}


/** Initialize the cars for a race.
    The cars are positionned on the starting grid.
    @return 0 Ok, -1 Error
 */
int
ReInitCars(void)
{
  char buf[512];
  char path[512];
  int nCars;
  int index;
  int i, j;
  const char *robotModuleName;
  int robotIdx;
  void *robhdle;
  tCarElt *elt;
  //const char *focused; // Never used.
  //int focusedIdx; // Never used.
  void *params = ReInfo->params;

  /* Get the number of cars (= drivers) racing */
  nCars = GfParmGetEltNb(params, RM_SECT_DRIVERS_RACING);
  GfLogTrace("Loading %d car(s)\n", nCars);

  FREEZ(ReInfo->carList);
  ReInfo->carList = (tCarElt*)calloc(nCars, sizeof(tCarElt));
  FREEZ(ReInfo->rules);
  ReInfo->rules = (tRmCarRules*)calloc(nCars, sizeof(tRmCarRules));
  //focused = GfParmGetStr(ReInfo->params, RM_SECT_DRIVERS, RM_ATTR_FOCUSED, "");
  //focusedIdx = (int)GfParmGetNum(ReInfo->params, RM_SECT_DRIVERS, RM_ATTR_FOCUSEDIDX, NULL, 0);
  index = 0;

  /* For each car/driver : */
  for (i = 1; i < nCars + 1; i++) 
  {
    /* Get the name of the module (= shared library) of the robot */
    snprintf(path, sizeof(path), "%s/%d", RM_SECT_DRIVERS_RACING, i);
    robotModuleName = GfParmGetStr(ReInfo->params, path, RM_ATTR_MODULE, "");
    robotIdx = (int)GfParmGetNum(ReInfo->params, path, RM_ATTR_IDX, NULL, 0);

#if 0 // SDW
    if (replayReplay)
      // Register against the Replay driver
      snprintf(path, sizeof(path), "%sdrivers/replay/replay.%s", GfLibDir(), DLLEXT);
    else
#endif
      snprintf(path, sizeof(path), "%sdrivers/%s/%s.%s", GfLibDir(), robotModuleName, robotModuleName, DLLEXT);

    /* Load the robot shared library */
    if (GfModLoad(CAR_IDENT, path, ReInfo->robModList)) 
    {
      GfLogError("Failed to load robot module %s\n", path);
      continue;
    }

    /* Load the racing driver info in the race data structure */
    elt = NULL;
    snprintf(path, sizeof(path), "%s/%d", RM_SECT_DRIVERS_RACING, i);
    if ((int)GfParmGetNum(ReInfo->params, path, RM_ATTR_EXTENDED, NULL, 0) == 0) 
    {
      /* Search for the index of the racing driver in the list of interfaces
         of the module */
      for (j = 0; j < (*(ReInfo->robModList))->modInfoSize; j++) 
      {
        if ((*(ReInfo->robModList))->modInfo[j].name && (*(ReInfo->robModList))->modInfo[j].index == robotIdx) 
        {
          /* We have the right driver : load it */
          elt = reLoadSingleCar( index, i, j, robotIdx, TRUE, robotModuleName );
          if (!elt)
		  {
            GfLogError("No descriptor file for robot %s or parameter errors (1)\n", robotModuleName);
			snprintf(buf, sizeof(buf), "Error: May be no driver, or some parameters are out of bound");
	        ReUI().addLoadingMessage(buf);
			snprintf(buf, sizeof(buf), "       Have a look at the console window for mode details about the error");
	        ReUI().addLoadingMessage(buf);
			snprintf(buf, sizeof(buf), "       Back to the config menu in 10 s ...");
	        ReUI().addLoadingMessage(buf);
			
			// Wait some time to allow the user to read the message!
            GfSleep(10.0); // 10 seconds
		  }
        }
      }
    }
    else 
    {
      GfLogTrace("Loading robot %s descriptor file\n", robotModuleName );
      snprintf(buf, sizeof(buf), "%sdrivers/%s/%s.xml", GfLocalDir(), robotModuleName, robotModuleName);
      robhdle = GfParmReadFile(buf, GFPARM_RMODE_STD);
      if (!robhdle) 
      {
        snprintf(buf, sizeof(buf), "drivers/%s/%s.xml", robotModuleName, robotModuleName);
        robhdle = GfParmReadFile(buf, GFPARM_RMODE_STD);
      }
      if (robhdle && ( strcmp( robotModuleName, "human" ) == 0 || strcmp( robotModuleName, "networkhuman" ) == 0 ) )
      {
        /* Human driver */
        elt = reLoadSingleCar( index, i, robotIdx - (*(ReInfo->robModList))->modInfo[0].index, robotIdx, FALSE, robotModuleName );
      }
      else if (robhdle && ( strcmp( GfParmGetStr( robhdle, ROB_SECT_ARBITRARY, ROB_ATTR_TEAM, "foo" ),
                              GfParmGetStr( robhdle, ROB_SECT_ARBITRARY, ROB_ATTR_TEAM, "bar" ) ) == 0 ) )
      {
        elt = reLoadSingleCar( index, i, (*(ReInfo->robModList))->modInfoSize, robotIdx, FALSE, robotModuleName );
      }
      else
        GfLogError("No descriptor for robot %s (2)\n", robotModuleName );
    }

    if (elt)
      ++index;
  }

  nCars = index; /* real number of cars */
  if (nCars == 0) 
  {
    GfLogError("No driver for that race ; exiting ...\n");
    return -1;
  }
  else 
  {
    GfLogInfo("%d driver(s) ready to race\n", nCars);
  }

  if (replayReplay)
    replayRecord = 0;
  else {
        char buf[1024];
	const char *replayRateSchemeName;
        snprintf(buf, sizeof(buf), "%s%s", GfLocalDir(), RACE_ENG_CFG);

        void *paramHandle = GfParmReadFile(buf, GFPARM_RMODE_REREAD | GFPARM_RMODE_CREAT);
        replayRateSchemeName = GfParmGetStr(paramHandle, RM_SECT_RACE_ENGINE, RM_ATTR_REPLAY_RATE, "0");
        GfParmReleaseHandle(paramHandle);

	replayRecord = atoi(replayRateSchemeName);
  }

  if (replayRecord || replayReplay) {
#ifdef THIRD_PARTY_SQLITE3
    int result;

    result = sqlite3_open("/tmp/race.sqlite", &replayDB);
    if (result) {
      GfLogError("Replay: Unable to open Database: %s\n", sqlite3_errmsg(replayDB));
      sqlite3_close(replayDB);
      replayDB = NULL;
    } else {
      GfLogInfo("Replay: Database Opened 0x8%8.8X\n", replayDB);

      if (replayRecord)
        GfLogInfo("Replay: Record Timestep = %f\n", 1/(float)replayRecord);

      if (replayReplay)
        GfLogInfo("Replay: Playback from file\n");

      /* speed up database by turning of synchronous behaviour/etc */
      sqlite3_exec(replayDB, "PRAGMA synchronous = OFF", NULL, NULL, NULL);
      sqlite3_exec(replayDB, "PRAGMA journal_mode = OFF", NULL, NULL, NULL);
      sqlite3_exec(replayDB, "PRAGMA count_changes = OFF", NULL, NULL, NULL);
#if 0 // This pragma seems to prevent re-opening the sqlite3 database
      sqlite3_exec(replayDB, "PRAGMA locking_mode = EXCLUSIVE", NULL, NULL, NULL);
#endif
      sqlite3_exec(replayDB, "PRAGMA default_temp_store = MEMORY", NULL, NULL, NULL);

      //replayBlobs = (sqlite3_stmt *) calloc(nCars, sizeof(void *)); //sqlite3_stmt));

      replayTimestamp = -5;
      ghostcarActive = 0;
    }
#endif
  }

  ReInfo->s->_ncars = nCars;
  FREEZ(ReInfo->s->cars);
  ReInfo->s->cars = (tCarElt **)calloc(nCars, sizeof(tCarElt *));
  for (i = 0; i < nCars; i++)
  {
    ReInfo->s->cars[i] = &(ReInfo->carList[i]);

#ifdef THIRD_PARTY_SQLITE3
    //open a table for each car
    if (replayDB) {
      char command[200];
      int result;

      if (replayRecord) {
        sprintf(command, "DROP TABLE IF EXISTS car%d", i);
        result = sqlite3_exec(replayDB, command, 0, 0, 0);
        if (result) GfLogInfo("Replay: Unable to drop table car%d: %s\n", i, sqlite3_errmsg(replayDB));
      }

      sprintf(command, "CREATE TABLE IF NOT EXISTS car%d (timestamp, lap, datablob BLOB)", i);
      result = sqlite3_exec(replayDB, command, 0, 0, 0);
      if (result) {
         GfLogInfo("Replay: Unable to create table car%d: %s\n", i, sqlite3_errmsg(replayDB));
         exit(0);
      }

      if (replayReplay) {
        // Build index to allow faster read access
        sprintf(command, "CREATE UNIQUE INDEX IF NOT EXISTS index%d ON car%d (timestamp)", i, i);
        result = sqlite3_exec(replayDB, command, 0, 0, 0);
        if (result) GfLogInfo("Replay: Unable to create index car%d: %s\n", i, sqlite3_errmsg(replayDB));
      }
    }
#endif
  }

  ReInfo->_rePitRequester = 0;

  // TODO: reconsider splitting the call into one for cars, track and maybe other objects.
  // I stuff for now anything into one call because collision detection works with the same
  // library on all objects, so it is a bit dangerous to distribute the handling to various
  // locations (because the library maintains global state like a default collision handler etc.).
  RePhysicsEngine().initialize(nCars, ReInfo->track);

  initStartingGrid();

  initPits();

  return 0;
}
コード例 #17
0
void GfFileSetup()
{
	void *dataVersionHandle;
	void *localVersionHandle;
	char *filename;
	size_t filenameLength;
	char *dataLocation;
	char *localLocation;
	char *absLocalLocation;
	char *absDataLocation;
	bool *isIndexUsed;
	int isIndexUsedLen;
	int index;
	bool anyLocalChange, fileFound;
	int major;
	int minor;
	struct stat st;

	// Open data (installation) version.xml.
	filenameLength = strlen(GfDataDir()) + 12 + 40;
	filename = (char*)malloc( sizeof(char) * filenameLength );
	sprintf( filename, "%sversion.xml", GfDataDir() );
	dataVersionHandle = GfParmReadFile( filename, GFPARM_RMODE_STD );
	if( !dataVersionHandle )
	{
		free( filename );
		return;
	}

	// Exit if nothing inside.
	if( GfParmListSeekFirst( dataVersionHandle, "versions" ) != 0 )
	{
		free( filename );
		GfParmReleaseHandle( dataVersionHandle );
		return;
	}

	// Create LocalDir (user settings root) if not already done.
	GfDirCreate( GfLocalDir() );

	// Open local (user settings) version.xml (create it if not there).
	if( filenameLength < strlen(GfLocalDir()) + 12 )
	{
		free( filename );
		filenameLength = strlen(GfLocalDir()) + 12 + 40;
		filename = (char*)malloc( sizeof(char) * filenameLength );
	}

	sprintf( filename, "%sversion.xml", GfLocalDir() );
	anyLocalChange = !GfFileExists(filename);
	localVersionHandle = GfParmReadFile( filename, GFPARM_RMODE_CREAT );

	// Exit if open/creation failed.
	if( !localVersionHandle )
	{
		free( filename );
		GfParmReleaseHandle( dataVersionHandle );
		return;
	}

	// Setup the index of the XML files referenced in the local version.xml.
	isIndexUsedLen = GfParmGetEltNb( localVersionHandle, "versions" )
		             + GfParmGetEltNb( dataVersionHandle, "versions" ) + 2;
	isIndexUsed = (bool*)malloc( sizeof(bool) * isIndexUsedLen );
	for( index = 0; index < isIndexUsedLen; index++ )
		isIndexUsed[index] = false;
	if( GfParmListSeekFirst( localVersionHandle, "versions" ) == 0 )
	{
		do
		{
			index = atoi( GfParmListGetCurEltName( localVersionHandle, "versions" ) );
			if( 0 <= index && index < isIndexUsedLen )
				isIndexUsed[index] = true;
		} while( GfParmListSeekNext( localVersionHandle, "versions" ) == 0 );
	}

	// For each file referenced in the installation version.xml
	do
	{
		fileFound = false;

		// Get its installation path (data), user settings path (local),
		// and new major and minor version numbers
		dataLocation = strdup( GfParmGetCurStr( dataVersionHandle, "versions", "Data location", "" ) );
		localLocation = strdup( GfParmGetCurStr( dataVersionHandle, "versions", "Local location", "" ) );
		major = (int)GfParmGetCurNum( dataVersionHandle, "versions", "Major version", NULL, 0 );
		minor = (int)GfParmGetCurNum( dataVersionHandle, "versions", "Minor version", NULL, 0 );

		absLocalLocation = (char*)malloc( sizeof(char)*(strlen(GfLocalDir())+strlen(localLocation)+3) );
		sprintf( absLocalLocation, "%s%s", GfLocalDir(), localLocation );

		absDataLocation = (char*)malloc( sizeof(char)*(strlen(GfDataDir())+strlen(dataLocation)+3) );
		sprintf( absDataLocation, "%s%s", GfDataDir(), dataLocation );

		GfLogTrace("Checking %s : user settings version ", localLocation);

		// Search for its old major and minor version numbers in the user settings.
		if( GfParmListSeekFirst( localVersionHandle, "versions" ) == 0 )
		{
			do
			{
				if( strcmp( absLocalLocation, GfParmGetCurStr( localVersionHandle, "versions", "Local location", "" ) ) == 0 )
				{
					fileFound = true;
					const int locMinor = (int)GfParmGetCurNum( localVersionHandle, "versions", "Minor version", NULL, 0 );
					const int locMajor = (int)GfParmGetCurNum( localVersionHandle, "versions", "Major version", NULL, 0 );

					GfLogTrace("%d.%d is ", locMajor, locMinor);

					if( locMajor != major || locMinor < minor)
					{
						GfLogTrace("obsolete (installed one is %d.%d) => updating ...\n",
								   major, minor);
						if ( gfFileSetupCopy( absDataLocation, absLocalLocation, major, minor, localVersionHandle, -1 ) )
							anyLocalChange = true;
					}
					else
					{
					    GfLogTrace("up-to-date");
						if (stat(absLocalLocation, &st))
						{
							GfLogTrace(", but not there => installing ...\n");
							if ( gfFileSetupCopy( absDataLocation, absLocalLocation, major, minor, localVersionHandle, -1 ) )
								anyLocalChange = true;
						}
						else
							GfLogTrace(".\n");
					}
					
					break;
				}
			} while( GfParmListSeekNext( localVersionHandle, "versions" ) == 0 );
		}

		if( !fileFound)
		{
			index = 0;
			while( isIndexUsed[index] )
				++index;
			GfLogTrace("not found => installing ...\n");
			if ( gfFileSetupCopy( absDataLocation, absLocalLocation, major, minor, localVersionHandle, index ) )
				anyLocalChange = true;
			isIndexUsed[index] = true;
		}

		free( dataLocation );
		free( localLocation );
		free( absDataLocation );
		free( absLocalLocation );

	} while( GfParmListSeekNext( dataVersionHandle, "versions" ) == 0 );

	// Write the user settings version.xml if changed.
	if (anyLocalChange)
		GfParmWriteFile( NULL, localVersionHandle, "versions" );

	GfParmReleaseHandle( localVersionHandle );
	GfParmReleaseHandle( dataVersionHandle );
	free( isIndexUsed );
	free( filename );
}
コード例 #18
0
static void
rmQualifResults(void *prevHdle, tRmInfo *info, const char* pszTitle, int start)
{
    void		*results = info->results;
    const char		*race = info->_reRaceName;
    int			i;
    static char		buf[256];
    static char		path[512];
    char		*str;

	GfLogTrace("Entering %s Results menu\n", pszTitle);

    // Create screen, load menu XML descriptor and create static controls.
    rmScrHdle = GfuiScreenCreate();
    void *hmenu = GfuiMenuLoad("qualifsresultsmenu.xml");
    GfuiMenuCreateStaticControls(rmScrHdle, hmenu);

    // Create variable title label.
    const int titleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Title");
    snprintf(buf, sizeof(buf), "%s at %s", race, info->track->name);
    GfuiLabelSetText(rmScrHdle, titleId, buf);

	// Get layout properties.
    const int nMaxLines = (int)GfuiMenuGetNumProperty(hmenu, "nMaxResultLines", 15);
    const int yTopLine = (int)GfuiMenuGetNumProperty(hmenu, "yTopLine", 400);
    const int yLineShift = (int)GfuiMenuGetNumProperty(hmenu, "yLineShift", 20);

	// Never used : remove ?
    //snprintf(path, sizeof(path), "%s/%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK, 1);
    //tdble refTime = GfParmGetNum(results, path, RE_ATTR_TIME, NULL, 0);
    //snprintf(path, sizeof(path), "%s/%s/%s", info->track->name, RE_SECT_RESULTS, race);
    //const int totLaps = (int)GfParmGetNum(results, path, RE_ATTR_LAPS, NULL, 0);
    snprintf(path, sizeof(path), "%s/%s/%s/%s", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK);
    const int nbCars = (int)GfParmGetEltNb(results, path);
	GfLogDebug("rmQualifResults: path=%s, file=%s\n", path, GfParmGetFileName(results));
	GfLogDebug("rmQualifResults: start=%d, nbCars=%d, nMaxLines=%d\n", start, nbCars, nMaxLines);
	
	int y = yTopLine;
    for (i = start; i < MIN(start + nMaxLines, nbCars); i++) {
		snprintf(path, sizeof(path), "%s/%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, RE_SECT_RANK, i + 1);
		// Never used : remove ?
		//const int laps = (int)GfParmGetNum(results, path, RE_ATTR_LAPS, NULL, 0);

        //Rank
        snprintf(buf, sizeof(buf), "%d", i+1);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Rank", true, // From template.
								   buf, GFUI_TPL_X, y);

        //Driver short name
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverName", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_SNAME, ""), GFUI_TPL_X, y);

        //Driver type
        const std::string strModName = GfParmGetStr(results, path, RE_ATTR_MODULE, "");
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "DriverType", true, // From template.
								   GfDriver::getType(strModName).c_str(), GFUI_TPL_X, y);

        //Car
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "CarModel", true, // From template.
								   GfParmGetStr(results, path, RE_ATTR_CAR, ""), GFUI_TPL_X, y);


        //Best lap
        str = GfTime2Str(GfParmGetNum(results, path, RE_ATTR_BEST_LAP_TIME, NULL, 0), 0, false, 3);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "BestLapTime", true, // From template.
								   str, GFUI_TPL_X, y);
        free(str);

		// Next line.
		y -= yLineShift;
    }//for i


    if (start > 0) {
		RmPrevRace.prevHdle = prevHdle;
		RmPrevRace.info     = info;
		RmPrevRace.start    = start - nMaxLines;
		RmPrevRace.title    = pszTitle;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "PreviousPageArrow",
									(void*)&RmPrevRace, rmChgQualifScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEUP,   "Previous Results", (void*)&RmPrevRace, rmChgQualifScreen, NULL);
    }

    // Add "Continue" button 
    GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "ContinueButton", prevHdle, GfuiScreenReplace);
    
    //Create 'save' button in the bottom right
    //rmSaveButtonId = GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "savebutton", info, rmSaveRes);

    if (i < nbCars) {
		RmNextRace.prevHdle = prevHdle;
		RmNextRace.info     = info;
		RmNextRace.start    = start + nMaxLines;
		RmNextRace.title    = pszTitle;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "NextPageArrow",
									(void*)&RmNextRace, rmChgQualifScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEDOWN, "Next Results", (void*)&RmNextRace, rmChgQualifScreen, NULL);
    }

    GfuiAddKey(rmScrHdle, GFUIK_ESCAPE, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_RETURN, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F12, "Take a Screen Shot", NULL, GfuiScreenShot, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F1, "Help", rmScrHdle, GfuiHelpScreen, NULL);

    GfuiScreenActivate(rmScrHdle);
}
コード例 #19
0
// The event loop itself.
void GfuiEventLoop::operator()()
{
	SDL_Event event; // Event structure
#if SDL_MAJOR_VERSION >= 2
	static int unicode = 0;
   static SDL_Keymod modifier = KMOD_NONE;
#endif

	// Check for events.
	while (!quitRequested())
	{
		// Loop until there are no events left in the queue.
		while (!quitRequested() && SDL_PollEvent(&event))
		{
		    // Process events we care about, and ignore the others.
			switch(event.type)
			{
				case SDL_KEYDOWN:
#if SDL_MAJOR_VERSION < 2
					   injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 0,event.key.keysym.unicode);
#else
					if((event.key.keysym.sym & SDLK_SCANCODE_MASK) == SDLK_SCANCODE_MASK)
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 0,0);
					}
					else if(false == isprint(event.key.keysym.sym))
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 0,0);
					}
					else if((event.key.keysym.mod != KMOD_NONE)
							&&(event.key.keysym.mod != KMOD_LSHIFT)
							&&(event.key.keysym.mod != KMOD_RSHIFT))
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 0,0);
					}
#if 0
					else
					{
						printf("SDL_KEYDOWN: %c\r\n",(char)event.key.keysym.sym);
					}
#endif
#endif
					break;

#if SDL_MAJOR_VERSION >= 2
				case SDL_TEXTINPUT:
					unicode = (int)(event.text.text[0]);
					modifier = SDL_GetModState();
					injectKeyboardEvent(unicode,modifier, 0,0);
					//printf("SDL_TEXTINPUT: %c %X\r\n",(char)unicode,modifier);
					break;
#endif

				case SDL_KEYUP:
#if SDL_MAJOR_VERSION < 2
					injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 1,event.key.keysym.unicode);
#else
					if((event.key.keysym.sym & SDLK_SCANCODE_MASK) == SDLK_SCANCODE_MASK)
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 1,0);
					}
					else if(false == isprint(event.key.keysym.sym))
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 1,0);
					}
					else if((event.key.keysym.mod != KMOD_NONE)
							&&(event.key.keysym.mod != KMOD_LSHIFT)
							&&(event.key.keysym.mod != KMOD_RSHIFT))
					{
						injectKeyboardEvent(event.key.keysym.sym, event.key.keysym.mod, 1,0);
					}
					else
					{
						injectKeyboardEvent(unicode, event.key.keysym.mod, 1,0);
						//printf("SDL_KEYUP: %c unicode = %c\r\n",(char)event.key.keysym.sym,unicode);
					}
#endif
					break;

				case SDL_MOUSEMOTION:
					injectMouseMotionEvent(event.motion.state, event.motion.x, event.motion.y);
					break;


				case SDL_MOUSEBUTTONDOWN:
				case SDL_MOUSEBUTTONUP:
					injectMouseButtonEvent(event.button.button, event.button.state,
										   event.button.x, event.button.y);
					break;

				case SDL_QUIT:
					postQuit();
					break;

#if SDL_MAJOR_VERSION >= 2
#if SDL_JOYSTICK
				case SDL_JOYAXISMOTION:
					injectJoystickAxisEvent(event.jaxis.which, event.jaxis.axis, (float) event.jaxis.value / 32768);
					break;

				case SDL_JOYBUTTONDOWN:
					injectJoystickButtonEvent(event.jbutton.which, event.jbutton.button, SDL_PRESSED);
					break;

				case SDL_JOYBUTTONUP:
					injectJoystickButtonEvent(event.jbutton.which, event.jbutton.button, 0);
					break;
#endif
				case SDL_WINDOWEVENT_EXPOSED:
#else
				case SDL_VIDEOEXPOSE:
#endif
					forceRedisplay();
					break;
			}
		}

		if (!quitRequested())
		{
			// Recompute if anything to.
			recompute();

			// Redisplay if anything to.
			redisplay();
		}
	}

	GfLogTrace("Quitting GFUI event loop.\n");
}
コード例 #20
0
static void
rmPracticeResults(void *prevHdle, tRmInfo *info, int start)
{
	// Used across rmPracticeResults calls when multiple pages.
	static int NLastLapDamages = 0;

    void		*results = info->results;
    const char		*race = info->_reRaceName;
    int			i;
    int			y;
    static char		buf[256];
    static char		path[1024];
    char		*str;
    int 		damages; 

    // Create screen, load menu XML descriptor and create static controls.
    rmScrHdle = GfuiScreenCreate();

	GfLogTrace("Entering Practice Results menu\n");

    void *hmenu = GfuiMenuLoad("practiceresultsmenu.xml");
    GfuiMenuCreateStaticControls(rmScrHdle, hmenu);

    // Create variable title labels.
    snprintf(buf, sizeof(buf), "%s at %s", race, info->track->name);
    const int titleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Title");
    GfuiLabelSetText(rmScrHdle, titleId, buf);
 
    snprintf(path, sizeof(path), "%s/%s/%s", info->track->name, RE_SECT_RESULTS, race);
    snprintf(buf, sizeof(buf), "%s (%s)", GfParmGetStr(results, path, RM_ATTR_DRVNAME, NULL),
			 GfParmGetStr(results, path, RM_ATTR_CAR, NULL));

    const int subTitleId = GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "SubTitle");
    GfuiLabelSetText(rmScrHdle, subTitleId, buf);
 
	// Get layout properties.
    const int nMaxLines = (int)GfuiMenuGetNumProperty(hmenu, "nMaxResultLines", 15);
    const int yTopLine = (int)GfuiMenuGetNumProperty(hmenu, "yTopLine", 400);
    const int yLineShift = (int)GfuiMenuGetNumProperty(hmenu, "yLineShift", 20);

	
	// Display the result table.
    y = yTopLine;
    
    snprintf(path, sizeof(path), "%s/%s/%s", info->track->name, RE_SECT_RESULTS, race);
    const int totLaps = (int)GfParmGetEltNb(results, path);

	// Reset last damage value if top of the table.
	if (start == 0)
		NLastLapDamages = 0; 
	else {
		snprintf(path, sizeof(path), "%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, start - 1);
		NLastLapDamages =  (int)(GfParmGetNum(results, path, RE_ATTR_DAMMAGES, NULL, 0)); 
	}

    for (i = 0 + start; i < MIN(start + nMaxLines, totLaps); i++) {
		snprintf(path, sizeof(path), "%s/%s/%s/%d", info->track->name, RE_SECT_RESULTS, race, i + 1);

		/* Lap */
		snprintf(buf, sizeof(buf), "%d", i+1);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "LapNumber", true, // From template.
								   buf, GFUI_TPL_X, y);

		/* Time */
		str = GfTime2Str(GfParmGetNum(results, path, RE_ATTR_TIME, NULL, 0), "  ", false, 3);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "LapTime", true, // From template.
								   str, GFUI_TPL_X, y);
		free(str);

		/* Best Lap Time */
		str = GfTime2Str(GfParmGetNum(results, path, RE_ATTR_BEST_LAP_TIME, NULL, 0), "  ", false, 3);
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "BestTime", true, // From template.
								   str, GFUI_TPL_X, y);
		free(str);

		/* Top Spd */
		snprintf(buf, sizeof(buf), "%3.1f", (GfParmGetNum(results, path, RE_ATTR_TOP_SPEED, NULL, 0) * 3.6));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "TopSpeed", true, // From template.
								   buf, GFUI_TPL_X, y);

		/* Min Spd */
		snprintf(buf, sizeof(buf), "%3.1f", (GfParmGetNum(results, path, RE_ATTR_BOT_SPEED, NULL, 0) * 3.6));
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "MinSpeed", true, // From template.
								   buf, GFUI_TPL_X, y);

		/* Damages in current lap + (total so far) */
		damages =  (int)(GfParmGetNum(results, path, RE_ATTR_DAMMAGES, NULL, 0)); 
		snprintf(buf, sizeof(buf), "%d (%d)", damages ? damages - NLastLapDamages : 0, damages); 
		GfuiMenuCreateLabelControl(rmScrHdle, hmenu, "Damages", true, // From template.
								   buf, GFUI_TPL_X, y);
		NLastLapDamages = damages; 

		y -= yLineShift;
    }

    if (start > 0) {
		RmPrevRace.prevHdle = prevHdle;
		RmPrevRace.info     = info;
		RmPrevRace.start    = start - nMaxLines;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "PreviousPageArrow",
									(void*)&RmPrevRace, rmChgPracticeScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEUP,   "Previous Results", (void*)&RmPrevRace, rmChgPracticeScreen, NULL);
    }
    
    // Add "Continue" button
    GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "ContinueButton", prevHdle, GfuiScreenReplace);
    
    //Create 'save' button in the bottom right
    //rmSaveButtonId = GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "SaveButton", info, rmSaveRes);
    
    if (i < totLaps) {
		RmNextRace.prevHdle = prevHdle;
		RmNextRace.info     = info;
		RmNextRace.start    = start + nMaxLines;
		GfuiMenuCreateButtonControl(rmScrHdle, hmenu, "NextPageArrow",
									(void*)&RmNextRace, rmChgPracticeScreen);
		GfuiAddKey(rmScrHdle, GFUIK_PAGEDOWN, "Next Results", (void*)&RmNextRace, rmChgPracticeScreen, NULL);
    }

    GfuiAddKey(rmScrHdle, GFUIK_ESCAPE, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_RETURN, "Continue", prevHdle, GfuiScreenReplace, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F12, "Take a Screen Shot", NULL, GfuiScreenShot, NULL);
    GfuiAddKey(rmScrHdle, GFUIK_F1, "Help", rmScrHdle, GfuiHelpScreen, NULL);

    GfuiScreenActivate(rmScrHdle);
}
コード例 #21
0
/*
 * Function
 *	GfModInitialize
 *
 * Description
 *	Initialize the module with given handle and library file path
 *
 * Parameters
 *	soHandle (in)	handle of the loaded shared library
 *	soPath   (in)	path of the loaded shared library
 *	gfid     (in)	id of the gaming framework that the module MUST implement to be initialized
 *	                (Not taken into account if == GfIdAny)
 *	mod      (in)	address of module entry to allocate and initialize  
 *	                (0 if any error occured or modules not retained for bad GFId)
 *
 * Return
 *	0	if initialization succeeded (even if the module was rejected for bad GFId)
 *	-1	if any error occured
 *
 * Remarks
 *	
 */
int GfModInitialize(tSOHandle soHandle, const char *soPath, unsigned int gfid, tModList **mod)
{
    tfModInfoWelcome    fModInfoWelcome; /* function to exchange  information with the module at welcome time */
    tfModInfoInitialize	fModInfoInit = 0;	 /* init function of the module */
    int   initSts = 0;	 /* returned status */
    int	  retained = 1;
    char  soName[256];
    char  soDir[1024];
    char* lastSlash;
    
    /* Allocate module entry in list */
    if (!(*mod = (tModList*)calloc(1, sizeof(tModList))))
    {
		GfLogError("GfModInitialize: Failed to allocate tModList for module %s\n", soPath);
		return -1;
    }
    
    /* Determine the shared library / DLL name and load dir */
    strcpy(soDir, soPath);
    lastSlash = strrchr(soDir, '/');
    if (lastSlash)
    {
		strcpy(soName, lastSlash+1);
		*lastSlash = 0;
    }
    else
    {
		strcpy(soName, soPath);
		*soDir = 0;
    }
    soName[strlen(soName) - SOFileExtLen] = 0; /* cut so file extension */

    /* Welcome the module : exchange informations with it :
       1) Call the dedicated module function if present */
    if ((fModInfoWelcome = (tfModInfoWelcome)dlsym(SOHandle(soHandle), GfModInfoWelcomeFuncName)) != 0) 
    {
        /* Prepare information to give to the module */
		tModWelcomeIn welcomeIn;
		welcomeIn.itfVerMajor = 1;
		welcomeIn.itfVerMinor = 0;
		welcomeIn.name = soName;

		/* Prepare a place for the module-given information */
		tModWelcomeOut welcomeOut;

		/* Call the welcome function */
		if ((initSts = fModInfoWelcome(&welcomeIn, &welcomeOut)) != 0)
		{
			GfLogError("GfModInitialize: Module welcome function failed %s\n", soPath);
		}
		else
		{
			/* Save information given by the module */
			(*mod)->modInfoSize = welcomeOut.maxNbItf;
		}
    } 

    /* 2) If not present, default number of interfaces (backward compatibility) */
    else
    {
        (*mod)->modInfoSize = GfModInfoDefaultMaxItf;
    }

    /* Get module initialization function if welcome succeeded :
       1) Try the new sheme (fixed name) */
    if (initSts == 0)
	{
		fModInfoInit =
			(tfModInfoInitialize)dlsym(SOHandle(soHandle), GfModInfoInitializeFuncName);
		//GfLogDebug("GfModInitialize: fModInfoInit(%s) @ %p\n",
		//		   GfModInfoInitializeFuncName, fModInfoInit);
	}
	/* 2) Backward compatibility (dll name) */
	if (initSts == 0 && !fModInfoInit)
	{
		fModInfoInit = (tfModInfoInitialize)dlsym(SOHandle(soHandle), soName);
		//GfLogDebug("GfModInitialize: fModInfoInit(%s) @ %p\n", soName, fModInfoInit);
	}
	
    /* Call module initialization function if welcome succeeded and init function found */
    if (initSts == 0 && fModInfoInit) 
    {
		/* Allocate module interfaces info array according to the size we got */
		tModInfo* constModInfo;
		if ((constModInfo = GfModInfoAllocate((*mod)->modInfoSize)) != 0) 
		{
			/* Library loaded, init function exists, call it... */
			if ((initSts = fModInfoInit(constModInfo)) == 0)
			{
				/* Duplicate strings in each interface, in case the module gave us static data ! */
				if (((*mod)->modInfo = GfModInfoDuplicate(constModInfo, (*mod)->modInfoSize)) != 0) 
				{
					/* Reject module if not of requested gaming framework Id */
					if (gfid != GfIdAny && (*mod)->modInfo[0].gfId != gfid) 
					{
						GfLogTrace("GfModInitialize: Module not retained %s\n", soPath);
						GfModInfoFreeNC((*mod)->modInfo, (*mod)->modInfoSize);
						retained = 0;
					}
		    
					/* Free the module info data returned by the module (we have a copy) */
					GfModInfoFree(constModInfo);
				}
				else
				{
					initSts = -1;
				}
			} 
			else
			{
				GfLogError("GfModInitialize: Module init function failed %s\n", soPath);
			}
		}
		else
		{
			initSts = -1;
		}
    } 

    /* If init function not found, we have a problem ... */
    else
    {
		GfLogError("GfModInitialize: Module init function %s not found ...  %s\n", 
				soPath, dlerror());
		initSts = -1;
    }

    /* Store other module information */
    if (initSts == 0 && retained)
    {
        GfOut("Initialized module %s (maxItf=%d)\n", soPath, (*mod)->modInfoSize);
		(*mod)->handle = (tSOHandle)soHandle;
		(*mod)->sopath = strdup(soPath);
    }
    else
    {
        free(*mod);
		*mod = 0;
    }

    return initSts;
}
コード例 #22
0
ファイル: racetrack.cpp プロジェクト: 702nADOS/speed-dreams
// Initialize track weather info from race settings
void
reTrackInitWeather(void)
{
	static const char* CloudsValues[] = RM_VALS_CLOUDS;
	static const int NCloudsValues = sizeof(CloudsValues) / sizeof(const char*);
	
	static const char *RainValues[] = RM_VALS_RAIN;
	static const int NRainValues = sizeof(RainValues) / sizeof(const char*);

	tTrackLocalInfo *trackLocal = &ReInfo->track->local;

	// Load cloud cover settings for the session
	// (defaults to  "All sesions" one, or else "none").
	int clouds = TR_CLOUDS_NONE;
	const char* pszClouds =
		GfParmGetStr(ReInfo->params, ReInfo->_reRaceName, RM_ATTR_CLOUDS, 0);
	if (!pszClouds)
		pszClouds =
			GfParmGetStr(ReInfo->params, RM_VAL_ANYRACE, RM_ATTR_CLOUDS, RM_VAL_CLOUDS_NONE);
	for (int i = 0; i < NCloudsValues; i++)
		if (!strcmp(pszClouds, CloudsValues[i]))
		{
			clouds = i;
			break;
		}

	// Load rain fall (and track dry/wet conditions) settings for the session
	// if feature supported (defaults to  "All sesions" one, or else "none").
	int rain = TR_RAIN_NONE;
	if (ReInfo->s->_features & RM_FEATURE_WETTRACK)
	{
		const char* pszRain =
			GfParmGetStr(ReInfo->params, ReInfo->_reRaceName, RM_ATTR_RAIN, 0);
		if (!pszRain)
			pszRain =
				GfParmGetStr(ReInfo->params, RM_VAL_ANYRACE, RM_ATTR_RAIN, RM_VAL_RAIN_NONE);
		for (int i = 0; i < NRainValues; i++)
			if (!strcmp(pszRain, RainValues[i]))
			{
				rain = i;
				break;
			}
	}

	// Take care of the random case for rain falls and ground water.
	const bool bRandomRain = (rain == TR_RAIN_RANDOM);
	if (bRandomRain)
	{
		// Force random clouds, in case there is no rain at the end.
		clouds = TR_CLOUDS_RANDOM;
		
		// Random rain (if random[0,1] < trackLocal->anyrainlkhood, then it rains).
		const tdble randDraw = (tdble)(rand()/(double)RAND_MAX);

		GfLogTrace("Rain likelyhoods : overall=%.2f, little=%.2f, medium=%.2f\n",
				   trackLocal->anyrainlkhood, trackLocal->littlerainlkhood,
				   trackLocal->mediumrainlkhood);
		GfLogDebug("Overall rain random draw = %.2f,\n", randDraw);
		if (randDraw < trackLocal->anyrainlkhood)
		{
			// Now, let's determine how much it rains :
			// if random[0,1] < little rain likelyhood => rain = little rain
			const tdble randDraw2 = (tdble)(rand()/(double)RAND_MAX);
			GfLogDebug("Specific rain random draw = %.2f,\n", randDraw2);
			if (randDraw2 < trackLocal->littlerainlkhood)
				rain = TR_RAIN_LITTLE;
			// else if random[0,1] < medium + little rain likelyhood => rain = medium rain
			else if (randDraw2 <  trackLocal->littlerainlkhood + trackLocal->mediumrainlkhood)
				rain = TR_RAIN_MEDIUM;
			// otherwise, random[0,1] >= medium + little rain likelyhood => rain = Heavy rain
			else
				rain = TR_RAIN_HEAVY;
		}
		else
		{
			// No Rain.
			rain = TR_RAIN_NONE;
		}
	}
	
	// Take care of the random case for clouds cover.
	const bool bRandomClouds = (clouds == TR_CLOUDS_RANDOM);
	if (bRandomClouds)
	{
		if (rain != TR_RAIN_NONE)
		{
			// If any rain level, heavy clouds.
			clouds = TR_CLOUDS_FULL;
		}
		else
		{
			// Really random clouds.
			clouds = rand() % (TR_CLOUDS_FULL + 1);
		}
	}

	// Ground water = rain for the moment (might change in the future).
	const int water = rain;
	
	GfLogInfo("Weather : Using %s rain (%d) and ground water (%d) + %s clouds (%d) settings\n",
			  bRandomRain ? "random" : "user defined", rain, water,
			  bRandomClouds ? "random" : "user defined", clouds);
	
	// Update track local info.
	trackLocal->rain = rain;
	trackLocal->clouds = clouds;
	trackLocal->water = water;

	// Update track physics from computed local info.
	reTrackUpdatePhysics();
}
コード例 #23
0
OpenalSound::OpenalSound(const char* filename, OpenalSoundInterface* sitf,
						 int flags, bool loop, bool static_pool)
: Sound(flags, loop)
{
	this->static_pool = static_pool;
	poolindex = -1;
	itf = sitf;

	MAX_DISTANCE = 10000.0f;
	MAX_DISTANCE_LOW = 5.0f;
	REFERENCE_DISTANCE = 5.0f;
	ROLLOFF_FACTOR = 0.5f;

	int i;
	for (i = 0; i<3; i++) {
		source_position[i] = 0.0f;
		source_velocity[i] = 0.0f;
		zeroes[i] = 0.0f;
	}

	GfLogTrace("OpenAL : Creating %s source from %s\n",
			   static_pool ? "static" : "dynamic", filename);

	int error = alGetError();
	if (error != AL_NO_ERROR) {
		printf("Uncatched OpenAL Error on entry: %d with file %s\n", error, filename);
	}
	
	alGenBuffers (1, &buffer);
	error = alGetError();
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alGenBuffers failed %s\n", error, filename);
		is_enabled = false;
		return;
	}

	SDL_AudioSpec wavspec;
	Uint32 wavlen;
	Uint8 *wavbuf;
	if (!SDL_LoadWAV(filename, &wavspec, &wavbuf, &wavlen))
	{
		if (alIsBuffer(buffer))
			alDeleteBuffers(1, &buffer);
		GfError("OpenAL Error: Could not load %s (%s)\n", filename, SDL_GetError());
		is_enabled = false;
		return;
	}

	if (wavspec.channels > 1)
	{
		if (alIsBuffer(buffer))
			alDeleteBuffers(1, &buffer);
		GfError("OpenAL Error: Unsupported stereo sample %s\n", filename);
		is_enabled = false;
		return;
	}

	// Map WAV header to OpenAL format
	ALenum format;
	switch(wavspec.format)
	{
		case AUDIO_U8:
		case AUDIO_S8:
			format = AL_FORMAT_MONO8;
			break;
		case AUDIO_U16:
		case AUDIO_S16:
			format = AL_FORMAT_MONO16;
			break;
		default:
			SDL_FreeWAV(wavbuf);
			if (alIsBuffer(buffer))
				alDeleteBuffers(1, &buffer);
			GfError("OpenAL Error: Unsupported WAV format %d for %s (not among U8, S8, U16, S16)\n",
					wavspec.format, filename);
			is_enabled = false;
			return;
	}

	alBufferData(buffer, format, wavbuf, wavlen, wavspec.freq);
	error = alGetError();
	if (error != AL_NO_ERROR)
	{
		GfError("OpenAL Error: %d, alBufferData %s\n", error, filename);
		SDL_FreeWAV(wavbuf);
		if (alIsBuffer(buffer)) {
			alDeleteBuffers(1, &buffer);
			alGetError();
		}
		is_enabled = false;
		return;
	}
	
	SDL_FreeWAV(wavbuf);
	
	if (!static_pool) {
		is_enabled = true;
		return;
	}
	
	if (!sitf->getStaticSource(&source)) {
		is_enabled = false;
		printf("    No static sources left: %s\n", filename);
		if (alIsBuffer(buffer)) {
			alDeleteBuffers(1, &buffer);
			alGetError();
		}
		return;
	} else {
		is_enabled = true;	
	}

	alSourcefv (source, AL_POSITION, source_position);
	error = alGetError();
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcefv AL_POSITION %s\n", error, filename);
	}

	alSourcefv (source, AL_VELOCITY, source_velocity);
	error = alGetError();
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcefv AL_VELOCITY %s\n", error, filename);
	}

	alSourcei (source, AL_BUFFER, buffer);
	error = alGetError();
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcei AL_BUFFER %s\n", error, filename);
	}

	alSourcei (source, AL_LOOPING, loop);
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcei AL_LOOPING %s\n", error, filename);
	}

	alSourcef (source, AL_MAX_DISTANCE, MAX_DISTANCE);
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcef AL_MAX_DISTANCE %s\n", error, filename);
	}

	alSourcef (source, AL_REFERENCE_DISTANCE, REFERENCE_DISTANCE);
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcef AL_REFERENCE_DISTANCE %s\n", error, filename);
	}

	alSourcef (source, AL_ROLLOFF_FACTOR, ROLLOFF_FACTOR);
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcef AL_ROLLOFF_FACTOR %s\n", error, filename);
	}

	alSourcef (source, AL_GAIN, 0.0f);
	if (error != AL_NO_ERROR) {
		printf("OpenAL Error: %d, alSourcef AL_GAIN %s\n", error, filename);
	}
}
コード例 #24
0
ファイル: client.cpp プロジェクト: xinderuila1/speed-dream
bool NetClient::SendDriverInfoPacket(NetDriver *pDriver)
{
    SetDriverName(pDriver->name);
    pDriver->address.port = m_pHost->address.port;

    GfLogTrace("SendDriverInfoPacket: pDriver\n");
    GfLogTrace("->host=%d\n", pDriver->address.host);
    GfLogTrace("->port=%d\n", pDriver->address.port);
    GfLogTrace("->idx=%d\n", pDriver->idx);
    GfLogTrace("->name=%s\n", pDriver->name);
    GfLogTrace("->sname=%s\n", pDriver->sname);
    GfLogTrace("->cname=%s\n", pDriver->cname);
    GfLogTrace("->car=%s\n", pDriver->car);
    GfLogTrace("->team=%s\n", pDriver->team);
    GfLogTrace("->author=%s\n", pDriver->author);
    GfLogTrace("->racenumber=%d\n", pDriver->racenumber);
    GfLogTrace("->skilllevel=%s\n", pDriver->skilllevel);
    GfLogTrace("->red=%.1f\n", pDriver->red);
    GfLogTrace("->green=%.1f\n", pDriver->green);
    GfLogTrace("->blue=%.1f\n", pDriver->blue);
    GfLogTrace("->module=%s\n", pDriver->module);
    GfLogTrace("->type=%s\n", pDriver->type);
    GfLogTrace("->client=%d\n", pDriver->client);

    PackedBuffer msg;

    try
    {
        msg.pack_ubyte(PLAYERINFO_PACKET);
        msg.pack_int(pDriver->idx);
        msg.pack_string(pDriver->name, sizeof pDriver->name);
        msg.pack_string(pDriver->sname, sizeof pDriver->sname);
        msg.pack_string(pDriver->cname, sizeof pDriver->cname);
        msg.pack_string(pDriver->car, sizeof pDriver->car);
        msg.pack_string(pDriver->team, sizeof pDriver->team);
        msg.pack_string(pDriver->author, sizeof pDriver->author);
        msg.pack_int(pDriver->racenumber);
        msg.pack_string(pDriver->skilllevel,
                sizeof pDriver->skilllevel);
        msg.pack_float(pDriver->red);
        msg.pack_float(pDriver->green);
        msg.pack_float(pDriver->blue);
        msg.pack_string(pDriver->module, sizeof pDriver->module);
        msg.pack_string(pDriver->type, sizeof pDriver->type);
        msg.pack_int(pDriver->client);
    }
//    catch (PackedBufferException &e)
    catch (PackedBufferException)
    {
        GfLogFatal("SendDriverInfoPacket: packed buffer error\n");
    }
    GfLogTrace("SendDriverInfoPacket: packed data length=%d\n",
            msg.length());

    ENetPacket * pPacket = enet_packet_create (msg.buffer(), 
            msg.length(), 
            ENET_PACKET_FLAG_RELIABLE);

    if (enet_peer_send (m_pServer, RELIABLECHANNEL, pPacket)==0)
        return true;

    return false;
}
コード例 #25
0
ファイル: OsgScreens.cpp プロジェクト: 702nADOS/speed-dreams
void SDScreens::InitCars(tSituation *s)
{
    //char buf[256];
    //char	idx[16];
    //int		index;
    int		i;
    tCarElt 	*elt;
    //void	*hdle;
    const char *pszSpanSplit;
    int grNbSuggestedScreens = 0;

    for (i = 0; i < s->_ncars; i++) 
    {
    	elt = s->cars[i];
        //index = elt->index;
        //hdle = elt->_paramsHandle;

    	// WARNING: This index hack on the human robot for the Career mode
    	//          does no more work with the new "welcome" module system
    	//          (the "normal" index has no more the 10 limit) ... TO BE FIXED !!!!!!!
    	/*if (elt->_driverType == RM_DRV_HUMAN && elt->_driverIndex > 10)
        sprintf(idx, "Robots/index/%d", elt->_driverIndex - 11);
    else
        sprintf(idx, "Robots/index/%d", elt->_driverIndex);

    grCarInfo[index].iconColor[0] = GfParmGetNum(hdle, idx, "red",   (char*)NULL, GfParmGetNum(hdle, ROB_SECT_ARBITRARY, "red",   NULL, 0));
    grCarInfo[index].iconColor[1] = GfParmGetNum(hdle, idx, "green", (char*)NULL, GfParmGetNum(hdle, ROB_SECT_ARBITRARY, "green", NULL, 0));
    grCarInfo[index].iconColor[2] = GfParmGetNum(hdle, idx, "blue",  (char*)NULL, GfParmGetNum(hdle, ROB_SECT_ARBITRARY, "blue",  NULL, 0));
    grCarInfo[index].iconColor[3] = 1.0;
    grInitCar(elt);*/

    	// Pre-assign each human driver (if any) to a different screen
    	// (set him as the "current driver" for this screen).
    	if (grNbSuggestedScreens < SD_NB_MAX_SCREEN
        	&& elt->_driverType == RM_DRV_HUMAN && !elt->_networkPlayer)
    	{
        	Screens[grNbSuggestedScreens]->setCurrentCar(elt);
        	GfLogTrace("Screen #%d : Assigned to %s\n", grNbSuggestedScreens, elt->_name);
        	grNbSuggestedScreens++;
    	}
    }

    /* Check whether view should be spanned across vertical splits */
    pszSpanSplit = GfParmGetStr(grHandle, GR_SCT_GRAPHIC, GR_ATT_SPANSPLIT, GR_VAL_NO);
    m_SpanSplit = strcmp(pszSpanSplit, GR_VAL_YES) ? 0 : 1;

    if (m_SpanSplit == 0 && grNbSuggestedScreens > 1) 
    {
        // Mulitplayer, so ignore the stored number of screens
        m_NbActiveScreens = grNbSuggestedScreens;
        m_NbArrangeScreens = 0;
    } else 
    {
            // Load the real number of active screens and the arrangment.
        m_NbActiveScreens = (int)GfParmGetNum(grHandle, GR_SCT_DISPMODE, GR_ATT_NB_SCREENS, NULL, 1.0);
        m_NbArrangeScreens = (int)GfParmGetNum(grHandle, GR_SCT_DISPMODE, GR_ATT_ARR_SCREENS, NULL, 0.0);
    }

    // Initialize the cameras for all the screens.
    for (unsigned i=0; i<Screens.size();i++)
    {
        Screens[i]->Init(s);
    }

    // Setup the screens (= OpenGL viewports) inside the physical game window.
    this->AdaptScreenSize();
}
コード例 #26
0
ファイル: client.cpp プロジェクト: xinderuila1/speed-dream
void NetClient::ResetNetwork()
{
    if (m_pClient == NULL)
        return;

    if (m_pServer == NULL)
        return;

    ENetEvent event;

    enet_peer_disconnect (m_pServer, 0);

    bool bDisconnect = false;

    /* Allow up to 3 seconds for the disconnect to succeed
       and drop any packets received packets.
     */
    while (enet_host_service (m_pClient, & event, 3000) > 0)
    {
        switch (event.type)
        {
        case ENET_EVENT_TYPE_RECEIVE:
            enet_packet_destroy (event.packet);
            break;

        case ENET_EVENT_TYPE_DISCONNECT:
            GfLogTrace ("Network disconnection succeeded.");
            bDisconnect=true;
            break;

        case ENET_EVENT_TYPE_NONE:
        case ENET_EVENT_TYPE_CONNECT:
            // Do nothing.
            break;
        }
    }

    /* We've arrived here, so the disconnect attempt didn't */
    /* succeed yet.  Force the connection down.             */
    if (!bDisconnect)
        enet_peer_reset (m_pServer);

    NetSetClient(false);

    ENetPeer * pCurrentPeer1;

    if (m_pHost ==NULL)
        return;

    for (pCurrentPeer1 = m_pHost-> peers;
            pCurrentPeer1 < & m_pHost->peers [m_pHost->peerCount];
            ++ pCurrentPeer1)
    {
        if (pCurrentPeer1->state != ENET_PEER_STATE_CONNECTED)
            continue;

        enet_peer_reset (pCurrentPeer1);
    }

    enet_host_destroy(m_pHost);
    m_pHost = NULL;

}
コード例 #27
0
void
RmNextEventMenu(void)
{
	char buf[128];

	tRmInfo* reInfo = LmRaceEngine().inData();
	void	*params = reInfo->params;
	void	*results = reInfo->results;
	int		raceNumber;
	int		 xx;

	if (rmScrHandle) {
		GfuiScreenRelease(rmScrHandle);
	}

	GfLogTrace("Entering Next Event menu\n");
	
	// Create screen, load menu XML descriptor and create static controls.
	rmScrHandle = GfuiScreenCreate(NULL, 
								  NULL, (tfuiCallback)NULL, 
								  NULL, (tfuiCallback)NULL, 
								  1);
	void *menuXMLDescHdle = GfuiMenuLoad("racenexteventmenu.xml");
	GfuiMenuCreateStaticControls(rmScrHandle, menuXMLDescHdle);

	// Create background image from race params.
	const char* pszBGImg = GfParmGetStr(params, RM_SECT_HEADER, RM_ATTR_BGIMG, 0);
	if (pszBGImg) {
		GfuiScreenAddBgImg(rmScrHandle, pszBGImg);
	}

	// Create variable title label from race params.
	int titleId = GfuiMenuCreateLabelControl(rmScrHandle, menuXMLDescHdle, "TitleLabel");
	char pszTitle[128];
	if (LmRaceEngine().race()->getManager()->hasSubFiles())
	{
		const char* pszGroup = GfParmGetStr(reInfo->params, RM_SECT_HEADER, RM_ATTR_NAME, "<no group>");
		snprintf(pszTitle, sizeof(pszTitle), "%s - %s", reInfo->_reName, pszGroup);
	}
	else
		snprintf(pszTitle, sizeof(pszTitle), "%s", reInfo->_reName);
	GfuiLabelSetText(rmScrHandle, titleId, pszTitle);

	// Calculate which race of the series this is
	raceNumber = 1;
	for (xx = 1; xx < (int)GfParmGetNum(results, RE_SECT_CURRENT, RE_ATTR_CUR_TRACK, NULL, 1); ++xx) 
	{
		snprintf(buf, sizeof(buf), "%s/%d", RM_SECT_TRACKS, xx);
		if (!strcmp( GfParmGetStr(reInfo->params, buf, RM_ATTR_NAME, "free"), "free") == 0)
			++raceNumber;
	}

	// Create variable subtitle label from race params.
	snprintf(buf, sizeof(buf), "Race Day #%d/%d at %s",
			 raceNumber,
			 (int)GfParmGetNum(params, RM_SECT_TRACKS, RM_ATTR_NUMBER, NULL, -1 ) >= 0
			 ? (int)GfParmGetNum(params, RM_SECT_TRACKS, RM_ATTR_NUMBER, NULL, -1 )
			 : GfParmGetEltNb(params, RM_SECT_TRACKS), 
			 reInfo->track->name);
	int subTitleId = GfuiMenuCreateLabelControl(rmScrHandle, menuXMLDescHdle, "SubTitleLabel");
	GfuiLabelSetText(rmScrHandle, subTitleId, buf);

	// Create Start and Abandon buttons.
	GfuiMenuCreateButtonControl(rmScrHandle, menuXMLDescHdle, "StartButton", NULL, rmStateManage);
	GfuiMenuCreateButtonControl(rmScrHandle, menuXMLDescHdle, "AbandonButton", RmRaceSelectMenuHandle, GfuiScreenActivate);

	// Close menu XML descriptor.
	GfParmReleaseHandle(menuXMLDescHdle);
	
	// Register keyboard shortcuts.
	GfuiMenuDefaultKeysAdd(rmScrHandle);
	GfuiAddKey(rmScrHandle, GFUIK_RETURN, "Start Event", NULL, rmStateManage, NULL);
	GfuiAddKey(rmScrHandle, GFUIK_ESCAPE, "Abandon", RmRaceSelectMenuHandle, GfuiScreenActivate, NULL);

	// Activate screen.
	GfuiScreenActivate(rmScrHandle);
}
コード例 #28
0
ファイル: raceutil.cpp プロジェクト: rongzhou/speed-dreams
int RmGetFeaturesList( void* param )
{
	int nCars;
	char const *cardllname;
	int caridx;
	char const *features;
	int driverFeatureMask;
	int raceFeatureMask = -1; // All bits set to 1.
	void *robhdle;
	
	char path[ 256 ];
	char buf[ 1024 ];
	int xx, yy;
	int features_index;
	int buf_index;

	nCars = GfParmGetEltNb( param, RM_SECT_DRIVERS );
	for( xx = 1; xx < nCars + 1; ++xx )
	{
		/* Open robot */
		sprintf( path, "%s/%d", RM_SECT_DRIVERS, xx );
		cardllname = GfParmGetStr( param, path, RM_ATTR_MODULE, "" );
		caridx = (int)GfParmGetNum( param, path, RM_ATTR_IDX, NULL, 0 );
		sprintf( buf, "%s/drivers/%s/%s.xml", GfLocalDir(), cardllname, cardllname );
		robhdle = GfParmReadFile( buf, GFPARM_RMODE_STD );

		if( !robhdle )
		{
			sprintf( buf, "drivers/%s/%s.xml", cardllname, cardllname );
			robhdle = GfParmReadFile( buf, GFPARM_RMODE_STD );
		}

		if( !robhdle )
			continue;

		driverFeatureMask = 0;

		sprintf( buf, "%s/%s/%d", ROB_SECT_ROBOTS, ROB_LIST_INDEX, caridx );
		if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_TYPE, ROB_VAL_ROBOT ), ROB_VAL_HUMAN ) == 0 )
		{
			if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_ARCADE ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION;
			else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_SEMI_ROOKIE ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION;
			else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_ROOKIE ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION;
			else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_AMATEUR ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION | RM_FEATURE_WETTRACK;
			      /* | RM_FEATURE_BLUE */
			else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_SEMI_PRO ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION | RM_FEATURE_WETTRACK;
			      /* | RM_FEATURE_PENALTIES | RM_FEATURE_SC | RM_FEATURE_YELLOW | RM_FEATURE_RED | */
			else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_LEVEL, ROB_VAL_ARCADE ), ROB_VAL_PRO ) == 0 )
				driverFeatureMask |= RM_FEATURE_TIMEDSESSION | RM_FEATURE_PENALTIES | RM_FEATURE_WETTRACK;
			      /*RM_FEATURE_SC | RM_FEATURE_YELLOW | RM_FEATURE_BLUE | RM_FEATURE_RED | RM_FEATURE_PITEXIT |*/		      
		} else if( strcmp( GfParmGetStr( robhdle, buf, ROB_ATTR_TYPE, ROB_VAL_ROBOT ), ROB_VAL_ROBOT ) == 0 )
		{
			sprintf( buf, "%s/%s/%d", ROB_SECT_ROBOTS, ROB_LIST_INDEX, caridx );
			features = GfParmGetStr( robhdle, buf, ROB_ATTR_FEATURES, "" );
			features_index = 0;
			buf_index = 0;
			while( true )
			{
				if( features[ features_index ] != '\0' && features[ features_index ] != ';'
					&& buf_index < nMaxFeatureNameLength )
				{
					/* Feature name not yet ended */
					buf[ buf_index ] = features[ features_index ];
					++buf_index;
					++features_index;
				} else if( features[ features_index ] == '\0' || features[ features_index ] == ';' )
				{
					/* Feature name ended, check for matched */
					buf[ buf_index ] = '\0';
					for( yy = 0; yy < nFeatures; ++yy )
					{
						if( strcmp( features_list[ yy ].name, buf ) == 0 )
						{
							driverFeatureMask |= features_list[ yy ].value;
						}
					}
	
					if( features[ features_index ] == '\0' )
						break; /* Leave */
					++features_index;
					buf_index = 0;
				}
			}	
		}

		GfLogDebug("Driver %s#%d supported-feature mask : 0x%02X\n",
				   cardllname, caridx, driverFeatureMask);

		/* Binary and: the raceFeatureMask is only the features all cars have */
		raceFeatureMask &= driverFeatureMask;

		GfParmReleaseHandle( robhdle );
	}

	GfLogTrace("Race supported-feature mask : 0x%02X\n", raceFeatureMask);
	
	return raceFeatureMask;
}
コード例 #29
0
// Host on-line race menu.
void
RmNetworkHostMenu(void * /* dummy */)
{
	GfLogTrace("Entering Network Host menu.\n");
	
	if (!NetGetNetwork())
	{
		NetSetServer(true);
		NetSetClient(false);
		if (!NetGetServer()->Start(SPEEDDREAMSPORT))
		{
			NetSetServer(false);
			return;
		}
	}

	if (racemanMenuHdle)
		GfuiScreenRelease(racemanMenuHdle);

	racemanMenuHdle = GfuiScreenCreate(NULL,  NULL, (tfuiCallback)OnActivateNetworkHost, 
								   NULL, (tfuiCallback)NULL, 1);

	void *mparam = GfuiMenuLoad("networkhostmenu.xml");

	GfuiMenuCreateStaticControls(racemanMenuHdle, mparam);

	RmSetRacemanMenuHandle(racemanMenuHdle);

	NetworkRaceInfo();

	g_trackHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"trackname");

	g_lapsHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"lapcountname");
	g_catHd = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,"carcatname");
    
	g_OutlineId = GfuiMenuCreateStaticImageControl(racemanMenuHdle,mparam,"outlineimage");
	
	//Show players
	for (int i = 0; i < MAXNETWORKPLAYERS; i++) {
		char buf[1024];
		sprintf(buf,"ready%i",i);
		g_readystatus[i] = GfuiMenuCreateStaticImageControl(racemanMenuHdle,mparam,buf);
		GfuiVisibilitySet(racemanMenuHdle,g_readystatus[i],false);

		sprintf(buf,"driver%i",i);
		g_playerNames[i] = GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,buf);
		GfuiLabelSetText(racemanMenuHdle,g_playerNames[i],"");

		sprintf(buf,"car%i",i);
		g_carNames[i] =  GfuiMenuCreateLabelControl(racemanMenuHdle,mparam,buf);
		GfuiLabelSetText(racemanMenuHdle,g_carNames[i],"");
	}

	g_ReadyCheckboxId =
		GfuiMenuCreateCheckboxControl(racemanMenuHdle, mparam, "playerreadycheckbox",
								NULL, onHostPlayerReady);

	g_HostSettingsButtonId =
		GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "networkhostsettings",
								racemanMenuHdle, rmNetworkHostSettingsMenu);
	GfuiEnable(racemanMenuHdle, g_HostSettingsButtonId, GFUI_DISABLE);

	g_RaceSetupId =
		GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "racesetup",
								racemanMenuHdle, RmConfigureRace);

	GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "start race",
								NULL, ServerPrepareStartNetworkRace);
	g_CancelButtonId = GfuiMenuCreateButtonControl(racemanMenuHdle, mparam, "cancel",
								NULL, rmNetworkServerDisconnect);

	GfParmReleaseHandle(mparam);
	
	GfuiMenuDefaultKeysAdd(racemanMenuHdle);
	GfuiAddKey(racemanMenuHdle, GFUIK_ESCAPE, "Back to previous menu",
								0, 0, rmNetworkServerDisconnect);

	UpdateNetworkPlayers();

	GfuiScreenActivate(racemanMenuHdle);
}