Exemple #1
0
void C_Camera::SpecTargetByName(const char *name)
{
	if (!Q_stricmp(name, "ball"))
	{
		if (GetMatchBall())
		{
			SetTarget(GetMatchBall()->entindex());
		}
	}
	else
	{
		for (int i = 1; i <= gpGlobals->maxClients; i++)
		{
			C_BasePlayer *pPlayer =	UTIL_PlayerByIndex(i);

			if (!pPlayer || Q_strcmp(name, pPlayer->GetPlayerName()))
				continue;

			SetTarget(i);
			break;
		}
	}
}
void CASW_Mission_Chooser_Source_Local::OnSaveUpdated(const char *szSaveName)
{
	// if we haven't started scanning for saves yet, don't worry about it
	if (!m_bBuiltSavedCampaignList && !m_bBuildingSavedCampaignList)
		return;

	// make sure it has the campaignsave extension
	char stripped[256];
	V_StripExtension(szSaveName, stripped, sizeof(stripped));
	char szWithExtension[256];
	Q_snprintf(szWithExtension, sizeof(szWithExtension), "%s.campaignsave", stripped);
	// check it's not already in the saved list
	for (int i=0;i<m_SavedCampaignList.Count();i++)
	{
		if (!Q_strcmp(m_SavedCampaignList[i].m_szSaveName, szWithExtension))
		{
			m_SavedCampaignList.Remove(i);
			break;
		}
	}
	Msg("Updating save game summary %s\n", szSaveName);
	AddToSavedCampaignList(szWithExtension);
}
Exemple #3
0
/*
===============
Info_ValueForKey

Searches the string for the given
key and returns the associated value, or an empty string.
===============
*/
char *Info_ValueForKey( const char *s, const char *key )
{
	char	pkey[MAX_INFO_STRING];
	static	char value[2][MAX_INFO_STRING]; // use two buffers so compares work without stomping on each other
	static	int valueindex;
	char	*o;
	
	valueindex ^= 1;
	if( *s == '\\' ) s++;

	while( 1 )
	{
		o = pkey;
		while( *s != '\\' && *s != '\n' )
		{
			if( !*s ) return "";
			*o++ = *s++;
		}

		*o = 0;
		s++;

		o = value[valueindex];

		while( *s != '\\' && *s != '\n' && *s )
		{
			if( !*s ) return "";
			*o++ = *s++;
		}
		*o = 0;

		if( !Q_strcmp( key, pkey ))
			return value[valueindex];
		if( !*s ) return "";
		s++;
	}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CMaterialModifyProxy::OnBindSetVar( C_MaterialModifyControl *pControl )
{
	IMaterial *pMaterial = pControl->GetMaterial();
	if( !pMaterial )
	{
		Assert( 0 );
		return;
	}

	if ( pMaterial != m_pMaterial )
	{
//		Warning( "\t%s!=%s\n", pMaterial->GetName(), m_pMaterial->GetName() );
		return;
	}

	bool bFound;
	IMaterialVar *pMaterialVar = pMaterial->FindVar( pControl->GetMaterialVariableName(), &bFound, false );
	if ( !bFound )
		return;

	if( Q_strcmp( pControl->GetMaterialVariableValue(), "" ) )
	{
//		const char *pMaterialName = m_pMaterial->GetName();
//		const char *pMaterialVarName = pMaterialVar->GetName();
//		const char *pMaterialVarValue = pControl->GetMaterialVariableValue();
//		if( debug_materialmodifycontrol_client.GetBool() 
//			&& Q_stristr( m_pMaterial->GetName(), "faceandhair" )
//			&& Q_stristr( pMaterialVar->GetName(), "self" )
//			)
//		{
//			static int count = 0;
//			DevMsg( 1, "CMaterialModifyProxy::OnBindSetVar \"%s\" %s=%s %d pControl=0x%p\n", 
//				m_pMaterial->GetName(), pMaterialVar->GetName(), pControl->GetMaterialVariableValue(), count++, pControl );
//		}
		pMaterialVar->SetValueAutodetectType( pControl->GetMaterialVariableValue() );
	}
}
Exemple #5
0
void NET_Stats_f(void)
{
    qsocket_t *s;

    if (Cmd_Argc() == 1) {
	Con_Printf("unreliable messages sent   = %i\n",
		   unreliableMessagesSent);
	Con_Printf("unreliable messages recv   = %i\n",
		   unreliableMessagesReceived);
	Con_Printf("reliable messages sent     = %i\n", messagesSent);
	Con_Printf("reliable messages received = %i\n", messagesReceived);
	Con_Printf("packetsSent                = %i\n", packetsSent);
	Con_Printf("packetsReSent              = %i\n", packetsReSent);
	Con_Printf("packetsReceived            = %i\n", packetsReceived);
	Con_Printf("receivedDuplicateCount     = %i\n",
		   receivedDuplicateCount);
	Con_Printf("shortPacketCount           = %i\n", shortPacketCount);
	Con_Printf("droppedDatagrams           = %i\n", droppedDatagrams);
    } else if (Q_strcmp(Cmd_Argv(1), "*") == 0) {
	for (s = net_activeSockets; s; s = s->next)
	    PrintStats(s);
	for (s = net_freeSockets; s; s = s->next)
	    PrintStats(s);
    } else {
	for (s = net_activeSockets; s; s = s->next)
	    if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0)
		break;
	if (s == NULL)
	    for (s = net_freeSockets; s; s = s->next)
		if (Q_strcasecmp(Cmd_Argv(1), s->address) == 0)
		    break;
	if (s == NULL)
	    return;
	PrintStats(s);
    }
}
//-----------------------------------------------------------------------------
// 
//-----------------------------------------------------------------------------
void CBindPanel::DrawBindingName()
{
	int iconWide = m_iIconTall * m_fWidthScale * m_fScale;

	int x = (iconWide>>1);
	int y = ( m_iIconTall * m_fScale ) * 0.5f;

	if ( !m_bController && !IsConsole() )
	{
		// Draw the caption
		vgui::surface()->DrawSetTextFont( m_hKeysFont );
		int fontTall = vgui::surface()->GetFontTall( m_hKeysFont );

		char szBinding[ 256 ];
		Q_strcpy( szBinding, m_szKey );

		if ( Q_strcmp( szBinding, "SEMICOLON" ) == 0 )
		{
			Q_strcpy( szBinding, ";" );
		}
		else if ( Q_strlen( szBinding ) == 1 && szBinding[ 0 ] >= 'a' && szBinding[ 0 ] <= 'z' )
		{
			// Make single letters uppercase
			szBinding[ 0 ] += ( 'A' - 'a' );
		}

		wchar wszCaption[ 64 ];
		g_pVGuiLocalize->ConstructString( wszCaption, sizeof(wchar)*64, szBinding, NULL );

		int iWidth = GetScreenWidthForCaption( wszCaption, m_hKeysFont );

		// Draw black text
		vgui::surface()->DrawSetTextColor( 0,0,0, 255 );
		vgui::surface()->DrawSetTextPos( x - (iWidth>>1) - 1, y - (fontTall >>1) - 1 );
		vgui::surface()->DrawUnicodeString( wszCaption );
	}
Exemple #7
0
bool CHLTVDirector::StartCameraManShot()
{
	Assert( m_nNextShotTick <= m_nBroadcastTick );

	int index = FindFirstEvent( m_nNextShotTick );

	// check for cameraman mode
	while( index != m_EventHistory.InvalidIndex() )
	{
		CGameEvent &dc = m_EventHistory[index];

		// only check if this is the current tick
		if ( dc.m_Tick > m_nBroadcastTick )
			break; 

		if ( Q_strcmp( dc.m_Event->GetName(), "hltv_cameraman") == 0 )
		{
			if ( dc.m_Event->GetInt("index") > 0 )
			{
				// ok, this guy is now the active camera man
				m_iCameraMan = dc.m_Event->GetInt("index");

				m_iPVSEntity = m_iCameraMan;
				m_nNextShotTick = m_nBroadcastTick+1; // check setting right on next frame

				// send camera man command to client
				m_pHLTVServer->BroadcastEvent( dc.m_Event );
				return true;
			}
		}

		index = m_EventHistory.NextInorder( index );
	}

	return false;	// no camera man found
}
Exemple #8
0
uint VID_EnumerateInstances( void )
{
	num_instances = 0;

#ifdef _WIN32
	if( EnumWindows( &pfnEnumWnd, 0 ))
		return num_instances;
#else
#ifdef XASH_X11
	Display* display = XOpenDisplay(NULL);
	Window* winlist;
	char* name;
	unsigned long len;
	int i;

	if(!display)
	{
		MsgDev(D_ERROR, "Lol, no displays? Returning 1 instance.\n");
		return 1;
	}

	if( !(winlist = NetClientList(display, &len)) ) return 1;

	for(i = 0; i < len; i++)
	{
		if( !(name = WindowClassName(display, winlist[i])) ) continue;
		if( !Q_strcmp( name, WINDOW_NAME ) )
			num_instances++;
		free(name);
	}

	XFree(winlist);
#endif
#endif
	return 1;
}
Exemple #9
0
void KeyValues::RecursiveMergeKeyValues(KeyValues *baseKV)
{
	for (KeyValues *baseChild = baseKV->m_pSub; baseChild != NULL; baseChild = baseChild->m_pPeer)
	{
		bool bFoundMatch = false;

		for (KeyValues *newChild = m_pSub; newChild != NULL; newChild = newChild->m_pPeer)
		{
			if (!Q_strcmp(baseChild->GetName(), newChild->GetName()))
			{
				newChild->RecursiveMergeKeyValues(baseChild);
				bFoundMatch = true;
				break;
			}
		}

		if (!bFoundMatch)
		{
			KeyValues *dat = baseChild->MakeCopy();
			Assert(dat);
			AddSubKey(dat);
		}
	}
}
void ReadCheatCommandsFromFile( char *pchFileName )
{
	KeyValues *pCheatCodeKeys = new KeyValues( "cheat_codes" );
	pCheatCodeKeys->LoadFromFile( g_pFullFileSystem, pchFileName, NULL );

	KeyValues *pKey = NULL;
	for ( pKey = pCheatCodeKeys->GetFirstTrueSubKey(); pKey; pKey = pKey->GetNextTrueSubKey() )
	{
		int iCheat = s_CheatCodeCommands.AddToTail();
		CheatCodeData_t *pNewCheatCode = &(s_CheatCodeCommands[ iCheat ]);

		Q_strncpy( pNewCheatCode->szName, pKey->GetName(), CHEAT_NAME_MAX_LEN );	// Get the name
		pNewCheatCode->bDevOnly = ( pKey->GetInt( "dev", 0 ) != 0 );				// Get developer only flag
		pNewCheatCode->iCodeLength = 0;												// Start at zero code elements
		Q_strncpy( pNewCheatCode->szCommand, pKey->GetString( "command", "echo \"Cheat code has no command!\"" ), CHEAT_COMMAND_MAX_LEN );

		KeyValues *pSubKey = NULL;
		for ( pSubKey = pKey->GetFirstSubKey(); pSubKey; pSubKey = pSubKey->GetNextKey() )
		{
			const char *pchType = pSubKey->GetName();
			if ( Q_strcmp( pchType, "code" ) == 0 )
			{
				AssertMsg( ( pNewCheatCode->iCodeLength < CHEAT_NAME_MAX_LEN ), "Cheat code elements exceeded max!" );

				pNewCheatCode->pButtonCodes[ pNewCheatCode->iCodeLength ] = g_pInputSystem->StringToButtonCode( pSubKey->GetString() );
				++pNewCheatCode->iCodeLength;
			}
		}

		if ( pNewCheatCode->iCodeLength < CHEAT_NAME_MAX_LEN )
		{
			// If it's activation is a subsequence of another cheat, the longer cheat can't be activated!
			DevWarning( "Cheat code \"%s\" has less than %i code elements!", pKey->GetName(), CHEAT_NAME_MAX_LEN );
		}
	}
}
Exemple #11
0
void C_HL2MPRagdoll::Interp_Copy( C_BaseAnimatingOverlay *pSourceEntity )
{
	if ( !pSourceEntity )
		return;
	
	VarMapping_t *pSrc = pSourceEntity->GetVarMapping();
	VarMapping_t *pDest = GetVarMapping();
    	
	// Find all the VarMapEntry_t's that represent the same variable.
	for ( int i = 0; i < pDest->m_Entries.Count(); i++ )
	{
		VarMapEntry_t *pDestEntry = &pDest->m_Entries[i];
		const char *pszName = pDestEntry->watcher->GetDebugName();
		for ( int j=0; j < pSrc->m_Entries.Count(); j++ )
		{
			VarMapEntry_t *pSrcEntry = &pSrc->m_Entries[j];
			if ( !Q_strcmp( pSrcEntry->watcher->GetDebugName(), pszName ) )
			{
				pDestEntry->watcher->Copy( pSrcEntry->watcher );
				break;
			}
		}
	}
}
Exemple #12
0
void GameRulesHelper::OnServerActivated()
{
	
	printf("Doin stuf\n");
	m_pGameRulesProxy = UTIL_FindEntityByClassname(nullptr, "dota_gamerules");
	m_pGameManagerProxy = UTIL_FindEntityByClassname(nullptr, "dota_gamemanager");

	auto *pSendTable = ((IServerUnknown *) m_pGameRulesProxy)->GetNetworkable()->GetServerClass()->m_pTable;
	auto *pManagerSendTable = ((IServerUnknown *)m_pGameManagerProxy)->GetNetworkable()->GetServerClass()->m_pTable;

	if (!s_bHaveOffsets)
	{
		m_Offsets.m_nSeriesType = UTIL_FindInSendTable(pSendTable, "m_nSeriesType");
		m_Offsets.m_nRadiantSeriesWins = UTIL_FindInSendTable(pSendTable, "m_nRadiantSeriesWins");
		m_Offsets.m_nDireSeriesWins = UTIL_FindInSendTable(pSendTable, "m_nDireSeriesWins");
		m_Offsets.m_nGameState = UTIL_FindInSendTable(pSendTable, "m_nGameState");
		m_Offsets.m_fGameTime = UTIL_FindInSendTable(pSendTable, "m_fGameTime");
		m_Offsets.m_nGGTeam = UTIL_FindInSendTable(pSendTable, "m_nGGTeam");
		m_Offsets.m_flGGEndsAtTime = UTIL_FindInSendTable(pSendTable, "m_flGGEndsAtTime");
		m_Offsets.m_iGameMode = UTIL_FindInSendTable(pSendTable, "m_iGameMode");
		m_Offsets.m_bGamePaused = UTIL_FindInSendTable(pSendTable, "m_bGamePaused");
		m_Offsets.m_iPauseTeam = UTIL_FindInSendTable(pSendTable, "m_iPauseTeam");
		m_Offsets.m_StableHeroAvailable = UTIL_FindInSendTable(pManagerSendTable, "m_StableHeroAvailable");
		m_Offsets.m_CurrentHeroAvailable = UTIL_FindInSendTable(pManagerSendTable, "m_CurrentHeroAvailable");
		m_Offsets.m_CulledHeroes = UTIL_FindInSendTable(pManagerSendTable, "m_CulledHeroes");

		s_bHaveOffsets = true;
	}

	m_pGameRules = nullptr;
	m_pGameManager = nullptr;

	for (int i = 0; i < pSendTable->GetNumProps(); i++)
	{
		auto pProp = pSendTable->GetProp(i);

		if (pProp->GetDataTable() && !Q_strcmp("dota_gamerules_data", pProp->GetName()))
		{
			auto proxyFn = pProp->GetDataTableProxyFn();
			if (proxyFn)
			{
				CSendProxyRecipients recp;
				m_pGameRules = proxyFn(NULL, NULL, NULL, &recp, 0);
			}

			break;
		}
	}

	for (int i = 0; i < pManagerSendTable->GetNumProps(); i++)
	{
		auto pProp = pManagerSendTable->GetProp(i);

		if (pProp->GetDataTable() && !Q_strcmp("dota_gamemanager_data", pProp->GetName()))
		{
			auto proxyFn = pProp->GetDataTableProxyFn();

			if (proxyFn)
			{
				CSendProxyRecipients recp;
				m_pGameManager = proxyFn(NULL, NULL, NULL, &recp, 0);
				printf("Manager name: %d\n", m_pGameManager);
			}

			break;
		}
	}

	const char *pszBannedHeroes = CommandLine()->ParmValue("-d2bannedheroes", "");
	if (pszBannedHeroes && pszBannedHeroes[0])
	{
		V_SplitString(pszBannedHeroes, ",", bannedHeroes);
	}

	BanThem();
}
Exemple #13
0
// Load the bot profile database
void BotProfileManager::Init(const char *filename, unsigned int *checksum)
{
	static const char *BotDifficultyName[] = { "EASY", "NORMAL", "HARD", "EXPERT", nullptr };

	int dataLength;
	char *dataPointer = (char *)LOAD_FILE_FOR_ME(const_cast<char *>(filename), &dataLength);
	char *dataFile = dataPointer;

	if (!dataFile)
	{
		if (AreBotsAllowed())
		{
			CONSOLE_ECHO("WARNING: Cannot access bot profile database '%s'\n", filename);
		}

		return;
	}

	// compute simple checksum
	if (checksum)
	{
		*checksum = ComputeSimpleChecksum((const unsigned char *)dataPointer, dataLength);
	}

	// keep list of templates used for inheritance
	BotProfileList templateList;
	BotProfile defaultProfile;

	// Parse the BotProfile.db into BotProfile instances
	while (true)
	{
		dataFile = SharedParse(dataFile);
		if (!dataFile)
			break;

		char *token = SharedGetToken();

		bool isDefault = (!Q_stricmp(token, "Default"));
		bool isTemplate = (!Q_stricmp(token, "Template"));
		bool isCustomSkin = (!Q_stricmp(token, "Skin"));

		if (isCustomSkin)
		{
			const int BufLen = 64;
			char skinName[BufLen];

			// get skin name
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected skin name\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();
			Q_snprintf(skinName, BufLen, "%s", token);

			// get attribute name
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected 'Model'\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();
			if (Q_stricmp(token, "Model") != 0)
			{
				CONSOLE_ECHO("Error parsing %s - expected 'Model'\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			// eat '='
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected '='\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();
			if (Q_strcmp(token, "=") != 0)
			{
				CONSOLE_ECHO("Error parsing %s - expected '='\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			// get attribute value
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected attribute value\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();

			const char *decoratedName = GetDecoratedSkinName(skinName, filename);
			bool skinExists = GetCustomSkinIndex(decoratedName) > 0;
			if (m_nextSkin < NumCustomSkins && !skinExists)
			{
				// decorate the name
				m_skins[m_nextSkin] = CloneString(decoratedName);

				// construct the model filename
				m_skinModelnames[m_nextSkin] = CloneString(token);
				m_skinFilenames[m_nextSkin] = new char[Q_strlen(token) * 2 + Q_strlen("models/player//.mdl") + 1];
				Q_sprintf(m_skinFilenames[m_nextSkin], "models/player/%s/%s.mdl", token, token);
				m_nextSkin++;
			}

			// eat 'End'
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected 'End'\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();
			if (Q_strcmp(token, "End") != 0)
			{
				CONSOLE_ECHO("Error parsing %s - expected 'End'\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			// it's just a custom skin - no need to do inheritance on a bot profile, etc.
			continue;
		}

		// encountered a new profile
		BotProfile *profile;
		if (isDefault)
		{
			profile = &defaultProfile;
		}
		else
		{
			profile = new BotProfile;
			// always inherit from Default
			*profile = defaultProfile;
		}

		// do inheritance in order of appearance
		if (!isTemplate && !isDefault)
		{
			const BotProfile *inherit = nullptr;

			// template names are separated by "+"
			while (true)
			{
				char *c = Q_strchr(token, '+');
				if (c)
					*c = '\0';

				// find the given template name
				for (auto templates : templateList)
				{
					if (!Q_stricmp(templates->GetName(), token))
					{
						inherit = templates;
						break;
					}
				}

				if (!inherit)
				{
					CONSOLE_ECHO("Error parsing '%s' - invalid template reference '%s'\n", filename, token);
					FREE_FILE(dataPointer);
					return;
				}

				// inherit the data
				profile->Inherit(inherit, &defaultProfile);

				if (c == nullptr)
					break;

				token = c + 1;
			}
		}

		// get name of this profile
		if (!isDefault)
		{
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing '%s' - expected name\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			profile->m_name = CloneString(SharedGetToken());

#ifdef REGAMEDLL_FIXES
			if (RANDOM_LONG(0, 2) == 2)
#else
			// HACK HACK
			// Until we have a generalized means of storing bot preferences, we're going to hardcode the bot's
			// preference towards silencers based on his name.
			if (profile->m_name[0] % 2)
#endif
			{
				profile->m_prefersSilencer = true;
			}
		}

		// read attributes for this profile
		bool isFirstWeaponPref = true;
		while (true)
		{
			// get next token
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected 'End'\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();

			// check for End delimiter
			if (!Q_stricmp(token, "End"))
				break;

			// found attribute name - keep it
			char attributeName[64];
			Q_strcpy(attributeName, token);

			// eat '='
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected '='\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();
			if (Q_strcmp(token, "=") != 0)
			{
				CONSOLE_ECHO("Error parsing %s - expected '='\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			// get attribute value
			dataFile = SharedParse(dataFile);
			if (!dataFile)
			{
				CONSOLE_ECHO("Error parsing %s - expected attribute value\n", filename);
				FREE_FILE(dataPointer);
				return;
			}

			token = SharedGetToken();

			// store value in appropriate attribute
			if (!Q_stricmp("Aggression", attributeName))
			{
				profile->m_aggression = Q_atof(token) / 100.0f;
			}
			else if (!Q_stricmp("Skill", attributeName))
			{
				profile->m_skill = Q_atof(token) / 100.0f;
			}
			else if (!Q_stricmp("Skin", attributeName))
			{
				profile->m_skin = Q_atoi(token);

				if (profile->m_skin == 0)
				{
					// Q_atoi() failed - try to look up a custom skin by name
					profile->m_skin = GetCustomSkinIndex(token, filename);
				}
			}
			else if (!Q_stricmp("Teamwork", attributeName))
			{
				profile->m_teamwork = Q_atof(token) / 100.0f;
			}
			else if (!Q_stricmp("Cost", attributeName))
			{
				profile->m_cost = Q_atoi(token);
			}
			else if (!Q_stricmp("VoicePitch", attributeName))
			{
				profile->m_voicePitch = Q_atoi(token);
			}
			else if (!Q_stricmp("VoiceBank", attributeName))
			{
				profile->m_voiceBank = FindVoiceBankIndex(token);
			}
			else if (!Q_stricmp("WeaponPreference", attributeName))
			{
				// weapon preferences override parent prefs
				if (isFirstWeaponPref)
				{
					isFirstWeaponPref = false;
					profile->m_weaponPreferenceCount = 0;
				}

				if (!Q_stricmp(token, "none"))
				{
					profile->m_weaponPreferenceCount = 0;
				}
				else
				{
					if (profile->m_weaponPreferenceCount < BotProfile::MAX_WEAPON_PREFS)
					{
						profile->m_weaponPreference[profile->m_weaponPreferenceCount++] = AliasToWeaponID(token);
					}
				}
			}
			else if (!Q_stricmp("ReactionTime", attributeName))
			{
				profile->m_reactionTime = Q_atof(token);

#ifndef GAMEUI_EXPORTS
				// subtract off latency due to "think" update rate.
				// In GameUI, we don't really care.
				profile->m_reactionTime -= g_flBotFullThinkInterval;
#endif

			}
			else if (!Q_stricmp("AttackDelay", attributeName))
			{
				profile->m_attackDelay = Q_atof(token);
			}
			else if (!Q_stricmp("Difficulty", attributeName))
			{
				// override inheritance
				profile->m_difficultyFlags = 0;

				// parse bit flags
				while (true)
				{
					char *c = Q_strchr(token, '+');
					if (c)
						*c = '\0';

					for (int i = 0; i < NUM_DIFFICULTY_LEVELS; i++)
					{
						if (!Q_stricmp(BotDifficultyName[i], token))
							profile->m_difficultyFlags |= (1<<i);
					}

					if (c == nullptr)
						break;

					token = c + 1;
				}
			}
			else if (!Q_stricmp("Team", attributeName))
			{
				if (!Q_stricmp(token, "T"))
				{
					profile->m_teams = BOT_TEAM_T;
				}
				else if (!Q_stricmp(token, "CT"))
				{
					profile->m_teams = BOT_TEAM_CT;
				}
				else
				{
					profile->m_teams = BOT_TEAM_ANY;
				}
			}
			else
			{
				CONSOLE_ECHO("Error parsing %s - unknown attribute '%s'\n", filename, attributeName);
			}
		}

		if (!isDefault)
		{
			if (isTemplate)
			{
				// add to template list
				templateList.push_back(profile);
			}
			else
			{
				// add profile to the master list
				m_profileList.push_back(profile);
			}
		}
	}

	FREE_FILE(dataPointer);

	// free the templates
	for (auto templates : templateList)
		delete templates;

	templateList.clear();
}
inline bool FStruEq(const char *sz1, const char *sz2)
{
	return(Q_strcmp(sz1, sz2) == 0);
}
Exemple #15
0
static bool StrLess( const char * const &pszLeft, const char * const &pszRight )
{
	return ( Q_strcmp( pszLeft, pszRight) < 0 );
}
Exemple #16
0
/*
==================
SV_SetPlayer

Sets sv_client and sv_player to the player with idnum Cmd_Argv(1)
==================
*/
qboolean SV_SetPlayer( void )
{
	char		*s;
	sv_client_t	*cl;
	int		i, idnum;

	if( !svs.clients || sv.background )
	{
		Msg( "^3No server running.\n" );
		return false;
	}

	if( sv_maxclients->integer == 1 || Cmd_Argc() < 2 )
	{
		// special case for local client
		svs.currentPlayer = svs.clients;
		svs.currentPlayerNum = 0;
		return true;
	}

	s = Cmd_Argv( 1 );

	// numeric values are just slot numbers
	if( Q_isdigit( s ) || (s[0] == '-' && Q_isdigit( s + 1 )))
	{
		idnum = Q_atoi( s );
		if( idnum < 0 || idnum >= sv_maxclients->integer )
		{
			Msg( "Bad client slot: %i\n", idnum );
			return false;
		}

		svs.currentPlayer = &svs.clients[idnum];
		svs.currentPlayerNum = idnum;

		if( !svs.currentPlayer->state )
		{
			Msg( "Client %i is not active\n", idnum );
			return false;
		}
		return true;
	}

	// check for a name match
	for( i = 0, cl = svs.clients; i < sv_maxclients->integer; i++, cl++ )
	{
		if( !cl->state ) continue;
		if( !Q_strcmp( cl->name, s ))
		{
			svs.currentPlayer = cl;
			svs.currentPlayerNum = (cl - svs.clients);
			return true;
		}
	}

	Msg( "Userid %s is not on the server\n", s );
	svs.currentPlayer = NULL;
	svs.currentPlayerNum = 0;

	return false;
}
Exemple #17
0
void C_HLTVCamera::FireGameEvent( IGameEvent * event)
{
	if ( !g_bEngineIsHLTV )
		return;	// not in HLTV mode

	const char *type = event->GetName();

	if ( Q_strcmp( "game_newmap", type ) == 0 )
	{
		Reset();	// reset all camera settings

		// show spectator UI
		if ( !GetViewPortInterface() )
			return;

		if ( engine->IsPlayingDemo() )
        {
			// for demo playback show full menu
			GetViewPortInterface()->ShowPanel( PANEL_SPECMENU, true );

			SetMode( OBS_MODE_ROAMING );
		}
		else
		{
			// during live broadcast only show black bars
			GetViewPortInterface()->ShowPanel( PANEL_SPECGUI, true );
		}

		return;
	}

	if ( Q_strcmp( "hltv_message", type ) == 0 )
	{
		wchar_t outputBuf[1024];
		const char *pszText = event->GetString( "text", "" );
		
		char *tmpStr = hudtextmessage->LookupString( pszText );
		const wchar_t *pBuf = g_pVGuiLocalize->Find( tmpStr );
		if ( pBuf )
		{
			// Copy pBuf into szBuf[i].
			int nMaxChars = sizeof( outputBuf ) / sizeof( wchar_t );
			wcsncpy( outputBuf, pBuf, nMaxChars );
			outputBuf[nMaxChars-1] = 0;
		}
		else
		{
			g_pVGuiLocalize->ConvertANSIToUnicode( tmpStr, outputBuf, sizeof(outputBuf) );
		}

		GetCenterPrint()->Print( ConvertCRtoNL( outputBuf ) );
		return ;
	}

	if ( Q_strcmp( "hltv_title", type ) == 0 )
	{
		Q_strncpy( m_szTitleText, event->GetString( "text", "" ), sizeof(m_szTitleText) );
		return;
	}

	if ( Q_strcmp( "hltv_status", type ) == 0 )
	{
		int nNumProxies = event->GetInt( "proxies" );
		m_nNumSpectators = event->GetInt( "clients" ) - nNumProxies;
		return;
	}

	// after this only auto-director commands follow
	// don't execute them is autodirector is off and PVS is unlocked
	if ( !spec_autodirector.GetBool() && !IsPVSLocked() )
		return;

	if ( Q_strcmp( "hltv_cameraman", type ) == 0 )
	{
		Reset();

		m_nCameraMode = OBS_MODE_ROAMING;
		m_iCameraMan = event->GetInt( "index" ); 
		
		return;
	}

	if ( Q_strcmp( "hltv_fixed", type ) == 0 )
	{
		m_iCameraMan  = 0;
		
		m_vCamOrigin.x = event->GetInt( "posx" );
		m_vCamOrigin.y = event->GetInt( "posy" );
		m_vCamOrigin.z = event->GetInt( "posz" );

		QAngle angle;
 		angle.x = event->GetInt( "theta" );
		angle.y = event->GetInt( "phi" );
		angle.z = 0; // no roll yet

		if ( m_nCameraMode != OBS_MODE_FIXED )
		{
			SetMode( OBS_MODE_FIXED );
			SetCameraAngle( angle );
			m_flFOV = event->GetFloat( "fov", 90 );
		}

		SetPrimaryTarget( event->GetInt( "target" ) );

		if ( m_iTraget1 == 0 )
		{
			SetCameraAngle( angle );
		}
						
		return;
	}

	if ( Q_strcmp( "hltv_chase", type ) == 0 )
	{
		bool bInEye	= event->GetBool( "ineye" );

		// check if we are already in a player chase mode
		bool bIsInChaseMode = (m_nCameraMode==OBS_MODE_IN_EYE)|| (m_nCameraMode==OBS_MODE_CHASE);

		// if we are in auto director or not in a valid chase mode, set new mode now
		if ( spec_autodirector.GetBool() || !bIsInChaseMode )
		{
			SetMode( bInEye?OBS_MODE_IN_EYE:OBS_MODE_CHASE );
		}

		m_iCameraMan  = 0;
				
		m_iTraget2		= event->GetInt( "target2" );
		m_flDistance	= event->GetFloat( "distance", m_flDistance );
		m_flOffset		= event->GetFloat( "offset", m_flOffset );
		m_flTheta		= event->GetFloat( "theta", m_flTheta );
		m_flPhi			= event->GetFloat( "phi", m_flPhi );
		m_flFOV			= event->GetFloat( "fov", 90 );
 		m_flInertia		= event->GetFloat( "inertia", 30.f ) / 10.f;

		// if inertia is not set use standard value
		if ( m_flInertia <= 0 )
			m_flInertia = 3.0f;

		SetPrimaryTarget( event->GetInt( "target1" ) );
							
		return;
	}
}
//=========================================================
// ClientUserInfoChanged
//=========================================================
void CTeamplayRules::ClientSettingsChanged( CBasePlayer *pPlayer )
{
	/* TODO: handle skin, model & team changes 

  	char text[1024];

	// skin/color/model changes
	int iTeam = Q_atoi( engine->GetClientConVarValue( pPlayer->entindex(), "cl_team" ) );
	int iClass = Q_atoi( engine->GetClientConVarValue( pPlayer->entindex(), "cl_class" ) );

	if ( defaultteam.GetBool() )
	{
		// int clientIndex = pPlayer->entindex();

		// engine->SetClientKeyValue( clientIndex, "model", pPlayer->TeamName() );
		// engine->SetClientKeyValue( clientIndex, "team", pPlayer->TeamName() );
		UTIL_SayText( "Not allowed to change teams in this game!\n", pPlayer );
		return;
	}

	if ( defaultteam.GetFloat() || !IsValidTeam( mdls ) )
	{
		// int clientIndex = pPlayer->entindex();

		// engine->SetClientKeyValue( clientIndex, "model", pPlayer->TeamName() );
		Q_snprintf( text,sizeof(text), "Can't change team to \'%s\'\n", mdls );
		UTIL_SayText( text, pPlayer );
		Q_snprintf( text,sizeof(text), "Server limits teams to \'%s\'\n", m_szTeamList );
		UTIL_SayText( text, pPlayer );
		return;
	}

	ChangePlayerTeam( pPlayer, mdls, true, true );
	// recound stuff
	RecountTeams(); */

	const char *pszName = engine->GetClientConVarValue( pPlayer->entindex(), "name" );

	const char *pszOldName = pPlayer->GetPlayerName();

	// msg everyone if someone changes their name,  and it isn't the first time (changing no name to current name)
	// Note, not using FStrEq so that this is case sensitive
	if ( pszOldName[0] != 0 && Q_strcmp( pszOldName, pszName ) )
	{
		IGameEvent * event = gameeventmanager->CreateEvent( "player_changename" );
		if ( event )
		{
			event->SetInt( "userid", pPlayer->GetUserID() );
			event->SetString( "oldname", pszOldName );
			event->SetString( "newname", pszName );
			gameeventmanager->FireEvent( event );
		}
		
		pPlayer->SetPlayerName( pszName );
	}

	// NVNT see if this user is still or has began using a haptic device
	const char *pszHH = engine->GetClientConVarValue( pPlayer->entindex(), "hap_HasDevice" );
	if(pszHH)
	{
		int iHH = atoi(pszHH);
		pPlayer->SetHaptics(iHH!=0);
	}
}
/* <1ef79d> ../cstrike/dlls/career_tasks.cpp:385 */
void CCareerTask::__MAKE_VHOOK(OnEvent)(GameEventType event, CBasePlayer *pVictim, CBasePlayer *pAttacker)
{
	if (m_isComplete)
		return;

	if (event == m_event)
	{
		if ((m_defuser && !pAttacker->m_bIsDefusing) || (m_vip && !pAttacker->m_bIsVIP))
			return;

		if (m_rescuer)
		{
			int hostages_ = 0;
			CBaseEntity *hostageEntity = NULL;

			while ((hostageEntity = UTIL_FindEntityByClassname(hostageEntity, "hostage_entity")) != NULL)
			{
				if (hostageEntity->pev->takedamage != DAMAGE_YES)
					continue;

				CHostage *hostage = static_cast<CHostage *>(hostageEntity);

				if (!hostage->IsFollowingSomeone())
					continue;

				if (hostage->IsValid() && hostage->m_target == pAttacker)
					++hostages_;
			}

			if (!hostages_)
			{
				return;
			}
		}

		if (m_event != EVENT_KILL || (!m_weaponId && !m_weaponClassId)
			&& m_event != EVENT_HEADSHOT || (!m_weaponId && !m_weaponClassId)
			&& m_event != EVENT_PLAYER_TOOK_DAMAGE || (!m_weaponId && !m_weaponClassId))
		{
			if (m_event == EVENT_ROUND_WIN)
			{
				if (!Q_strcmp(m_name, "defendhostages"))
				{
					int hostages_ = 0;
					CBaseEntity *hostageEntity = NULL;

					while ((hostageEntity = UTIL_FindEntityByClassname(hostageEntity, "hostage_entity")) != NULL)
					{
						if (hostageEntity->pev->takedamage != 1.0f && hostageEntity->pev->deadflag != DEAD_DEAD)
							++hostages_;
					}

					if (!hostages_)
					{
						++m_eventsSeen;
						SendPartialNotification();
					}
				}
				else if (!Q_strcmp(m_name, "hostagessurvive"))
				{
					int hostages_ = 0;
					CBaseEntity *hostageEntity = NULL;

					while ((hostageEntity = UTIL_FindEntityByClassname(hostageEntity, "hostage_entity")) != NULL)
					{
						CHostage *hostage = (CHostage *)hostageEntity;

						if (hostage && hostage->IsDead())
							++hostages_;
					}

					if (!hostages_)
					{
						++m_eventsSeen;
						SendPartialNotification();
					}
				}
				else if (!Q_strcmp(m_name, "winfast"))
				{
					if (m_eventsNeeded >= TheCareerTasks->GetRoundElapsedTime())
					{
						m_eventsSeen = m_eventsNeeded;
						SendPartialNotification();
					}
				}
				else if (IsTaskCompletableThisRound())
				{
					++m_eventsSeen;
					SendPartialNotification();
				}
			}
			else
			{
				++m_eventsSeen;
				SendPartialNotification();
			}
		}
	}

	if (event == m_event && !m_mustLive && m_eventsSeen >= m_eventsNeeded && IsTaskCompletableThisRound())
	{
		CBasePlayer *player = UTIL_GetLocalPlayer();
		EMIT_SOUND(ENT(player->pev), CHAN_VOICE, "events/task_complete.wav", VOL_NORM, ATTN_NORM);

		m_isComplete = true;
		MESSAGE_BEGIN(MSG_ALL, gmsgCZCareer);
			WRITE_STRING("TASKDONE");
			WRITE_BYTE(m_id);
		MESSAGE_END();

		if (TheTutor != NULL)
		{
			TheTutor->OnEvent(EVENT_CAREER_TASK_DONE);
		}

		UTIL_LogPrintf("Career Task Done %d\n", m_id);

		if (m_event == EVENT_ROUND_WIN && !Q_strcmp(m_name, "winfast"))
		{
			TheCareerTasks->SetFinishedTaskTime((int)TheCareerTasks->GetRoundElapsedTime());
			UTIL_GetLocalPlayer()->SyncRoundTimer();
		}
	}
	else if (event >= EVENT_ROUND_DRAW)
	{
		if (event > EVENT_ROUND_LOSS)
		{
			if (event == EVENT_DIE && (m_mustLive || m_crossRounds))
			{
				m_eventsSeen = 0;
				SendPartialNotification();
				m_diedThisRound = true;
			}
		}
		else if (m_mustLive)
		{
			if (m_eventsSeen >= m_eventsNeeded && !m_diedThisRound && IsTaskCompletableThisRound())
			{
				CBasePlayer *player = UTIL_GetLocalPlayer();
				EMIT_SOUND(ENT(player->pev), CHAN_VOICE, "events/task_complete.wav", VOL_NORM, ATTN_NORM);

				m_isComplete = true;
				MESSAGE_BEGIN(MSG_ALL, gmsgCZCareer);
					WRITE_STRING("TASKDONE");
					WRITE_BYTE(m_id);
				MESSAGE_END();

				UTIL_LogPrintf("Career Task Done %d\n", m_id);

				if (m_event == EVENT_ROUND_WIN && !Q_strcmp(m_name, "winfast"))
				{
					TheCareerTasks->SetFinishedTaskTime((int)TheCareerTasks->GetRoundElapsedTime());
					UTIL_GetLocalPlayer()->SyncRoundTimer();
				}

				if (TheTutor != NULL)
				{
					TheTutor->OnEvent(EVENT_CAREER_TASK_DONE);
				}
			}

			m_diedThisRound = false;

			if (m_mustLive)
			{
				m_eventsSeen = 0;
				SendPartialNotification();
			}
		}
	}
}
void CNB_Vote_Panel::UpdateVoteLabels()
{
	m_pProgressBar->SetPos( YRES( 10 ), YRES( 40 ) );

	// update yes/no press buttons
	C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer();
	if ( !pPlayer )
		return;

	m_pMapNameLabel->SetVisible( true );
	m_pYesVotesLabel->SetVisible( true );
	m_pNoVotesLabel->SetVisible( true );

	m_pTitle->SetText( "#asw_vote_mission_title" );

	if ( pPlayer->m_iMapVoted.Get() == 0 )
	{
		if ( gpGlobals->curtime > m_flCheckBindings )
		{
			Q_snprintf(m_szVoteYesKey, sizeof(m_szVoteYesKey), "%s", ASW_FindKeyBoundTo( "vote_yes" ) );
			Q_strupr(m_szVoteYesKey);
			Q_snprintf(m_szVoteNoKey, sizeof(m_szVoteNoKey), "%s", ASW_FindKeyBoundTo( "vote_no" ) );
			Q_strupr(m_szVoteNoKey);

			m_flCheckBindings += 1.0f;
		}		
		// copy the found key into wchar_t format (localize it if it's a token rather than a normal keyname)
		wchar_t keybuffer[ 12 ];
		wchar_t buffer[64];
		g_pVGuiLocalize->ConvertANSIToUnicode( m_szVoteYesKey, keybuffer, sizeof( keybuffer ) );		
		g_pVGuiLocalize->ConstructString( buffer, sizeof(buffer), g_pVGuiLocalize->Find("#press_to_vote_yes"), 1, keybuffer );
		m_pPressToVoteYesLabel->SetText( buffer );

		g_pVGuiLocalize->ConvertANSIToUnicode( m_szVoteNoKey, keybuffer, sizeof( keybuffer ) );		
		g_pVGuiLocalize->ConstructString( buffer, sizeof(buffer), g_pVGuiLocalize->Find("#press_to_vote_no"), 1, keybuffer );
		m_pPressToVoteNoLabel->SetText( buffer );
	}
	else if ( pPlayer->m_iMapVoted.Get() == 1 )
	{
		m_pPressToVoteYesLabel->SetText( "#asw_you_voted_no" );
		m_pPressToVoteNoLabel->SetText( "" );
	}
	else
	{
		m_pPressToVoteYesLabel->SetText( "#asw_you_voted_yes" );
		m_pPressToVoteNoLabel->SetText( "" );
	}

	// update timer
	/*
	int iSecondsLeft = ASWGameRules()->GetCurrentVoteTimeLeft();
	if (iSecondsLeft != m_iSecondsLeft)
	{
		m_iSecondsLeft = iSecondsLeft;
		char buffer[8];
		Q_snprintf(buffer, sizeof(buffer), "%d", iSecondsLeft);

		wchar_t wnumber[8];
		g_pVGuiLocalize->ConvertANSIToUnicode(buffer, wnumber, sizeof( wnumber ));

		wchar_t wbuffer[96];		
		g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
			g_pVGuiLocalize->Find("#asw_time_left"), 1,
			wnumber);
		m_pCounterLabel->SetText(wbuffer);
	}
	*/
	m_pCounterLabel->SetText( "" );

	// update count and other labels
	if (m_iYesCount != ASWGameRules()->GetCurrentVoteYes())
	{
		m_iYesCount = ASWGameRules()->GetCurrentVoteYes();
		char buffer[8];
		Q_snprintf(buffer, sizeof(buffer), "%d", m_iYesCount);

		wchar_t wnumber[8];
		g_pVGuiLocalize->ConvertANSIToUnicode(buffer, wnumber, sizeof( wnumber ));

		wchar_t wbuffer[96];		
		g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
			g_pVGuiLocalize->Find("#asw_yes_votes"), 1,
			wnumber);
		m_pYesVotesLabel->SetText(wbuffer);
	}
	if (m_iNoCount != ASWGameRules()->GetCurrentVoteNo())
	{
		m_iNoCount = ASWGameRules()->GetCurrentVoteNo();
		char buffer[8];
		Q_snprintf(buffer, sizeof(buffer), "%d", m_iNoCount);

		wchar_t wnumber[8];
		g_pVGuiLocalize->ConvertANSIToUnicode(buffer, wnumber, sizeof( wnumber ));

		wchar_t wbuffer[96];		
		g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
			g_pVGuiLocalize->Find("#asw_no_votes"), 1,
			wnumber);
		m_pNoVotesLabel->SetText(wbuffer);
	}	
	if (Q_strcmp(m_szMapName, ASWGameRules()->GetCurrentVoteDescription()))
	{
		Q_snprintf(m_szMapName, sizeof(m_szMapName), "%s", ASWGameRules()->GetCurrentVoteDescription());

		wchar_t wmapname[64];
		g_pVGuiLocalize->ConvertANSIToUnicode(m_szMapName, wmapname, sizeof( wmapname ));

		wchar_t wbuffer[96];						
		if (ASWGameRules()->GetCurrentVoteType() == ASW_VOTE_CHANGE_MISSION)
		{
			m_pTitle->SetText( "#asw_vote_mission_title" );
			m_bVoteMapInstalled = true;
			if ( missionchooser && missionchooser->LocalMissionSource() )
			{
				if ( !missionchooser->LocalMissionSource()->GetMissionDetails( ASWGameRules()->GetCurrentVoteMapName() ) )
					m_bVoteMapInstalled = false;
			}

			if ( m_bVoteMapInstalled )
			{
				const char *szContainingCampaign = ASWGameRules()->GetCurrentVoteCampaignName();
				if ( !szContainingCampaign || !szContainingCampaign[0] )
				{
					_snwprintf( wbuffer, sizeof( wbuffer ), L"%s", wmapname );
				}
				else
				{
					_snwprintf( wbuffer, sizeof( wbuffer ), L"%s", wmapname );
				}
			}
			else
			{
				g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
					g_pVGuiLocalize->Find("#asw_current_mission_vote_not_installed"), 1,
					wmapname);
			}
		}
		else if (ASWGameRules()->GetCurrentVoteType() == ASW_VOTE_SAVED_CAMPAIGN)
		{
			m_pTitle->SetText( "#asw_vote_saved_title" );
			g_pVGuiLocalize->ConstructString( wbuffer, sizeof(wbuffer),
				g_pVGuiLocalize->Find("#asw_current_saved_vote"), 1,
				wmapname);
		}

		int w, t;
		m_pMapNameLabel->GetSize(w, t);
		if (m_pMapNameLabel->GetTextImage())
			m_pMapNameLabel->GetTextImage()->SetSize(w, t);
		m_pMapNameLabel->SetText(wbuffer);
		m_pMapNameLabel->InvalidateLayout(true);
	}
}
Exemple #21
0
static qsocket_t *_Datagram_CheckNewConnections (void)
{
	struct qsockaddr clientaddr;
	struct qsockaddr newaddr;
	int			newsock;
	int			acceptsock;
	qsocket_t	*sock;
	qsocket_t	*s;
	int			len;
	int			command;
	int			control;
	int			ret;

	acceptsock = dfunc.CheckNewConnections();
	if (acceptsock == -1)
		return NULL;

	SZ_Clear(&net_message);

	len = dfunc.Read (acceptsock, net_message.data, net_message.maxsize, &clientaddr);
	if (len < sizeof(int))
		return NULL;
	net_message.cursize = len;

	MSG_BeginReading ();
	control = BigLong(*((int *)net_message.data));
	MSG_ReadLong();
	if (control == -1)
		return NULL;
	if ((control & (~NETFLAG_LENGTH_MASK)) !=  NETFLAG_CTL)
		return NULL;
	if ((control & NETFLAG_LENGTH_MASK) != len)
		return NULL;

	command = MSG_ReadByte();
	if (command == CCREQ_SERVER_INFO)
	{
		if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0)
			return NULL;

		SZ_Clear(&net_message);
		// save space for the header, filled in later
		MSG_WriteLong(&net_message, 0);
		MSG_WriteByte(&net_message, CCREP_SERVER_INFO);
		dfunc.GetSocketAddr(acceptsock, &newaddr);
		MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr));
		MSG_WriteString(&net_message, hostname.string);
		MSG_WriteString(&net_message, sv.name);
		MSG_WriteByte(&net_message, net_activeconnections);
		MSG_WriteByte(&net_message, svs.maxclients);
		MSG_WriteByte(&net_message, NET_PROTOCOL_VERSION);
		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
		dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
		SZ_Clear(&net_message);
		return NULL;
	}

	if (command == CCREQ_PLAYER_INFO)
	{
		int			playerNumber;
		int			activeNumber;
		int			clientNumber;
		client_t	*client;
		
		playerNumber = MSG_ReadByte();
		activeNumber = -1;
		for (clientNumber = 0, client = svs.clients; clientNumber < svs.maxclients; clientNumber++, client++)
		{
			if (client->active)
			{
				activeNumber++;
				if (activeNumber == playerNumber)
					break;
			}
		}
		if (clientNumber == svs.maxclients)
			return NULL;

		SZ_Clear(&net_message);
		// save space for the header, filled in later
		MSG_WriteLong(&net_message, 0);
		MSG_WriteByte(&net_message, CCREP_PLAYER_INFO);
		MSG_WriteByte(&net_message, playerNumber);
		MSG_WriteString(&net_message, client->name);
		MSG_WriteLong(&net_message, client->colors);
		MSG_WriteLong(&net_message, (int)client->edict->v.frags);
		MSG_WriteLong(&net_message, (int)(net_time - client->netconnection->connecttime));
		MSG_WriteString(&net_message, client->netconnection->address);
		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
		dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
		SZ_Clear(&net_message);

		return NULL;
	}

	if (command == CCREQ_RULE_INFO)
	{
		char	*prevCvarName;
		cvar_t	*var;

		// find the search start location
		prevCvarName = MSG_ReadString();
		if (*prevCvarName)
		{
			var = Cvar_FindVar (prevCvarName);
			if (!var)
				return NULL;
			var = var->next;
		}
		else
			var = cvar_vars;

		// search for the next server cvar
		while (var)
		{
			if (var->server)
				break;
			var = var->next;
		}

		// send the response

		SZ_Clear(&net_message);
		// save space for the header, filled in later
		MSG_WriteLong(&net_message, 0);
		MSG_WriteByte(&net_message, CCREP_RULE_INFO);
		if (var)
		{
			MSG_WriteString(&net_message, var->name);
			MSG_WriteString(&net_message, var->string);
		}
		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
		dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
		SZ_Clear(&net_message);

		return NULL;
	}

	if (command != CCREQ_CONNECT)
		return NULL;

	if (Q_strcmp(MSG_ReadString(), "QUAKE") != 0)
		return NULL;

	if (MSG_ReadByte() != NET_PROTOCOL_VERSION)
	{
		SZ_Clear(&net_message);
		// save space for the header, filled in later
		MSG_WriteLong(&net_message, 0);
		MSG_WriteByte(&net_message, CCREP_REJECT);
		MSG_WriteString(&net_message, "Incompatible version.\n");
		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
		dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
		SZ_Clear(&net_message);
		return NULL;
	}

#ifdef BAN_TEST
	// check for a ban
	if (clientaddr.sa_family == AF_INET)
	{
		unsigned long testAddr;
		testAddr = ((struct sockaddr_in *)&clientaddr)->sin_addr.s_addr;
		if ((testAddr & banMask) == banAddr)
		{
			SZ_Clear(&net_message);
			// save space for the header, filled in later
			MSG_WriteLong(&net_message, 0);
			MSG_WriteByte(&net_message, CCREP_REJECT);
			MSG_WriteString(&net_message, "You have been banned.\n");
			*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
			dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
			SZ_Clear(&net_message);
			return NULL;
		}
	}
#endif

	// see if this guy is already connected
	for (s = net_activeSockets; s; s = s->next)
	{
		if (s->driver != net_driverlevel)
			continue;
		ret = dfunc.AddrCompare(&clientaddr, &s->addr);
		if (ret >= 0)
		{
			// is this a duplicate connection reqeust?
			if (ret == 0 && net_time - s->connecttime < 2.0)
			{
				// yes, so send a duplicate reply
				SZ_Clear(&net_message);
				// save space for the header, filled in later
				MSG_WriteLong(&net_message, 0);
				MSG_WriteByte(&net_message, CCREP_ACCEPT);
				dfunc.GetSocketAddr(s->socket, &newaddr);
				MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
				*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
				dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
				SZ_Clear(&net_message);
				return NULL;
			}
			// it's somebody coming back in from a crash/disconnect
			// so close the old qsocket and let their retry get them back in
			NET_Close(s);
			return NULL;
		}
	}

	// allocate a QSocket
	sock = NET_NewQSocket ();
	if (sock == NULL)
	{
		// no room; try to let him know
		SZ_Clear(&net_message);
		// save space for the header, filled in later
		MSG_WriteLong(&net_message, 0);
		MSG_WriteByte(&net_message, CCREP_REJECT);
		MSG_WriteString(&net_message, "Server is full.\n");
		*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
		dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
		SZ_Clear(&net_message);
		return NULL;
	}

	// allocate a network socket
	newsock = dfunc.OpenSocket(0);
	if (newsock == -1)
	{
		NET_FreeQSocket(sock);
		return NULL;
	}

	// connect to the client
	if (dfunc.Connect (newsock, &clientaddr) == -1)
	{
		dfunc.CloseSocket(newsock);
		NET_FreeQSocket(sock);
		return NULL;
	}

	// everything is allocated, just fill in the details	
	sock->socket = newsock;
	sock->landriver = net_landriverlevel;
	sock->addr = clientaddr;
	Q_strcpy(sock->address, dfunc.AddrToString(&clientaddr));

	// send him back the info about the server connection he has been allocated
	SZ_Clear(&net_message);
	// save space for the header, filled in later
	MSG_WriteLong(&net_message, 0);
	MSG_WriteByte(&net_message, CCREP_ACCEPT);
	dfunc.GetSocketAddr(newsock, &newaddr);
	MSG_WriteLong(&net_message, dfunc.GetSocketPort(&newaddr));
//	MSG_WriteString(&net_message, dfunc.AddrToString(&newaddr));
	*((int *)net_message.data) = BigLong(NETFLAG_CTL | (net_message.cursize & NETFLAG_LENGTH_MASK));
	dfunc.Write (acceptsock, net_message.data, net_message.cursize, &clientaddr);
	SZ_Clear(&net_message);

	return sock;
}
//-----------------------------------------------------------------------------
// Purpose: 
//-----------------------------------------------------------------------------
void CTFWinPanel::FireGameEvent( IGameEvent * event )
{
	const char *pEventName = event->GetName();

	if ( Q_strcmp( "teamplay_round_start", pEventName ) == 0 )
	{
		m_bShouldBeVisible = false;
	}
	else if ( Q_strcmp( "teamplay_game_over", pEventName ) == 0 )
	{
		m_bShouldBeVisible = false;
	}
	else if ( Q_strcmp( "tf_game_over", pEventName ) == 0 )
	{
		m_bShouldBeVisible = false;
	}
	else if ( Q_strcmp( "teamplay_win_panel", pEventName ) == 0 )
	{
		if ( !g_PR )
			return;

		int iWinningTeam = event->GetInt( "winning_team" );
		int iWinReason = event->GetInt( "winreason" );
		int iFlagCapLimit = event->GetInt( "flagcaplimit" );
		bool bRoundComplete = (bool) event->GetInt( "round_complete" );
		int iRoundsRemaining = event->GetInt( "rounds_remaining" );

		LoadControlSettings( "resource/UI/WinPanel.res" );		
		InvalidateLayout( false, true );

		SetDialogVariable( "WinningTeamLabel", "" );
		SetDialogVariable( "AdvancingTeamLabel", "" );
		SetDialogVariable( "WinReasonLabel", "" );
		SetDialogVariable( "DetailsLabel", "" );

		vgui::ImagePanel *pImagePanelBG = dynamic_cast<vgui::ImagePanel *>( FindChildByName("WinPanelBG") );
		Assert( pImagePanelBG );
		if ( !pImagePanelBG )
			return;

		// set the appropriate background image and label text
		const char *pTeamLabel = NULL;
		const char *pTopPlayersLabel = NULL;
		const wchar_t *pLocalizedTeamName = NULL;
		// this is an area defense, but not a round win, if this was a successful defend until time limit but not a complete round
		bool bIsAreaDefense = ( ( WINREASON_DEFEND_UNTIL_TIME_LIMIT == iWinReason ) && !bRoundComplete );
		switch ( iWinningTeam )
		{
		case TF_TEAM_BLUE:
			pImagePanelBG->SetImage( "../hud/winpanel_blue_bg_main.vmt" );
			pTeamLabel = ( bRoundComplete ? "#Winpanel_BlueWins" : ( bIsAreaDefense ? "#Winpanel_BlueDefends" : "#Winpanel_BlueAdvances" ) );
			pTopPlayersLabel = "#Winpanel_BlueMVPs";
			pLocalizedTeamName =  g_pVGuiLocalize->Find( "TF_BlueTeam_Name" );
			break;
		case TF_TEAM_RED:
			pImagePanelBG->SetImage( "../hud/winpanel_red_bg_main.vmt" );
			pTeamLabel = ( bRoundComplete ? "#Winpanel_RedWins" : ( bIsAreaDefense ? "#Winpanel_RedDefends" : "#Winpanel_RedAdvances" ) );
			pTopPlayersLabel = "#Winpanel_RedMVPs";
			pLocalizedTeamName =  g_pVGuiLocalize->Find( "TF_RedTeam_Name" );
			break;
		case TEAM_UNASSIGNED:	// stalemate
			pImagePanelBG->SetImage( "../hud/winpanel_black_bg_main.vmt" );
			pTeamLabel = "#Winpanel_Stalemate";
			pTopPlayersLabel = "#Winpanel_TopPlayers";
			break;
		default:
			Assert( false );
			break;
		}

		SetDialogVariable( bRoundComplete ? "WinningTeamLabel" : "AdvancingTeamLabel", g_pVGuiLocalize->Find( pTeamLabel ) );
		SetDialogVariable( "TopPlayersLabel", g_pVGuiLocalize->Find( pTopPlayersLabel ) );

		wchar_t wzWinReason[256]=L"";
		switch ( iWinReason )
		{
		case WINREASON_ALL_POINTS_CAPTURED:
			g_pVGuiLocalize->ConstructString( wzWinReason, sizeof( wzWinReason ), g_pVGuiLocalize->Find( "#Winreason_AllPointsCaptured" ), 1, pLocalizedTeamName );
			break;
		case WINREASON_FLAG_CAPTURE_LIMIT:
			{
				wchar_t wzFlagCaptureLimit[16];
				_snwprintf( wzFlagCaptureLimit, ARRAYSIZE( wzFlagCaptureLimit), L"%i", iFlagCapLimit );
				g_pVGuiLocalize->ConstructString( wzWinReason, sizeof( wzWinReason ), g_pVGuiLocalize->Find( "#Winreason_FlagCaptureLimit" ), 2, 
					pLocalizedTeamName, wzFlagCaptureLimit );
			}			
			break;
		case WINREASON_OPPONENTS_DEAD:
			g_pVGuiLocalize->ConstructString( wzWinReason, sizeof( wzWinReason ), g_pVGuiLocalize->Find( "#Winreason_OpponentsDead" ), 1, pLocalizedTeamName );
			break;
		case WINREASON_DEFEND_UNTIL_TIME_LIMIT:
			g_pVGuiLocalize->ConstructString( wzWinReason, sizeof( wzWinReason ), g_pVGuiLocalize->Find( "#Winreason_DefendedUntilTimeLimit" ), 1, pLocalizedTeamName );
			break;
		case WINREASON_STALEMATE:
			g_pVGuiLocalize->ConstructString( wzWinReason, sizeof( wzWinReason ), g_pVGuiLocalize->Find( "#Winreason_Stalemate" ), 0 );
			break;	
		default:
			Assert( false );
			break;
		}
		SetDialogVariable( "WinReasonLabel", wzWinReason );

		if ( !bRoundComplete && ( WINREASON_STALEMATE != iWinReason ) )
		{			
			// if this was a mini-round, show # of capture points remaining
			wchar_t wzNumCapturesRemaining[16];
			wchar_t wzCapturesRemainingMsg[256]=L"";
			_snwprintf( wzNumCapturesRemaining, ARRAYSIZE( wzNumCapturesRemaining ), L"%i", iRoundsRemaining );
			g_pVGuiLocalize->ConstructString( wzCapturesRemainingMsg, sizeof( wzCapturesRemainingMsg ), 
				g_pVGuiLocalize->Find( 1 == iRoundsRemaining ? "#Winpanel_CapturePointRemaining" : "Winpanel_CapturePointsRemaining" ),
				1, wzNumCapturesRemaining );
			SetDialogVariable( "DetailsLabel", wzCapturesRemainingMsg );
		}
		else if ( ( WINREASON_ALL_POINTS_CAPTURED == iWinReason ) || ( WINREASON_FLAG_CAPTURE_LIMIT == iWinReason ) )
		{
			// if this was a full round that ended with point capture or flag capture, show the winning cappers
			const char *pCappers = event->GetString( "cappers" );
			int iCappers = Q_strlen( pCappers );
			if ( iCappers > 0 )
			{	
				char szPlayerNames[256]="";
				wchar_t wzPlayerNames[256]=L"";
				wchar_t wzCapMsg[512]=L"";
				for ( int i = 0; i < iCappers; i++ )
				{
					Q_strncat( szPlayerNames, g_PR->GetPlayerName( (int) pCappers[i] ), ARRAYSIZE( szPlayerNames ) );
					if ( i < iCappers - 1 )
					{
						Q_strncat( szPlayerNames, ", ", ARRAYSIZE( szPlayerNames ) );
					}
				}
				g_pVGuiLocalize->ConvertANSIToUnicode( szPlayerNames, wzPlayerNames, sizeof( wzPlayerNames ) );
				g_pVGuiLocalize->ConstructString( wzCapMsg, sizeof( wzCapMsg ), g_pVGuiLocalize->Find( "#Winpanel_WinningCapture" ), 1, wzPlayerNames );
				SetDialogVariable( "DetailsLabel", wzCapMsg );
			}
		}

		// get the current & previous team scores
		int iBlueTeamPrevScore = event->GetInt( "blue_score_prev", 0 );
		int iRedTeamPrevScore = event->GetInt( "red_score_prev", 0 );
		m_iBlueTeamScore = event->GetInt( "blue_score", 0 );
		m_iRedTeamScore = event->GetInt( "red_score", 0 );
		
		if ( m_pTeamScorePanel )
		{			
			if ( bRoundComplete )
			{
				// set the previous team scores in scoreboard
				m_pTeamScorePanel->SetDialogVariable( "blueteamscore", iBlueTeamPrevScore );
				m_pTeamScorePanel->SetDialogVariable( "redteamscore", iRedTeamPrevScore );

				if ( ( m_iBlueTeamScore != iBlueTeamPrevScore ) || ( m_iRedTeamScore != iRedTeamPrevScore ) )
				{
					// if the new scores are different, set ourselves to update the scoreboard to the new values after a short delay, so players
					// see the scores tick up
					m_flTimeUpdateTeamScore = gpGlobals->curtime + 2.0f;
				}
			}
			// only show team scores if round is complete
			m_pTeamScorePanel->SetVisible( bRoundComplete );
		}

		C_TF_PlayerResource *tf_PR = dynamic_cast<C_TF_PlayerResource *>( g_PR );
		if ( !tf_PR )
			return;

		// look for the top 3 players sent in the event
		for ( int i = 1; i <= 3; i++ )
		{
			bool bShow = false;
			char szPlayerIndexVal[64]="", szPlayerScoreVal[64]="";
			// get player index and round points from the event
			Q_snprintf( szPlayerIndexVal, ARRAYSIZE( szPlayerIndexVal ), "player_%d", i );
			Q_snprintf( szPlayerScoreVal, ARRAYSIZE( szPlayerScoreVal ), "player_%d_points", i );
			int iPlayerIndex = event->GetInt( szPlayerIndexVal, 0 );
			int iRoundScore = event->GetInt( szPlayerScoreVal, 0 );
			// round score of 0 means no player to show for that position (not enough players, or didn't score any points that round)
			if ( iRoundScore > 0 )
				bShow = true;

#if !defined( _X360 )
			CAvatarImagePanel *pPlayerAvatar = dynamic_cast<CAvatarImagePanel *>( FindChildByName( CFmtStr( "Player%dAvatar", i ) ) );

			if ( pPlayerAvatar )
			{
				if ( bShow )
				{
					CBasePlayer *pPlayer = UTIL_PlayerByIndex( iPlayerIndex );
					pPlayerAvatar->SetPlayer( pPlayer );
				}

				pPlayerAvatar->SetVisible( bShow );
			}
#endif
			vgui::Label *pPlayerName = dynamic_cast<Label *>( FindChildByName( CFmtStr( "Player%dName", i ) ) );
			vgui::Label *pPlayerClass = dynamic_cast<Label *>( FindChildByName( CFmtStr( "Player%dClass", i ) ) );
			vgui::Label *pPlayerScore = dynamic_cast<Label *>( FindChildByName( CFmtStr( "Player%dScore", i ) ) );
			
			if ( !pPlayerName || !pPlayerClass || !pPlayerScore )
				return;

			if ( bShow )
			{
				// set the player labels to team color
				Color clr = g_PR->GetTeamColor( g_PR->GetTeam( iPlayerIndex ) );				
				pPlayerName->SetFgColor( clr );
				pPlayerClass->SetFgColor( clr );
				pPlayerScore->SetFgColor( clr );

				// set label contents
				pPlayerName->SetText( g_PR->GetPlayerName( iPlayerIndex ) );
				pPlayerClass->SetText( g_aPlayerClassNames[tf_PR->GetPlayerClass( iPlayerIndex )] );
				pPlayerScore->SetText( CFmtStr( "%d", iRoundScore ) );
			}

			// show or hide labels for this player position
			pPlayerName->SetVisible( bShow );
			pPlayerClass->SetVisible( bShow );
			pPlayerScore->SetVisible( bShow );
		}

		m_bShouldBeVisible = true;

		MoveToFront();
	}
}
void CASW_Voting_Missions::ScanThink()
{
	if (m_iListType == 0)		// if the player isn't looking at any particular list at the moment, don't bother updating our strings
	{
		SetThink( NULL );
		return;
	}

	if (!missionchooser || !missionchooser->LocalMissionSource())
		return;

	IASW_Mission_Chooser_Source* pMissionSource = missionchooser->LocalMissionSource();

	// let the source think, in case it needs to be scanning folders
	pMissionSource->Think();

	// player is looking at the list of missions
	if (m_iListType == 1)
	{
		if ( m_nCampaignIndex == -1 )
		{
			// make sure the source is setup to be looking at our page of missions (need to do this every time in case someone else is using the source too)
			pMissionSource->FindMissions(m_nOffset, m_iNumSlots, true);
			// copy them from the local source into our networked array
			ASW_Mission_Chooser_Mission* missions = pMissionSource->GetMissions();
			bool bChanged = false;
			for (int i=0;i<m_iNumSlots;i++)
			{
				if (i<ASW_SAVES_PER_PAGE && Q_strcmp(missions[i].m_szMissionName, STRING(m_iszMissionNames[i])))
				{
					bChanged = true;
					m_iszMissionNames.Set(i, AllocPooledString(missions[i].m_szMissionName));
					m_iszMissionNames.GetForModify(i);
				}
			}
			m_iNumMissions = pMissionSource->GetNumMissions(false);
			m_iNumOverviewMissions = pMissionSource->GetNumMissions(true);
		}
		else
		{
			// make sure the source is setup to be looking at our page of missions (need to do this every time in case someone else is using the source too)
			pMissionSource->FindMissionsInCampaign(m_nCampaignIndex, m_nOffset, m_iNumSlots);
			// copy them from the local source into our networked array
			ASW_Mission_Chooser_Mission* missions = pMissionSource->GetMissions();
			bool bChanged = false;
			for (int i=0;i<m_iNumSlots;i++)
			{
				if (i<ASW_SAVES_PER_PAGE && Q_strcmp(missions[i].m_szMissionName, STRING(m_iszMissionNames[i])))
				{
					bChanged = true;
					m_iszMissionNames.Set(i, AllocPooledString(missions[i].m_szMissionName));
					m_iszMissionNames.GetForModify(i);
				}
			}
			m_iNumMissions = pMissionSource->GetNumMissionsInCampaign( m_nCampaignIndex );
			m_iNumOverviewMissions = m_iNumMissions;
		}
	}
	else if (m_iListType == 2)	// player is looking at a list of campaigns
	{
		// make sure the source is setup to be looking at our page of campaign (need to do this every time in case someone else is using the source too)
		pMissionSource->FindCampaigns(m_nOffset, m_iNumSlots);
		// copy them from the local source into our networked array
		ASW_Mission_Chooser_Mission* campaigns = pMissionSource->GetCampaigns();
		for (int i=0;i<m_iNumSlots;i++)
		{
			if (i<ASW_CAMPAIGNS_PER_PAGE && Q_strcmp(campaigns[i].m_szMissionName, STRING(m_iszCampaignNames[i])))
			{
				m_iszCampaignNames.Set(i, AllocPooledString(campaigns[i].m_szMissionName));
			}
		}
		m_iNumCampaigns = pMissionSource->GetNumCampaigns();
	}
	else if (m_iListType == 3)	// player is looking at a list of saved campaign games
	{
		// make sure the source is setup to be looking at our page of saves (need to do this every time in case someone else is using the source too)
		bool bMulti = !( ASWGameResource() && ASWGameResource()->IsOfflineGame() );
		pMissionSource->FindSavedCampaigns(m_nOffset, m_iNumSlots, bMulti, (m_hPlayer.Get() && bMulti) ? m_hPlayer->GetASWNetworkID() : NULL);
		m_iNumSavedCampaigns = pMissionSource->GetNumSavedCampaigns(bMulti, (m_hPlayer.Get() && bMulti) ? m_hPlayer->GetASWNetworkID() : NULL);
		// copy them from the local source into our networked array
		ASW_Mission_Chooser_Saved_Campaign* saved = pMissionSource->GetSavedCampaigns();
		for (int i=0;i<m_iNumSlots;i++)
		{
			if (i<ASW_SAVES_PER_PAGE && Q_strcmp(saved[i].m_szSaveName, STRING(m_iszSaveNames[i])))
			{
				m_iszSaveNames.Set(i, AllocPooledString(saved[i].m_szSaveName));
				m_iszSaveCampaignNames.Set(i, AllocPooledString(saved[i].m_szCampaignName));
				m_iszSaveDateTimes.Set(i, AllocPooledString(saved[i].m_szDateTime));
				m_iszSavePlayerNames.Set(i, AllocPooledString(saved[i].m_szPlayerNames));
				m_iSaveMissionsComplete.Set(i, saved[i].m_iMissionsComplete);
			}
		}
	}
	
	SetThink( &CASW_Voting_Missions::ScanThink );
	SetNextThink(gpGlobals->curtime + 0.1f);
}
Exemple #24
0
void CTFHLTVDirector::CreateShotFromEvent( CHLTVGameEvent *event )
{
    // show event at least for 2 more seconds after it occured
    const char *name = event->m_Event->GetName();

    int thera = RandomFloat()>0.5?20:-20;

    if ( !Q_strcmp( "teamplay_point_startcapture", name ) ||
            !Q_strcmp( "teamplay_point_captured", name ) ||
            !Q_strcmp( "teamplay_capture_blocked", name ) )
    {
        CBaseEntity *pCapturePoint = GetCapturePointByIndex( event->m_Event->GetInt( "cp" ) );

        int iCameraIndex = -1;
        float flClosest = 99999.9f;

        if ( pCapturePoint )
        {
            // Does it have an associated viewpoint?
            for ( int i = 0; i<m_nNumFixedCameras; i++ )
            {
                CBaseEntity *pCamera = m_pFixedCameras[ i ];

                if ( pCamera )
                {
                    byte pvs[MAX_MAP_CLUSTERS/8];
                    int clusterIndex = engine->GetClusterForOrigin( pCamera->GetAbsOrigin() );
                    engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs );
                    bool bCameraInPVS = engine->CheckOriginInPVS( pCapturePoint->GetAbsOrigin(), pvs, sizeof( pvs ) );

                    if ( bCameraInPVS == true )
                    {
                        float flDistance = (pCapturePoint->GetAbsOrigin() - pCamera->GetAbsOrigin()).Length();
                        if ( flDistance <= flClosest )
                        {
                            iCameraIndex = i;
                            flClosest = flDistance;
                        }
                    }
                }
            }
        }

        CBasePlayer *pPlayer = NULL;

        if ( !Q_strcmp( "teamplay_point_captured", name ) )
        {
            const char *pszCappers = event->m_Event->GetString("cappers");
            int nLength = Q_strlen(pszCappers);

            if ( nLength > 0 )
            {
                int iRandomCapper = pszCappers[ RandomInt(0,nLength-1) ];
                pPlayer = UTIL_PlayerByIndex( iRandomCapper );
            }
        }
        else if ( !Q_strcmp( "teamplay_capture_blocked", name ) )
        {
            int iBlocker = event->m_Event->GetInt("blocker");
            pPlayer = UTIL_PlayerByIndex( iBlocker );
        }

        if ( pPlayer )
        {
            if ( iCameraIndex >= 0 && RandomFloat() > 0.66f )
            {
                StartFixedCameraShot( iCameraIndex, pPlayer->entindex() );
            }
            else if ( pCapturePoint )
            {
                StartChaseCameraShot( pPlayer->entindex(), pCapturePoint->entindex(), 96, 20, thera, false );
            }
            else
            {
                StartChaseCameraShot( pPlayer->entindex(), 0, 96, 20, 0, false );
            }
        }
        else if ( iCameraIndex >= 0 && pCapturePoint )
        {
            // no player known for this event
            StartFixedCameraShot( iCameraIndex, pCapturePoint->entindex() );
        }

        // shot 2 seconds after event
        m_nNextShotTick = min( m_nNextShotTick, (event->m_Tick+TIME_TO_TICKS(1.0)) );
    }
    else if ( !Q_strcmp( "object_destroyed", name ) )
    {
        CBasePlayer *attacker = UTIL_PlayerByUserId( event->m_Event->GetInt("attacker") );
        if ( attacker )
        {
            int iObjectIndex = event->m_Event->GetInt("index");
            StartChaseCameraShot( attacker->entindex(), iObjectIndex, 96, 20, thera, false );
        }
    }
    else if ( !Q_strcmp( "ctf_flag_captured", name ) )
    {
        CBasePlayer *capper = UTIL_PlayerByUserId( event->m_Event->GetInt("capper") );
        if ( capper )
        {
            StartChaseCameraShot( capper->entindex(), 0, 96, 20, 0, false );
        }
    }
    else if ( !Q_strcmp( "teamplay_flag_event", name ) )
    {
        StartChaseCameraShot( event->m_Event->GetInt("player"), 0, 96, 20, 0, false );
    }
    else
    {

        // let baseclass create a shot
        BaseClass::CreateShotFromEvent( event );
    }
}
Exemple #25
0
int WIPX_Init (void)
{
	int		i;
	char	buff[MAXHOSTNAMELEN];
	struct qsockaddr addr;
	char	*p;
	int		r;
	WORD	wVersionRequested; 

	if (COM_CheckParm ("-noipx"))
		return -1;

// make sure LoadLibrary has happened successfully
	if (!winsock_lib_initialized)
		return -1;

	if (winsock_initialized == 0)
	{
		wVersionRequested = MAKEWORD(1, 1); 

		r = pWSAStartup (MAKEWORD(1, 1), &winsockdata);

		if (r)
		{
			Con_Printf ("Winsock initialization failed.\n");
			return -1;
		}
	}
	winsock_initialized++;

	for (i = 0; i < IPXSOCKETS; i++)
		ipxsocket[i] = 0;

	// determine my name & address
	if (pgethostname(buff, MAXHOSTNAMELEN) == 0)
	{
		// if the quake hostname isn't set, set it to the machine name
		if (Q_strcmp(hostname.string, "UNNAMED") == 0)
		{
			// see if it's a text IP address (well, close enough)
			for (p = buff; *p; p++)
				if ((*p < '0' || *p > '9') && *p != '.')
					break;

			// if it is a real name, strip off the domain; we only want the host
			if (*p)
			{
				for (i = 0; i < 15; i++)
					if (buff[i] == '.')
						break;
				buff[i] = 0;
			}
			Cvar_Set ("hostname", buff);
		}
	}

	if ((net_controlsocket = WIPX_OpenSocket (0)) == -1)
	{
		Con_Printf("WIPX_Init: Unable to open control socket\n");
		if (--winsock_initialized == 0)
			pWSACleanup ();
		return -1;
	}

	((struct sockaddr_ipx *)&broadcastaddr)->sa_family = AF_IPX;
	memset(((struct sockaddr_ipx *)&broadcastaddr)->sa_netnum, 0, 4);
	memset(((struct sockaddr_ipx *)&broadcastaddr)->sa_nodenum, 0xff, 6);
	((struct sockaddr_ipx *)&broadcastaddr)->sa_socket = htons((unsigned short)net_hostport);

	WIPX_GetSocketAddr (net_controlsocket, &addr);
	Q_strcpy(my_ipx_address,  WIPX_AddrToString (&addr));
	p = Q_strrchr (my_ipx_address, ':');
	if (p)
		*p = 0;

	Con_Printf("Winsock IPX Initialized\n");
	ipxAvailable = true;

	return net_controlsocket;
}
Exemple #26
0
//-----------------------------------------------------------------------------
// Purpose: determine the class name of the weapon that got a kill
//-----------------------------------------------------------------------------
const char *CSDKGameRules::GetKillingWeaponName( const CTakeDamageInfo &info, CSDKPlayer *pVictim, int *iWeaponID )
{
	CBaseEntity *pInflictor = info.GetInflictor();
	CBaseEntity *pKiller = info.GetAttacker();
	CBasePlayer *pScorer = SDKGameRules()->GetDeathScorer( pKiller, pInflictor, pVictim );

	const char *killer_weapon_name = "world";
	*iWeaponID = SDK_WEAPON_NONE;

	if ( pScorer && pInflictor && ( pInflictor == pScorer ) )
	{
		// If the inflictor is the killer,  then it must be their current weapon doing the damage
		if ( pScorer->GetActiveWeapon() )
		{
			killer_weapon_name = pScorer->GetActiveWeapon()->GetClassname(); 
			if ( pScorer->IsPlayer() )
			{
				*iWeaponID = ToSDKPlayer(pScorer)->GetActiveSDKWeapon()->GetWeaponID();
			}
		}
	}
	else if ( pInflictor )
	{
		killer_weapon_name = STRING( pInflictor->m_iClassname );

		CWeaponSDKBase *pWeapon = dynamic_cast< CWeaponSDKBase * >( pInflictor );
		if ( pWeapon )
		{
			*iWeaponID = pWeapon->GetWeaponID();
		}
		else
		{
			CBaseGrenadeProjectile *pBaseGrenade = dynamic_cast<CBaseGrenadeProjectile*>( pInflictor );
			if ( pBaseGrenade )
			{
				*iWeaponID = pBaseGrenade->GetWeaponID();
			}
		}
	}

	// strip certain prefixes from inflictor's classname
	const char *prefix[] = { "weapon_", "NPC_", "func_" };
	for ( int i = 0; i< ARRAYSIZE( prefix ); i++ )
	{
		// if prefix matches, advance the string pointer past the prefix
		int len = Q_strlen( prefix[i] );
		if ( strncmp( killer_weapon_name, prefix[i], len ) == 0 )
		{
			killer_weapon_name += len;
			break;
		}
	}

	// grenade projectiles need to be translated to 'grenade' 
	if ( 0 == Q_strcmp( killer_weapon_name, "grenade_projectile" ) )
	{
		killer_weapon_name = "grenade";
	}

	return killer_weapon_name;
}
Exemple #27
0
/* <4c63> ../engine/cmd.c:521 */
void Cmd_Alias_f(void)
{
	cmdalias_t *a;
	const char *s;
	char cmd[MAX_CMD_LINE];
	int i, c;

	if (Cmd_Argc() == 1)
	{
		// Output all aliases
		Con_Printf("Current alias commands:\n");

		for (a = cmd_alias; a; a = a->next)
		{
			Con_Printf("%s : %s", a->name, a->value);	// Don't need \n here, because each alias value is appended with it
		}

		return;
	}

	s = Cmd_Argv(1);

	if (Q_strlen(s) >= MAX_ALIAS_NAME)
	{
		Con_Printf("Alias name is too long\n");
		return;
	}

	if (Cvar_FindVar(s))
	{
		Con_Printf("Alias name is invalid\n");
		return;
	}

	SetCStrikeFlags();	// TODO: Do this once somewhere at the server start

	if ((g_bIsCStrike || g_bIsCZero) &&
		(!Q_stricmp(s, "cl_autobuy")
		|| !Q_stricmp(s, "cl_rebuy")
		|| !Q_stricmp(s, "gl_ztrick")
		|| !Q_stricmp(s, "gl_ztrick_old")
		|| !Q_stricmp(s, "gl_d3dflip")))
	{
		Con_Printf("Alias name is invalid\n");
		return;
	}

	// Say hello to my little friend! (c)
	if (g_bIsTFC && (!Q_stricmp(s, "_special") || !Q_stricmp(s, "special")))
	{
		Con_Printf("Alias name is invalid\n");
		return;
	}

	// Gather arguments into one string
	cmd[0] = 0;
	c = Cmd_Argc();
	for (i = 2; i <= c; i++)
	{
		Q_strncat(cmd, Cmd_Argv(i), MAX_CMD_LINE - 2 - Q_strlen(cmd));	// always have a space for \n or ' ' and \0

		if (i != c)
		{
			Q_strcat(cmd, " ");
		}
	}
	Q_strcat(cmd, "\n");

	// Search for existing alias
	for (a = cmd_alias; a; a = a->next)
	{
		if (!Q_stricmp(a->name, s))
		{
			if (!Q_strcmp(a->value, cmd))
			{
				// Same value on the alias, return
				return;
			}
			// Release value, will realloc
			Z_Free(a->value);
			break;
		}
	}

	if (!a)
	{
		// Alloc new alias
		a = (cmdalias_t *)Z_Malloc(sizeof(cmdalias_t));
		a->next = cmd_alias;
		cmd_alias = a;

		Q_strncpy(a->name, s, ARRAYSIZE(a->name) - 1);
		a->name[ARRAYSIZE(a->name) - 1] = 0;
	}

	a->value = CopyString(cmd);
}
Exemple #28
0
// This message handler may be better off elsewhere
int CHudDeathNotice :: MsgFunc_DeathMsg( const char *pszName, int iSize, void *pbuf )
{
	m_iFlags |= HUD_ACTIVE;

	BEGIN_READ( pszName, pbuf, iSize );

	int killer = READ_BYTE();
	int victim = READ_BYTE();
	int i = 0;

	char killedwith[32];

	Q_strcpy( killedwith, "d_" );
	Q_strncat( killedwith, READ_STRING(), 32 );

	gHUD.m_Scoreboard.DeathMsg( killer, victim );

	for( i = 0; i < MAX_DEATHNOTICES; i++ )
	{
		if( rgDeathNoticeList[i].iId == 0 )
			break;
	}

	if( i == MAX_DEATHNOTICES )
	{
		// move the rest of the list forward to make room for this item
		memmove( rgDeathNoticeList, rgDeathNoticeList + 1, sizeof( DeathNoticeItem ) * MAX_DEATHNOTICES );
		i = MAX_DEATHNOTICES - 1;
	}

	gHUD.m_Scoreboard.GetAllPlayersInfo();

	// Get the Killer's name
	char *killer_name = g_PlayerInfoList[killer].name;

	if( !killer_name )
	{
		killer_name = "";
		rgDeathNoticeList[i].szKiller[0] = 0;
	}
	else
	{
		rgDeathNoticeList[i].KillerColor = GetClientColor( killer );
		Q_strncpy( rgDeathNoticeList[i].szKiller, killer_name, MAX_PLAYER_NAME_LENGTH );
		rgDeathNoticeList[i].szKiller[MAX_PLAYER_NAME_LENGTH-1] = 0;
	}

	// Get the Victim's name
	char *victim_name = NULL;

	// If victim is -1, the killer killed a specific, non-player object (like a sentrygun)
	if((( char )victim) != -1 )
		victim_name = g_PlayerInfoList[victim].name;

	if( !victim_name )
	{
		victim_name = "";
		rgDeathNoticeList[i].szVictim[0] = 0;
	}
	else
	{
		rgDeathNoticeList[i].VictimColor = GetClientColor( victim );
		Q_strncpy( rgDeathNoticeList[i].szVictim, victim_name, MAX_PLAYER_NAME_LENGTH );
		rgDeathNoticeList[i].szVictim[MAX_PLAYER_NAME_LENGTH-1] = 0;
	}

	// Is it a non-player object kill?
	if( ((char)victim) == -1 )
	{
		rgDeathNoticeList[i].iNonPlayerKill = TRUE;

		// Store the object's name in the Victim slot (skip the d_ bit)
		Q_strcpy( rgDeathNoticeList[i].szVictim, killedwith+2 );
	}
	else
	{
		if( killer == victim || killer == 0 )
			rgDeathNoticeList[i].iSuicide = TRUE;

		if( !Q_strcmp( killedwith, "d_teammate" ))
			rgDeathNoticeList[i].iTeamKill = TRUE;
	}

	// Find the sprite in the list
	int spr = gHUD.GetSpriteIndex( killedwith );

	rgDeathNoticeList[i].iId = spr;

	DEATHNOTICE_DISPLAY_TIME = CVAR_GET_FLOAT( "hud_deathnotice_time" );
	rgDeathNoticeList[i].flDisplayTime = gHUD.m_flTime + DEATHNOTICE_DISPLAY_TIME;

	if( rgDeathNoticeList[i].iNonPlayerKill )
	{
		ConsolePrint( rgDeathNoticeList[i].szKiller );
		ConsolePrint( " killed a " );
		ConsolePrint( rgDeathNoticeList[i].szVictim );
		ConsolePrint( "\n" );
	}
	else
	{
		// record the death notice in the console
		if( rgDeathNoticeList[i].iSuicide )
		{
			ConsolePrint( rgDeathNoticeList[i].szVictim );

			if( !Q_strcmp( killedwith, "d_world" ))
			{
				ConsolePrint( " died" );
			}
			else
			{
				ConsolePrint( " killed self" );
			}
		}
		else if( rgDeathNoticeList[i].iTeamKill )
		{
			ConsolePrint( rgDeathNoticeList[i].szKiller );
			ConsolePrint( " killed his teammate " );
			ConsolePrint( rgDeathNoticeList[i].szVictim );
		}
		else
		{
			ConsolePrint( rgDeathNoticeList[i].szKiller );
			ConsolePrint( " killed " );
			ConsolePrint( rgDeathNoticeList[i].szVictim );
		}

		if( *killedwith && (*killedwith > 13 ) && Q_strcmp( killedwith, "d_world" ) && !rgDeathNoticeList[i].iTeamKill )
		{
			ConsolePrint( " with " );

			// replace the code names with the 'real' names
			if( !Q_strcmp( killedwith+2, "egon" ))
				Q_strcpy( killedwith, "d_gluon gun" );
			if( !Q_strcmp( killedwith+2, "gauss" ))
				Q_strcpy( killedwith, "d_tau cannon" );

			ConsolePrint( killedwith+2 ); // skip over the "d_" part
		}
		ConsolePrint( "\n" );
	}

	END_READ();

	return 1;
}
Exemple #29
0
void Joy_AdvancedUpdate_f (void)
{

	// called once by IN_ReadJoystick and by user whenever an update is needed
	// cvars are now available
	int	i;
	DWORD dwTemp;

	// initialize all the maps
	for (i = 0; i < JOY_MAX_AXES; i++)
	{
		dwAxisMap[i] = AxisNada;
		dwControlMap[i] = JOY_ABSOLUTE_AXIS;
		pdwRawValue[i] = RawValuePointer(i);
	}

	if( joy_advanced.value == 0.0)
	{
		// default joystick initialization
		// 2 axes only with joystick control
		dwAxisMap[JOY_AXIS_X] = AxisTurn;
		// dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS;
		dwAxisMap[JOY_AXIS_Y] = AxisForward;
		// dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS;
	}
	else
	{
		if (Q_strcmp (joy_name.string, "joystick") != 0)
		{
			// notify user of advanced controller
			Con_Printf ("\n%s configured\n\n", joy_name.string);
		}

		// advanced initialization here
		// data supplied by user via joy_axisn cvars
		dwTemp = (DWORD) joy_advaxisx.value;
		dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS;
		dwTemp = (DWORD) joy_advaxisy.value;
		dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS;
		dwTemp = (DWORD) joy_advaxisz.value;
		dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS;
		dwTemp = (DWORD) joy_advaxisr.value;
		dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS;
		dwTemp = (DWORD) joy_advaxisu.value;
		dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS;
		dwTemp = (DWORD) joy_advaxisv.value;
		dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f;
		dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS;
	}

	// compute the axes to collect from DirectInput
	joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV;
	for (i = 0; i < JOY_MAX_AXES; i++)
	{
		if (dwAxisMap[i] != AxisNada)
		{
			joy_flags |= dwAxisFlags[i];
		}
	}
}
Exemple #30
0
/*
==============
CL_ParseUserMessage

handles all user messages
==============
*/
void CL_ParseUserMessage( sizebuf_t *msg, int svc_num )
{
	int	i, iSize;
	byte	pbuf[256]; // message can't be larger than 255 bytes

	// NOTE: any user message parse on engine, not in client.dll
	if( svc_num < svc_lastmsg || svc_num >= ( MAX_USER_MESSAGES + svc_lastmsg ))
	{
		// out or range
		MsgDev( D_ERROR, "CL_ParseUserMessage: illegible server message %d (out or range)\n", svc_num );
		return;
	}

	for( i = 0; i < MAX_USER_MESSAGES; i++ )
	{
		// search for user message
		if( clgame.msg[i].number == svc_num )
			break;
	}

	if( i == MAX_USER_MESSAGES ) // probably unregistered
	{
		MsgDev( D_ERROR, "CL_ParseUserMessage: illegible server message %d (probably unregistered)\n", svc_num );
		return;
	}

	// NOTE: some user messages handled into engine
	if( !Q_strcmp( clgame.msg[i].name, "ScreenShake" ))
	{
		CL_ParseScreenShake( msg );
		return;
	}
	else if( !Q_strcmp( clgame.msg[i].name, "ScreenFade" ))
	{
		CL_ParseScreenFade( msg );
		return;
	}

	iSize = clgame.msg[i].size;

	// message with variable sizes receive an actual size as first byte
	if( iSize == -1 ) iSize = BF_ReadByte( msg );

	// parse user message into buffer
	BF_ReadBytes( msg, pbuf, iSize );

	if( clgame.msg[i].func )
	{
		clgame.msg[i].func( clgame.msg[i].name, iSize, pbuf );

		// HACKHACK: run final credits for Half-Life
		// because hl1 doesn't have call END_SECTION
		if( !Q_stricmp( clgame.msg[i].name, "HudText" ) && !Q_stricmp( GI->gamefolder, "valve" ))
		{
			// it's a end, so we should run credits
			if( !Q_strcmp( (char *)pbuf, "END3" ))
				Host_Credits();
		}
	}
	else
	{
		MsgDev( D_ERROR, "CL_ParseUserMessage: %s not hooked\n", clgame.msg[i].name );
		clgame.msg[i].func = CL_UserMsgStub; // throw warning only once
	}
}