Exemple #1
0
//-----------------------------------------------------------------------------
// Make a temporary filename
//-----------------------------------------------------------------------------
char *CScriptLib::MakeTemporaryFilename( char const *pchModPath, char *pPath, int pathSize )
{
	char *pBuffer = _tempnam( pchModPath, "mgd_" );
	if ( pBuffer[0] == '\\' )
	{
		pBuffer++;
	}
	if ( pBuffer[strlen( pBuffer )-1] == '.' )
	{
		pBuffer[strlen( pBuffer )-1] = '\0';
	}
	V_snprintf( pPath, pathSize, "%s.tmp", pBuffer );

	free( pBuffer );

	return pPath;
}
Exemple #2
0
    bool SaveItem(specialitemload_t const &item)
    {
        unsigned long long profileid = item.steamid.ConvertToUint64();

        item.itemmutex->Lock();
        unsigned int index = item.itemlist->Find(profileid);
        if(item.itemlist->IsValidIndex(index))
        {
            char query[1024];
            char petname[512];

            CUtlVector<CSpecialItem *> *items = item.itemlist->Element(index);
            item.itemmutex->Unlock();

            //Msg("[ITEMDBG] Saving/deleting old item list.\n");
            for(int i = 0; i < items->Count(); i++)
            {
                //Msg("[ITEMDBG]  - Saving/deleting item %i\n", i);
                item.itemmutex->Lock();
                CSpecialItem *olditem = items->Element(i);

                m_SQL->EscapeString(petname, olditem->m_szPetName, strlen(olditem->m_szPetName));
                
                V_snprintf(query, sizeof(query), "UPDATE `specialitems` SET `petname` = '%s', `equipped` = %i WHERE `id` = %i LIMIT 1", petname, olditem->m_bEquipped, olditem->m_iIndex);
                item.itemmutex->Unlock();
                //Msg("[ITEMDBG] %s\n", query);
                m_SQL->Query(query);
                
                delete olditem->m_pItem;
                delete olditem;
            }

            item.itemmutex->Lock();
            item.itemlist->RemoveAt(index);
            item.itemmutex->Unlock();
            delete items;
        }
        else
        {
            item.itemmutex->Unlock();
        }

        return true;
    }
//-----------------------------------------------------------------------------
//	BugDlg_UploadBugSubmission
//
//	Expects fully qualified source paths
//-----------------------------------------------------------------------------
bool BugDlg_UploadBugSubmission( int bugID, char const *pSavefile, char const *pScreenshot, char const *pBspFile, char const *pVmfFile )
{
	char	szFilename[MAX_PATH];
	char	szLocalfile[MAX_PATH];
	char	szRemotefile[MAX_PATH];
	bool	bSuccess = true;

	if ( pSavefile && pSavefile[0] )
	{
		V_snprintf( szLocalfile, sizeof( szLocalfile ), "%s", pSavefile );
		Sys_StripPath( pSavefile, szFilename, sizeof( szFilename ) );
		V_snprintf( szRemotefile, sizeof( szRemotefile ), "%s/%s", GetSubmissionURL( bugID ), szFilename );
		Sys_NormalizePath( szLocalfile, false );
		Sys_NormalizePath( szRemotefile, false );

		if ( !BugDlg_UploadFile( szLocalfile, szRemotefile, false ) )
		{
			bSuccess = false;
		}
	}

	if ( pScreenshot && pScreenshot[0] )
	{
		V_snprintf( szLocalfile, sizeof( szLocalfile ), "%s", pScreenshot );
		Sys_StripPath( pScreenshot, szFilename, sizeof( szFilename ) );
		V_snprintf( szRemotefile, sizeof( szRemotefile ), "%s/%s", GetSubmissionURL( bugID ), szFilename );
		Sys_NormalizePath( szLocalfile, false );
		Sys_NormalizePath( szRemotefile, false );
		
		if ( !BugDlg_UploadFile( szLocalfile, szRemotefile, true ) )
		{
			bSuccess = false;
		}
	}

	if ( pBspFile && pBspFile[0] )
	{
		V_snprintf( szLocalfile, sizeof( szLocalfile ), "%s", pBspFile );
		Sys_StripPath( pBspFile, szFilename, sizeof( szFilename ) );
		V_snprintf( szRemotefile, sizeof( szRemotefile ), "%s/%s", GetSubmissionURL( bugID ), szFilename );
		Sys_NormalizePath( szLocalfile, false );
		Sys_NormalizePath( szRemotefile, false );
		
		if ( !BugDlg_UploadFile( szLocalfile, szRemotefile, true ) )
		{
			bSuccess = false;
		}
	}

	return bSuccess;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
boost::python::object PyFS_ReadFile( const char *filepath, const char *pathid, bool optimalalloc, int maxbytes, int startingbyte, bool textmode )
{
	if( !filepath )
	{
		PyErr_SetString(PyExc_IOError, "No filepath specified" );
		throw boost::python::error_already_set(); 
	}
	if( !SrcPyPathIsInGameFolder( filepath ) )
	{
		PyErr_SetString(PyExc_IOError, "filesystem module only allows paths in the game folder" );
		throw boost::python::error_already_set(); 
	}
	if( !filesystem->FileExists( filepath, pathid ) )
	{
		PyErr_SetString(PyExc_IOError, "File does not exists" );
		throw boost::python::error_already_set(); 
	}

	int iExpectedSize = maxbytes == 0 ? filesystem->Size( filepath, pathid ) : maxbytes - 1;
	void *buffer = NULL;
	int len = filesystem->ReadFileEx( filepath, pathid, &buffer, true, optimalalloc, maxbytes, startingbyte );
	if( len != iExpectedSize )
	{
		char buf[256];
		V_snprintf( buf, sizeof( buf ), "Failed to read file. Expected file size %d, got %d instead", iExpectedSize, len );
		PyErr_SetString( PyExc_IOError, buf );
		throw boost::python::error_already_set(); 
	}

	boost::python::object content( boost::python::handle<>( PyBytes_FromStringAndSize( (const char *)buffer, (Py_ssize_t)len ) ) );
	if( textmode )
		content = content.attr("decode")("utf-8"); // TODO: improve. Look at how Python "wt" mode handles text

	if( optimalalloc )
		filesystem->FreeOptimalReadBuffer( buffer );
	else
		free( buffer );
	buffer = NULL;
	return content;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
boost::python::list PyFS_ListDir( const char *pPath, const char *pPathID, const char *pWildCard )
{
	if( !pPath || !pWildCard )
		return boost::python::list();

	const char *pFileName;
	char wildcard[MAX_PATH];
	FileFindHandle_t fh;
	boost::python::list result;

	// TODO: Do we need to add a slash in case there is no slash?
	V_snprintf(wildcard, MAX_PATH, "%s%s", pPath, pWildCard);

	pFileName = filesystem->FindFirstEx( wildcard, pPathID, &fh );
	while( pFileName )
	{
		result.append( boost::python::object( pFileName ) );
		pFileName = filesystem->FindNext( fh );
	}
	filesystem->FindClose( fh );
	return result;
}
Exemple #6
0
void CEventLog::FormatPlayer( CBaseEntity *ent, char *str, int len ) const
{
	if ( !str || len <= 0 )
	{
		return;
	}

	CBasePlayer *player = ToBasePlayer( ent );

	const char *playerName = "Unknown";
	int userID = 0;
	const char *networkIDString = "";
	const char *teamName = "";
	int areaID = 0;
	if ( player )
	{
		playerName = player->GetPlayerName();
		userID = player->GetUserID();
		networkIDString = player->GetNetworkIDString();
		CTeam *team = player->GetTeam();
		if ( team )
		{
			teamName = team->GetName();
		}
	}

#ifdef USE_NAV_MESH
	if ( ent && ent->MyCombatCharacterPointer() )
	{
		CNavArea *area = ent->MyCombatCharacterPointer()->GetLastKnownArea();
		if ( area )
		{
			areaID = area->GetID();
		}
	}
#endif // USE_NAV_MESH

	V_snprintf( str, len, "\"%s<%i><%s><%s><Area %d>\"", playerName, userID, networkIDString, teamName, areaID );
}
Exemple #7
0
void CASW_Briefing::SelectMarine( int nOrder, int nProfileIndex, int nPreferredLobbySlot )
{
	// for now, just select him
	C_ASW_Player *pPlayer = C_ASW_Player::GetLocalASWPlayer();
	if ( !pPlayer )
		return;

	if ( IsOfflineGame() )
	{
		pPlayer->RosterSelectMarineForSlot( nProfileIndex, nPreferredLobbySlot );
	}
	else
	{
		pPlayer->RosterSelectSingleMarine( nProfileIndex );
	}

	if ( gpGlobals->curtime - m_flLastSelectionChatterTime < 1.0f )
		return;

	CASW_Marine_Profile *pProfile = Briefing()->GetMarineProfileByProfileIndex( nProfileIndex );
	if ( pProfile )
	{
		char szSelectionSound[ CHATTER_STRING_SIZE ];
		V_snprintf( szSelectionSound, sizeof( szSelectionSound ), "%s%d", pProfile->m_Chatter[ CHATTER_SELECTION ], RandomInt( 0, pProfile->m_iChatterCount[ CHATTER_SELECTION ] - 1 ) );

		CSoundParameters params;
		if ( C_BaseEntity::GetParametersForSound( szSelectionSound, params, NULL ) )
		{
			EmitSound_t playparams( params );
			playparams.m_nChannel = CHAN_STATIC;
			playparams.m_bEmitCloseCaption = false;

			CLocalPlayerFilter filter;
			C_BaseEntity::EmitSound( filter, -1, playparams );

			m_flLastSelectionChatterTime = gpGlobals->curtime;
		}
	}
}
Exemple #8
0
//-----------------------------------------------------------------------------
// Purpose: Strip off the last directory from dirName
// Input  : *dirName - 
//			maxlen - 
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool V_StripLastDir( char *dirName, int maxlen )
{
	if( dirName[0] == 0 || 
		!V_stricmp( dirName, "./" ) || 
		!V_stricmp( dirName, ".\\" ) )
		return false;
	
	int len = V_strlen( dirName );

	Assert( len < maxlen );

	// skip trailing slash
	if ( PATHSEPARATOR( dirName[len-1] ) )
	{
		len--;
	}

	while ( len > 0 )
	{
		if ( PATHSEPARATOR( dirName[len-1] ) )
		{
			dirName[len] = 0;
			V_FixSlashes( dirName, CORRECT_PATH_SEPARATOR );
			return true;
		}
		len--;
	}

	// Allow it to return an empty string and true. This can happen if something like "tf2/" is passed in.
	// The correct behavior is to strip off the last directory ("tf2") and return true.
	if( len == 0 )
	{
		V_snprintf( dirName, maxlen, ".%c", CORRECT_PATH_SEPARATOR );
		return true;
	}

	return true;
}
void SendPatchCommandToUIs( DWORD dwInstallerProcessId )
{
	Msg( "SendPatchCommandToUIs\n ");
	
	CUtlVector<char> data;
	data.AddToTail( VMPI_SERVICE_UI_PROTOCOL_VERSION );
	data.AddToTail( VMPI_SERVICE_TO_UI_PATCHING );

	// This arg tells the UI whether to exit after running the command or not.
	data.AddToTail( 1 );
	
	// First argument is the working directory, which is the cache path in this case.
	data.AddMultipleToTail( V_strlen( g_FileCachePath ) + 1, g_FileCachePath );
	
	// Second argument is the command line.
	char waitAndRestartExe[MAX_PATH], serviceUIExe[MAX_PATH], commandLine[1024 * 8];
	V_ComposeFileName( g_FileCachePath, "WaitAndRestart.exe", waitAndRestartExe, sizeof( waitAndRestartExe ) );
	V_ComposeFileName( g_BaseAppPath, "vmpi_service_ui.exe", serviceUIExe, sizeof( serviceUIExe ) ); // We're running the UI from the same directory this exe is in.
	char strSeconds[64];
	V_snprintf( strSeconds, sizeof( strSeconds ), "*%lu", dwInstallerProcessId );

	// IMPORTANT to use BuildCommandLineFromArgs here because it'll handle slashes and quotes correctly.
	// If we don't do that, the command often won't work.
	CUtlVector<char*> args;
	args.AddToTail( waitAndRestartExe );
	args.AddToTail( strSeconds );
	args.AddToTail( g_BaseAppPath );
	args.AddToTail( serviceUIExe );
	BuildCommandLineFromArgs( args, commandLine, sizeof( commandLine ) );
	data.AddMultipleToTail( V_strlen( commandLine ) + 1, commandLine );
	
	if ( g_pConnMgr )
	{
		g_pConnMgr->SendPacket( -1, data.Base(), data.Count() );
		Sleep( 1000 );	// Make sure this packet goes out.
	}
}
	static HANDLE CreateTempFile( CUtlString &WritePath, CUtlString &FileName )
	{
		char tempFileName[MAX_PATH];
		if ( WritePath.IsEmpty() )
		{
			// use a safe name in the cwd
			char *pBuffer = tmpnam( NULL );
			if ( !pBuffer )
			{
				return INVALID_HANDLE_VALUE;
			}
			if ( pBuffer[0] == '\\' )
			{
				pBuffer++;
			}
			if ( pBuffer[strlen( pBuffer )-1] == '.' )
			{
				pBuffer[strlen( pBuffer )-1] = '\0';
			}
			V_snprintf( tempFileName, sizeof( tempFileName ), "_%s.tmp", pBuffer );
		}
		else
		{
			// generate safe name at the desired prefix
			char uniqueFilename[MAX_PATH];
			SYSTEMTIME sysTime;                                                       \
			GetLocalTime( &sysTime );   
			sprintf( uniqueFilename, "%d_%d_%d_%d_%d.tmp", sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds );                                                \
			V_ComposeFileName( WritePath.String(), uniqueFilename, tempFileName, sizeof( tempFileName ) );
		}

		FileName = tempFileName;
		HANDLE hFile = CreateFile( tempFileName, GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
		
		return hFile;
	}
	static HANDLE CreateTempFile( CUtlString &WritePath, CUtlString &FileName )
	{
		char tempFileName[MAX_PATH];
		if ( WritePath.IsEmpty() )
		{
			// use a safe name in the cwd
			char *pBuffer = tmpnam( NULL );
			if ( !pBuffer )
			{
				return INVALID_HANDLE_VALUE;
			}
			if ( pBuffer[0] == '\\' )
			{
				pBuffer++;
			}
			if ( pBuffer[strlen( pBuffer )-1] == '.' )
			{
				pBuffer[strlen( pBuffer )-1] = '\0';
			}
			V_snprintf( tempFileName, sizeof( tempFileName ), "_%s.tmp", pBuffer );
		}
		else
		{
			char uniqueFilename[MAX_PATH];
			static int counter = 0;
			time_t now = time( NULL );
			struct tm *tm = localtime( &now );
			sprintf( uniqueFilename, "%d_%d_%d_%d_%d.tmp", tm->tm_wday, tm->tm_hour, tm->tm_min, tm->tm_sec, ++counter );                                                \
			V_ComposeFileName( WritePath.String(), uniqueFilename, tempFileName, sizeof( tempFileName ) );
		}

		FileName = tempFileName;
		FILE *hFile = fopen( tempFileName, "rw+" );
		
		return (HANDLE)hFile;
	}
bool CommandMenu::LoadFromKeyValues( KeyValues * params )
{
	if ( !params )
		return false;

	V_snprintf( m_CurrentTeam, 4, "%i", GetLocalPlayerTeam() );

	V_FileBase( engine->GetLevelName(), m_CurrentMap, sizeof(m_CurrentMap) );
	
	if ( params != m_MenuKeys )
	{
		if ( m_MenuKeys )
			m_MenuKeys->deleteThis();

		m_MenuKeys = params->MakeCopy(); // save keyvalues
	}

	// iterate through all menu items

	KeyValues * subkey = m_MenuKeys->GetFirstSubKey();

	while ( subkey )
	{
		if ( subkey->GetDataType() == KeyValues::TYPE_NONE )
		{
			if ( !LoadFromKeyValuesInternal( subkey, 0 ) ) // recursive call
				return false;
		}

		subkey = subkey->GetNextKey();
	}
	
	UpdateMenu();

	return true;
}
FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
{
	if ( !initInfo.m_pFileSystem || !initInfo.m_pDirectoryName )
		return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_LoadSearchPaths: Invalid parameters specified." );

	KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths;
	FSReturnCode_t retVal = LoadGameInfoFile( initInfo.m_pDirectoryName, pMainFile, pFileSystemInfo, pSearchPaths );
	if ( retVal != FS_OK )
		return retVal;
	
	// All paths except those marked with |gameinfo_path| are relative to the base dir.
	char baseDir[MAX_PATH];
	if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
		return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );

	initInfo.m_ModPath[0] = 0;

	#define GAMEINFOPATH_TOKEN		"|gameinfo_path|"
	#define BASESOURCEPATHS_TOKEN	"|all_source_engine_paths|"

	bool bLowViolence = IsLowViolenceBuild();
	bool bFirstGamePath = true;
	
	for ( KeyValues *pCur=pSearchPaths->GetFirstValue(); pCur; pCur=pCur->GetNextValue() )
	{
		const char *pPathID = pCur->GetName();
		const char *pLocation = pCur->GetString();
		
		if ( Q_stristr( pLocation, GAMEINFOPATH_TOKEN ) == pLocation )
		{
			pLocation += strlen( GAMEINFOPATH_TOKEN );
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, initInfo.m_pDirectoryName, pLocation, bLowViolence );
		}
		else if ( Q_stristr( pLocation, BASESOURCEPATHS_TOKEN ) == pLocation )
		{
			// This is a special identifier that tells it to add the specified path for all source engine versions equal to or prior to this version.
			// So in Orange Box, if they specified:
			//		|all_source_engine_paths|hl2
			// it would add the ep2\hl2 folder and the base (ep1-era) hl2 folder.
			//
			// We need a special identifier in the gameinfo.txt here because the base hl2 folder exists in different places.
			// In the case of a game or a Steam-launched dedicated server, all the necessary prior engine content is mapped in with the Steam depots,
			// so we can just use the path as-is.

			// In the case of an hldsupdatetool dedicated server, the base hl2 folder is "..\..\hl2" (since we're up in the 'orangebox' folder).
												   
			pLocation += strlen( BASESOURCEPATHS_TOKEN );

			// Add the Orange-box path (which also will include whatever the depots mapped in as well if we're 
			// running a Steam-launched app).
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );

			if ( FileSystem_IsHldsUpdateToolDedicatedServer() )
			{			
				// If we're using the hldsupdatetool dedicated server, then go up a directory to get the ep1-era files too.
				char ep1EraPath[MAX_PATH];
				V_snprintf( ep1EraPath, sizeof( ep1EraPath ), "..%c%s", CORRECT_PATH_SEPARATOR, pLocation );
				FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, ep1EraPath, bLowViolence );
			}
		}
		else
		{
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );
		}
	}

	pMainFile->deleteThis();

	//
	// Set up search paths for add-ons
	//
	if ( IsPC() )
	{
#ifdef ENGINE_DLL
		FileSystem_UpdateAddonSearchPaths( initInfo.m_pFileSystem );
#endif
	}

	// these specialized tool paths are not used on 360 and cause a costly constant perf tax, so inhibited
	if ( IsPC() )
	{
		// Create a content search path based on the game search path
		const char *pGameRoot = getenv( GAMEROOT_TOKEN );
		const char *pContentRoot = getenv( CONTENTROOT_TOKEN );

		if ( pGameRoot && pContentRoot )
		{
			int nLen = initInfo.m_pFileSystem->GetSearchPath( "GAME", false, NULL, 0 );
			char *pSearchPath = (char*)stackalloc( nLen * sizeof(char) );
			initInfo.m_pFileSystem->GetSearchPath( "GAME", false, pSearchPath, nLen );
			char *pPath = pSearchPath;
			while( pPath )
			{
				char *pSemiColon = strchr( pPath, ';' );
				if ( pSemiColon )
				{
					*pSemiColon = 0;
				}

				Q_StripTrailingSlash( pPath );
				Q_FixSlashes( pPath );

				const char *pCurPath = pPath;
				pPath = pSemiColon ? pSemiColon + 1 : NULL;

				char pRelativePath[MAX_PATH];
				char pContentPath[MAX_PATH];
				if ( !Q_MakeRelativePath( pCurPath, pGameRoot, pRelativePath, sizeof(pRelativePath) ) )
					continue;

				Q_ComposeFileName( pContentRoot, pRelativePath, pContentPath, sizeof(pContentPath) );
				initInfo.m_pFileSystem->AddSearchPath( pContentPath, "CONTENT" );
			}

			// Add the "platform" directory as a game searchable path
			char pPlatformPath[MAX_PATH];
			Q_ComposeFileName( pGameRoot, "platform", pPlatformPath, sizeof(pPlatformPath) );
			initInfo.m_pFileSystem->AddSearchPath( pPlatformPath, "GAME", PATH_ADD_TO_TAIL );

			initInfo.m_pFileSystem->AddSearchPath( pContentRoot, "CONTENTROOT" );
			initInfo.m_pFileSystem->AddSearchPath( pGameRoot, "GAMEROOT" );
		}
		else
		{
			// Come up with some reasonable default
			int nLen = initInfo.m_pFileSystem->GetSearchPath( "MOD", false, NULL, 0 );
			char *pSearchPath = (char*)stackalloc( nLen * sizeof(char) );
			initInfo.m_pFileSystem->GetSearchPath( "MOD", false, pSearchPath, nLen );
			char *pSemiColon = strchr( pSearchPath, ';' );
			if ( pSemiColon )
			{
				*pSemiColon = 0;
			}

			char pGameRootPath[MAX_PATH];
			Q_strncpy( pGameRootPath, pSearchPath, sizeof(pGameRootPath) );
			Q_StripTrailingSlash( pGameRootPath );
			Q_StripFilename( pGameRootPath );

			char pContentRootPath[MAX_PATH];
			Q_strncpy( pContentRootPath, pGameRootPath, sizeof(pContentRootPath) );
			char *pGame = Q_stristr( pContentRootPath, "game" );

			if ( pGame )
			{
				Q_strcpy( pGame, "content" );
			}

			initInfo.m_pFileSystem->AddSearchPath( pContentRootPath, "CONTENTROOT" );
			initInfo.m_pFileSystem->AddSearchPath( pGameRootPath, "GAMEROOT" );
		}

		// Also, mark specific path IDs as "by request only". That way, we won't waste time searching in them
		// when people forget to specify a search path.
		initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "contentroot", true );
		initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "gameroot", true );
		initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "content", true );
	}

	// Also, mark specific path IDs as "by request only". That way, we won't waste time searching in them
	// when people forget to specify a search path.
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "executable_path", true );
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "gamebin", true );
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod", true );

	// Add the write path last.
	if ( initInfo.m_ModPath[0] != 0 )
	{
		initInfo.m_pFileSystem->AddSearchPath( initInfo.m_ModPath, "DEFAULT_WRITE_PATH", PATH_ADD_TO_TAIL );
	}

#ifdef _DEBUG	
	initInfo.m_pFileSystem->PrintSearchPaths();
#endif

#if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) && !defined( _X360 )
	//copy search paths to stack tools so it can grab pdb's from all over. But only on P4 or Steam Beta builds
	if( (CommandLine()->FindParm( "-steam" ) == 0) || //not steam
		(CommandLine()->FindParm( "-internalbuild" ) != 0) ) //steam beta is ok
	{
		char szSearchPaths[4096];
		//int CBaseFileSystem::GetSearchPath( const char *pathID, bool bGetPackFiles, char *pPath, int nMaxLen )
		int iLength1 = initInfo.m_pFileSystem->GetSearchPath( "EXECUTABLE_PATH", false, szSearchPaths, 4096 );
		if( iLength1 == 1 )
			iLength1 = 0;

		int iLength2 = initInfo.m_pFileSystem->GetSearchPath( "GAMEBIN", false, szSearchPaths + iLength1, 4096 - iLength1 );
		if( (iLength2 > 1) && (iLength1 > 1) )
		{
			szSearchPaths[iLength1 - 1] = ';'; //replace first null terminator
		}

		const char *szAdditionalPath = CommandLine()->ParmValue( "-AdditionalPDBSearchPath" );
		if( szAdditionalPath && szAdditionalPath[0] )
		{
			int iLength = iLength1;
			if( iLength2 > 1 )
				iLength += iLength2;

			if( iLength != 0 )
			{
				szSearchPaths[iLength - 1] = ';'; //replaces null terminator
			}
			V_strncpy( &szSearchPaths[iLength], szAdditionalPath, 4096 - iLength );			
		}

		//Append the perforce symbol server last. Documentation says that "srv*\\perforce\symbols" should work, but it doesn't.
		//"symsrv*symsrv.dll*\\perforce\symbols" which the docs say is the same statement, works.
		{
			V_strncat( szSearchPaths, ";symsrv*symsrv.dll*\\\\perforce\\symbols", 4096 );
		}

		SetStackTranslationSymbolSearchPath( szSearchPaths );
		//MessageBox( NULL, szSearchPaths, "Search Paths", 0 );
	}
#endif

	return FS_OK;
}
Exemple #14
0
// glUseProgram() will be called as a side effect!
bool CGLMShaderPair::SetProgramPair( CGLMProgram *vp, CGLMProgram *fp )
{
	m_valid	= false;			// assume failure
	
	// true result means successful link and query
	bool vpgood = (vp!=NULL) && (vp->m_descs[ kGLMGLSL ].m_valid);
	bool fpgood = (fp!=NULL) && (fp->m_descs[ kGLMGLSL ].m_valid);
	
	if ( !fpgood )
	{
		// fragment side allowed to be "null".
		fp = m_ctx->m_pNullFragmentProgram;
	}

	if ( vpgood && fpgood )
	{
		if ( vp->m_nCentroidMask != fp->m_nCentroidMask )
		{
			Warning( "CGLMShaderPair::SetProgramPair: Centroid masks differ at link time of vertex shader %s and pixel shader %s!\n", 
				vp->m_shaderName, fp->m_shaderName );
		}

		// attempt link. but first, detach any previously attached programs
		if (m_vertexProg)
		{
			gGL->glDetachObjectARB(m_program, m_vertexProg->m_descs[kGLMGLSL].m_object.glsl);
			m_vertexProg = NULL;			
		}
		
		if (m_fragmentProg)
		{
			gGL->glDetachObjectARB(m_program, m_fragmentProg->m_descs[kGLMGLSL].m_object.glsl);
			m_fragmentProg = NULL;			
		}
		
		// now attach
		
		gGL->glAttachObjectARB( m_program, vp->m_descs[kGLMGLSL].m_object.glsl );
		m_vertexProg = vp;

		gGL->glAttachObjectARB( m_program, fp->m_descs[kGLMGLSL].m_object.glsl );
		m_fragmentProg = fp;
	
		// force the locations for input attributes v0-vN to be at locations 0-N
		// use the vertex attrib map to know which slots are live or not... oy!  we don't have that map yet... but it's OK.
		// fallback - just force v0-v15 to land in locations 0-15 as a standard.
		
		if ( vp->m_descs[kGLMGLSL].m_valid )
		{
			for( int i = 0; i < 16; i++ )
			{
				char tmp[16];
				sprintf(tmp, "v%d", i);	// v0 v1 v2 ... et al
				
				gGL->glBindAttribLocationARB( m_program, i, tmp );
			}
		}

		if (CommandLine()->CheckParm("-dumpallshaders"))
		{
			// Dump all shaders, for debugging.
			FILE* pFile = fopen("shaderdump.txt", "a+");
			if (pFile)
			{
				fprintf(pFile, "--------------VP:%s\n%s\n", vp->m_shaderName, vp->m_text);
				fprintf(pFile, "--------------FP:%s\n%s\n", fp->m_shaderName, fp->m_text);
				fclose(pFile);
			}
		}
			
		// now link
		gGL->glLinkProgramARB( m_program );

		// check for success
		GLint result = 0;
		gGL->glGetObjectParameterivARB(m_program,GL_OBJECT_LINK_STATUS_ARB,&result);	// want GL_TRUE
		
		if (result == GL_TRUE)
		{
			// success
			
			m_valid	= true;
			m_revision++;
		}
		else
		{
			GLint length = 0;
			GLint laux = 0;
			
			// do some digging
			gGL->glGetObjectParameterivARB(m_program,GL_OBJECT_INFO_LOG_LENGTH_ARB,&length);

			GLcharARB *logString = (GLcharARB *)malloc(length * sizeof(GLcharARB));
			gGL->glGetInfoLogARB(m_program, length, &laux, logString);	

			char *vtemp = strdup(vp->m_text);
			vtemp[ vp->m_descs[kGLMGLSL].m_textOffset + vp->m_descs[kGLMGLSL].m_textLength ] = 0;
			
			char *ftemp = strdup(fp->m_text);
			ftemp[ fp->m_descs[kGLMGLSL].m_textOffset + fp->m_descs[kGLMGLSL].m_textLength ] = 0;
			
			GLMPRINTF(("-D- ----- GLSL link failed: \n %s ",logString ));

			GLMPRINTF(("-D- ----- GLSL vertex program selected: %08x (handle %08x)", vp, vp->m_descs[kGLMGLSL].m_object.glsl ));
			GLMPRINTTEXT(( vtemp + vp->m_descs[kGLMGLSL].m_textOffset, eDebugDump, GLMPRINTTEXT_NUMBEREDLINES ));
			
			GLMPRINTF(("-D- ----- GLSL fragment program selected: %08x (handle %08x)", fp, vp->m_descs[kGLMGLSL].m_object.glsl ));
			GLMPRINTTEXT(( ftemp + fp->m_descs[kGLMGLSL].m_textOffset, eDebugDump, GLMPRINTTEXT_NUMBEREDLINES ));
			
			GLMPRINTF(("-D- -----end-----" ));

			free( ftemp );
			free( vtemp );
			free( logString );
		}
	}
	else
	{
		// fail
		Assert(!"Can't link these programs");
	}

	if (m_valid)
	{
		gGL->glUseProgram( m_program );

		m_ctx->NewLinkedProgram();
				
		m_locVertexParams = gGL->glGetUniformLocationARB( m_program, "vc");
		m_locVertexBoneParams = gGL->glGetUniformLocationARB( m_program, "vcbones");
		m_locVertexScreenParams = gGL->glGetUniformLocationARB( m_program, "vcscreen");
		m_nScreenWidthHeight = 0xFFFFFFFF;
				
		m_locVertexInteger0 = gGL->glGetUniformLocationARB( m_program, "i0");
		
		m_bHasBoolOrIntUniforms = false;
		if ( m_locVertexInteger0 >= 0 )
			m_bHasBoolOrIntUniforms = true;

		for ( uint i = 0; i < cMaxVertexShaderBoolUniforms; i++ )
		{
			char buf[256];
			V_snprintf( buf, sizeof(buf), "b%d", i );
			m_locVertexBool[i] = gGL->glGetUniformLocationARB( m_program, buf );
			if ( m_locVertexBool[i] != - 1 )
				m_bHasBoolOrIntUniforms = true;
		}

		for ( uint i = 0; i < cMaxFragmentShaderBoolUniforms; i++ )
		{
			char buf[256];
			V_snprintf( buf, sizeof(buf), "fb%d", i );
			m_locFragmentBool[i] = gGL->glGetUniformLocationARB( m_program, buf );
			if ( m_locFragmentBool[i] != - 1 )
				m_bHasBoolOrIntUniforms = true;
		}

 		m_locFragmentParams = gGL->glGetUniformLocationARB( m_program, "pc");
						
		for (uint i = 0; i < kGLMNumProgramTypes; i++)
		{
			m_NumUniformBufferParams[i] = 0;

			if (i == kGLMVertexProgram)
			{
				if (m_locVertexParams < 0)
					continue;
			}
			else if (m_locFragmentParams < 0)
				continue;

			const uint nNum = (i == kGLMVertexProgram) ? m_vertexProg->m_descs[kGLMGLSL].m_highWater : m_fragmentProg->m_descs[kGLMGLSL].m_highWater;
						
			uint j;
			for (j = 0; j < nNum; j++)
			{
				char buf[256];
				V_snprintf(buf, sizeof(buf), "%cc[%i]", "vp"[i], j);
				// Grab the handle of each array element, so we can more efficiently update array elements in the middle.
				int l = m_UniformBufferParams[i][j] = gGL->glGetUniformLocationARB( m_program, buf );
				if ( l < 0 )
					break;
			}
			
			m_NumUniformBufferParams[i] = j;
		}
		
 		m_locFragmentFakeSRGBEnable = gGL->glGetUniformLocationARB( m_program, "flSRGBWrite");
		m_fakeSRGBEnableValue = -1.0f;
						
		for( int sampler=0; sampler<16; sampler++)
		{
			char tmp[16];
			sprintf(tmp, "sampler%d", sampler);	// sampler0 .. sampler1.. etc
			
			GLint nLoc = gGL->glGetUniformLocationARB( m_program, tmp );
			m_locSamplers[sampler] = nLoc;
			if ( nLoc >= 0 )
			{
				gGL->glUniform1iARB( nLoc, sampler );
			}
		}
	}
	else
	{
		m_locVertexParams = -1;
		m_locVertexBoneParams = -1;
		m_locVertexScreenParams = -1;
		m_nScreenWidthHeight = 0xFFFFFFFF;

		m_locVertexInteger0 = -1;
		memset( m_locVertexBool, 0xFF, sizeof( m_locVertexBool ) );
		memset( m_locFragmentBool, 0xFF, sizeof( m_locFragmentBool ) );
		m_bHasBoolOrIntUniforms = false;
		
		m_locFragmentParams = -1;
		m_locFragmentFakeSRGBEnable = -1;
		m_fakeSRGBEnableValue = -999;
		
		memset( m_locSamplers, 0xFF, sizeof( m_locSamplers ) );
		
		m_revision = 0;		
	}

	return m_valid;
}
FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
{
	if ( !initInfo.m_pFileSystem || !initInfo.m_pDirectoryName )
		return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_LoadSearchPaths: Invalid parameters specified." );

	KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths;
	FSReturnCode_t retVal = LoadGameInfoFile( initInfo.m_pDirectoryName, pMainFile, pFileSystemInfo, pSearchPaths );
	if ( retVal != FS_OK )
		return retVal;
	
	// All paths except those marked with |gameinfo_path| are relative to the base dir.
	char baseDir[MAX_PATH];
	if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
		return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );

	initInfo.m_ModPath[0] = 0;

	#define GAMEINFOPATH_TOKEN		"|gameinfo_path|"
	#define BASESOURCEPATHS_TOKEN	"|all_source_engine_paths|"

	bool bLowViolence = IsLowViolenceBuild();
	bool bFirstGamePath = true;
	
	for ( KeyValues *pCur=pSearchPaths->GetFirstValue(); pCur; pCur=pCur->GetNextValue() )
	{
		const char *pPathID = pCur->GetName();
		const char *pLocation = pCur->GetString();
		
		if ( Q_stristr( pLocation, GAMEINFOPATH_TOKEN ) == pLocation )
		{
			pLocation += strlen( GAMEINFOPATH_TOKEN );
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, initInfo.m_pDirectoryName, pLocation, bLowViolence );
		}
		else if ( Q_stristr( pLocation, BASESOURCEPATHS_TOKEN ) == pLocation )
		{
			// This is a special identifier that tells it to add the specified path for all source engine versions equal to or prior to this version.
			// So in Orange Box, if they specified:
			//		|all_source_engine_paths|hl2
			// it would add the ep2\hl2 folder and the base (ep1-era) hl2 folder.
			//
			// We need a special identifier in the gameinfo.txt here because the base hl2 folder exists in different places.
			// In the case of a game or a Steam-launched dedicated server, all the necessary prior engine content is mapped in with the Steam depots,
			// so we can just use the path as-is.

			// In the case of an hldsupdatetool dedicated server, the base hl2 folder is "..\..\hl2" (since we're up in the 'orangebox' folder).
												   
			pLocation += strlen( BASESOURCEPATHS_TOKEN );

			// Add the Orange-box path (which also will include whatever the depots mapped in as well if we're 
			// running a Steam-launched app).
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );

			if ( FileSystem_IsHldsUpdateToolDedicatedServer() )
			{			
				// If we're using the hldsupdatetool dedicated server, then go up a directory to get the ep1-era files too.
				char ep1EraPath[MAX_PATH];
				V_snprintf( ep1EraPath, sizeof( ep1EraPath ), "..%c%s", CORRECT_PATH_SEPARATOR, pLocation );
				FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, ep1EraPath, bLowViolence );
			}
		}
		else
		{
			FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );
		}
	}

	pMainFile->deleteThis();

	// Also, mark specific path IDs as "by request only". That way, we won't waste time searching in them
	// when people forget to specify a search path.
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "executable_path", true );
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "gamebin", true );
	initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod", true );
	if ( initInfo.m_ModPath[0] != 0 )
	{
		// Add the write path last.
		initInfo.m_pFileSystem->AddSearchPath( initInfo.m_ModPath, "DEFAULT_WRITE_PATH", PATH_ADD_TO_TAIL );
	}

#ifdef _DEBUG	
	initInfo.m_pFileSystem->PrintSearchPaths();
#endif

	return FS_OK;
}
void CNB_Skill_Panel::OnThink()
{
	BaseClass::OnThink();

	if ( !MarineSkills() || !Briefing() )
		return;

	CASW_Marine_Profile *pProfile = Briefing()->GetMarineProfileByProfileIndex( m_nProfileIndex );
	if ( !pProfile )
		return;

	int nMaxSkillPoints = MarineSkills()->GetMaxSkillPoints( pProfile->GetSkillMapping( m_nSkillSlot ) );
	const char *szImageName = MarineSkills()->GetSkillImage( pProfile->GetSkillMapping( m_nSkillSlot ) );
	if ( V_strcmp( m_szLastSkillImage, szImageName ) )
	{
		V_snprintf( m_szLastSkillImage, sizeof( m_szLastSkillImage ), "%s", szImageName );
		char buffer[ 256 ];
		V_snprintf( buffer, sizeof( buffer ), "vgui/%s", szImageName );
		
		color32 white;
		white.r = 255;
		white.g = 255;
		white.b = 255;
		white.a = 255;

		color32 dull;
		dull.r = 192;
		dull.g = 192;
		dull.b = 192;
		dull.a = 255;

		m_pSkillButton->SetImage( CBitmapButton::BUTTON_ENABLED, buffer, white );
		m_pSkillButton->SetImage( CBitmapButton::BUTTON_DISABLED, buffer, dull );
		m_pSkillButton->SetImage( CBitmapButton::BUTTON_PRESSED, buffer, white );

		V_snprintf( buffer, sizeof( buffer ), "vgui/%s_over", szImageName );
		m_pSkillButton->SetImage( CBitmapButton::BUTTON_ENABLED_MOUSE_OVER, buffer, white );		
	}
	m_pSkillButton->SetEnabled( m_bSpendPointsMode && CanSpendPoint() );

	m_pSkillLabel->SetText( MarineSkills()->GetSkillName( pProfile->GetSkillMapping( m_nSkillSlot ) ) );

	wchar_t wszPointsBuffer[ 24 ];
	_snwprintf( wszPointsBuffer, sizeof( wszPointsBuffer ), L"%d / %d", m_nSkillPoints, nMaxSkillPoints );
	m_pSkillNumberLabel->SetText( wszPointsBuffer );

	m_pSkillBar->ClearMinMax();
	m_pSkillBar->AddMinMax( 0, nMaxSkillPoints );
	m_pSkillBar->Init( m_nSkillPoints, m_nSkillPoints, 0.1f, true, false );

	if ( IsCursorOver() )
	{
		if (!g_hBriefingTooltip.Get())
		{
			g_hBriefingTooltip = new BriefingTooltip(GetParent(), "MedalsTooltip");
		}	
		else if ( g_hBriefingTooltip->GetParent() != GetParent() )
		{
			g_hBriefingTooltip->SetParent( GetParent() );
		}

		if ( g_hBriefingTooltip.Get() && IsFullyVisible() &&
			g_hBriefingTooltip.Get()->GetTooltipPanel() != this )
		{	
			int tx, ty, w, h;
			tx = ty = 0;
			LocalToScreen(tx, ty);
			GetSize(w, h);
			tx += w * 0.5f;
			ty -= h * 0.01f;

			g_hBriefingTooltip.Get()->SetTooltip( this, MarineSkills()->GetSkillName( pProfile->GetSkillMapping( m_nSkillSlot ) ), MarineSkills()->GetSkillDescription( pProfile->GetSkillMapping( m_nSkillSlot ) ),
				tx, ty );
		}
	}
}
Exemple #17
0
void CPhysicsSystem::PhysicsSimulate()
{
	CMiniProfilerGuard mpg(&g_mp_PhysicsSimulate);
	VPROF_BUDGET( "CPhysicsSystem::PhysicsSimulate", VPROF_BUDGETGROUP_PHYSICS );
	float frametime = gpGlobals->frametime;

	if ( physenv )
	{
		g_Collisions.BufferTouchEvents( true );
#ifdef _DEBUG
		physenv->DebugCheckContacts();
#endif
		frametime *= cl_phys_timescale.GetFloat();

		int maxTicks = cl_phys_maxticks.GetInt();
		if ( maxTicks )
		{
			float maxFrameTime = physenv->GetDeltaFrameTime( maxTicks ) - 1e-4f;
			frametime = clamp( frametime, 0, maxFrameTime );
		}

		physenv->Simulate( frametime );

		int activeCount = physenv->GetActiveObjectCount();
		g_mp_active_object_count.Add(activeCount);
		IPhysicsObject **pActiveList = NULL;
		if ( activeCount )
		{
			PHYS_PROFILE(aUpdateActiveObjects)
			pActiveList = (IPhysicsObject **)stackalloc( sizeof(IPhysicsObject *)*activeCount );
			physenv->GetActiveObjects( pActiveList );

			for ( int i = 0; i < activeCount; i++ )
			{
				C_BaseEntity *pEntity = reinterpret_cast<C_BaseEntity *>(pActiveList[i]->GetGameData());
				if ( pEntity )
				{
					//const CCollisionProperty *collProp = pEntity->CollisionProp();
					//debugoverlay->AddBoxOverlay( collProp->GetCollisionOrigin(), collProp->OBBMins(), collProp->OBBMaxs(), collProp->GetCollisionAngles(), 190, 190, 0, 0, 0.01 );

					if ( pEntity->CollisionProp()->DoesVPhysicsInvalidateSurroundingBox() )
					{
						pEntity->CollisionProp()->MarkSurroundingBoundsDirty();
					}
					pEntity->VPhysicsUpdate( pActiveList[i] );
					IPhysicsShadowController *pShadow = pActiveList[i]->GetShadowController();
					if ( pShadow )
					{
						// active shadow object, check for error
						Vector pos, targetPos;
						QAngle rot, targetAngles;
						pShadow->GetTargetPosition( &targetPos, &targetAngles );
						pActiveList[i]->GetPosition( &pos, &rot );
						Vector delta = targetPos - pos;
						float dist = VectorNormalize(delta);
						bool bBlocked = false;
						if ( dist > cl_phys_block_dist.GetFloat() )
						{
							Vector vel;
							pActiveList[i]->GetImplicitVelocity( &vel, NULL );
							float proj = DotProduct(vel, delta);
							if ( proj < dist * cl_phys_block_fraction.GetFloat() )
							{
								bBlocked = true;
								//Msg("%s was blocked %.3f (%.3f proj)!\n", pEntity->GetClassname(), dist, proj );
							}
						}
						Vector targetAxis;
						float deltaTargetAngle;
						RotationDeltaAxisAngle( rot, targetAngles, targetAxis, deltaTargetAngle );
						if ( fabsf(deltaTargetAngle) > 0.5f )
						{
							AngularImpulse angVel;
							pActiveList[i]->GetImplicitVelocity( NULL, &angVel );
							float proj = DotProduct( angVel, targetAxis ) * Sign(deltaTargetAngle);
							if ( proj < (fabsf(deltaTargetAngle) * cl_phys_block_fraction.GetFloat()) )
							{
								bBlocked = true;
								//Msg("%s was rot blocked %.3f proj %.3f!\n", pEntity->GetClassname(), deltaTargetAngle, proj );
							}
						}
					
						if ( bBlocked )
						{
							C_BaseEntity *pBlocker = FindPhysicsBlocker( pActiveList[i] );
							if ( pBlocker )
							{
								if ( IsBlockedShouldDisableCollisions( pEntity ) )
								{
									PhysDisableEntityCollisions( pEntity, pBlocker );
									pActiveList[i]->RecheckContactPoints();
									// GetClassname returns a pointer to the same buffer always!
									//Msg("%s blocked !", pEntity->GetClassname() ); Msg("by %s\n", pBlocker->GetClassname() );
								}
							}
						}
					}
				}
			}
		}

#if 0
		if ( cl_visualize_physics_shadows.GetBool() )
		{
			int entityCount = NUM_ENT_ENTRIES;
			for ( int i = 0; i < entityCount; i++ )
			{
				IClientEntity *pClientEnt = cl_entitylist->GetClientEntity(i);
				if ( !pClientEnt )
					continue;
				C_BaseEntity *pEntity = pClientEnt->GetBaseEntity();
				if ( !pEntity )
					continue;

				Vector pos;
				QAngle angle;
				IPhysicsObject *pObj = pEntity->VPhysicsGetObject();
				if ( !pObj || !pObj->GetShadowController() )
					continue;

				pObj->GetShadowPosition( &pos, &angle );
				debugoverlay->AddBoxOverlay( pos, pEntity->CollisionProp()->OBBMins(), pEntity->CollisionProp()->OBBMaxs(), angle, 255, 255, 0, 32, 0 );
				char tmp[256];
				V_snprintf( tmp, sizeof(tmp),"%s, (%s)\n", pEntity->GetClassname(), VecToString(angle) );
				debugoverlay->AddTextOverlay( pos, 0, tmp );
			}
		}
#endif
		g_Collisions.BufferTouchEvents( false );
		g_Collisions.FrameUpdate();
	}
	physicssound::PlayImpactSounds( m_impactSounds );
}
Exemple #18
0
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CefRefPtr<CefDictionaryValue> PyToCefDictionaryValue( boost::python::object d )
{
	CefRefPtr<CefDictionaryValue> result = CefDictionaryValue::Create();

	boost::python::object items = d.attr("items")();
	boost::python::object iterator = items.attr("__iter__")();
	boost::python::ssize_t length = boost::python::len(items); 
	for( boost::python::ssize_t u = 0; u < length; u++ )
	{
		boost::python::object item = iterator.attr( PY_NEXT_METHODNAME )();
		boost::python::object value = item[1];

		boost::python::object valuetype = fntype( value );

		CefString cefkey = boost::python::extract< const char * >( boost::python::str( item[0] ) );

		if( value == boost::python::object() )
		{
			result->SetNull( cefkey );
		}
		else if( valuetype == builtins.attr("int") )
		{
			result->SetInt( cefkey, boost::python::extract<int>(value) );
		}
		else if( valuetype == builtins.attr("float") )
		{
			result->SetDouble( cefkey, boost::python::extract<float>(value) );
		}
		else if( valuetype == builtins.attr("str") )
		{
			const char *pStr = boost::python::extract<const char *>(value);
			result->SetString( cefkey, pStr );
		}
#if PY_VERSION_HEX < 0x03000000
		else if( valuetype == builtins.attr("unicode") )
		{
			const wchar_t *pStr = PyUnicode_AS_UNICODE( value.ptr() );
			if( !pStr )
			{
				PyErr_SetString(PyExc_ValueError, "PyToCefDictionaryValue: Invalid unicode object in message list" );
				throw boost::python::error_already_set(); 
			}
			result->SetString( cefkey, pStr );
		}
#endif // PY_VERSION_HEX < 0x03000000
		else if( valuetype == builtins.attr("bool") )
		{
			result->SetBool( cefkey, boost::python::extract<bool>(value) );
		}
#if PY_VERSION_HEX >= 0x03000000
		else if( fnisinstance( value, boost::python::object( builtins.attr("list") ) ) || valuetype == builtins.attr("tuple") || valuetype == builtins.attr("set") || valuetype == builtins.attr("map") )
#else
		else if( fnisinstance( value, boost::python::object( builtins.attr("list") ) ) || valuetype == builtins.attr("tuple") || valuetype == builtins.attr("set") )
#endif // PY_VERSION_HEX >= 0x03000000
		{
			result->SetList( cefkey, PyToCefValueList( value ) );
		}
		else if( fnisinstance( value, boost::python::object( builtins.attr("dict") ) ) )
		{
			result->SetDictionary( cefkey, PyToCefDictionaryValue( value ) );
		}
		else if( valuetype == srcbuiltins.attr("Color") )
		{
			Color c = boost::python::extract<Color>(value);
			result->SetString( cefkey, UTIL_VarArgs("rgba(%d, %d, %d, %.2f)", c.r(), c.g(), c.b(), c.a() / 255.0f) );
		}
		else
		{
			const char *pObjectTypeStr = boost::python::extract<const char *>( boost::python::str( valuetype ) );
			const char *pObjectStr = boost::python::extract<const char *>( boost::python::str( value ) );
			char buf[512];
			V_snprintf( buf, sizeof(buf), "PyToCefDictionaryValue: Unsupported type \"%s\" for object \"%s\" in message list", pObjectTypeStr, pObjectStr );
			PyErr_SetString(PyExc_ValueError, buf );
			throw boost::python::error_already_set(); 
		}
	}

	return result;
}
Exemple #19
0
//---------------------------------------------------------------------------------
// Initializes python.
//---------------------------------------------------------------------------------
bool CPythonManager::Initialize( void )
{
	// Construct a path to the python engine directory.
	char szPythonHome[MAX_GAME_PATH];
	V_snprintf(szPythonHome, MAX_GAME_PATH, "%s/Python3", g_GamePaths.GetSPDir());
	V_FixSlashes(szPythonHome);
	DevMsg(1, "[SP] Python home path set to %s\n", szPythonHome);

	// Convert to wide char for python.
	wchar_t wszPythonHome[1024];
	V_strtowcs(szPythonHome, -1, wszPythonHome, 1024);

	// Set that as the python home directory.
 	Py_SetPythonHome(wszPythonHome);
 	Py_SetProgramName(wszPythonHome);
	Py_SetPath(wszPythonHome);

	// Initialize python and its namespaces.
	Py_Initialize();

	// Print some information
	DevMsg(1, "Python version %s initialized!\n", Py_GetVersion());

	// Make sure sys is imported.
	PyRun_SimpleString("import sys");

	// Add the Python API path.
	AddToSysPath("/packages/source-python");

	// Add operating system specific paths.
#if defined(WIN32)
	AddToSysPath("/Python3/plat-win");
#else
	AddToSysPath("/Python3/plat-linux");

	// We've got a bunch of linux shared objects here we need to load.
	AddToSysPath("/Python3/lib-dynload");
#endif

	// Site packages for any extra packages...
	AddToSysPath("/packages/site-packages");

	// Add the custom packages path.
	AddToSysPath("/packages/custom");

	// And of course, the plugins directory for script imports.
	AddToSysPath("/plugins");

	// Initialize all converters
	InitConverters();

	// Initialize all submodules
	modulsp_init();

	// Import the main module file.
	DevMsg(1, "[SP] Importing main module..\n");
	BEGIN_BOOST_PY()

		python::import("__init__");

	END_BOOST_PY_NORET(); // Noret because we have more stuff to do after this import.

	DevMsg(0, "[Source.Python] Loaded successfully.\n");

	return true;
}
//-----------------------------------------------------------------------------
// Purpose: loads per-map manifest!
//-----------------------------------------------------------------------------
void ParseParticleEffectsMap( const char *pMapName, bool bLoadSheets, IFileList *pFilesToReload )
{
	MEM_ALLOC_CREDIT();

	CUtlVector<CUtlString> files;
	char szMapManifestFilename[MAX_PATH];

	szMapManifestFilename[0] = NULL;

	if ( pMapName && *pMapName )
	{
		V_snprintf( szMapManifestFilename, sizeof( szMapManifestFilename ), "maps/%s_particles.txt", pMapName );
	}

	// Open the manifest file, and read the particles specified inside it
	KeyValues *manifest = new KeyValues( szMapManifestFilename );
	if ( manifest->LoadFromFile( filesystem, szMapManifestFilename, "GAME" ) )
	{
		DevMsg( "Successfully loaded particle effects manifest '%s' for map '%s'\n", szMapManifestFilename, pMapName );
		for ( KeyValues *sub = manifest->GetFirstSubKey(); sub != NULL; sub = sub->GetNextKey() )
		{
			if ( !Q_stricmp( sub->GetName(), "file" ) )
			{
				// Ensure the particles are in the particles directory
				char szPath[ 512 ];
				Q_strncpy( szPath, sub->GetString(), sizeof( szPath ) );
				Q_StripFilename( szPath );
				char *pszPath = (szPath[0] == '!') ? &szPath[1] : &szPath[0];
				if ( pszPath && pszPath[0] && !Q_stricmp( pszPath, "particles" ) )
				{
					files.AddToTail( sub->GetString() );
					continue;
				}
				else
				{
					Warning( "CParticleMgr::LevelInit:  Manifest '%s' contains a particle file '%s' that's not under the particles directory. Custom particles must be placed in the particles directory.\n", szMapManifestFilename, sub->GetString() );
				}
			}
			else
			{
				Warning( "CParticleMgr::LevelInit:  Manifest '%s' with bogus file type '%s', expecting 'file'\n", szMapManifestFilename, sub->GetName() );
			}
		}
	}
	else
	{
		// Don't print a warning, and don't proceed any further if the file doesn't exist!
		return;
	}

	int nCount = files.Count();
	if ( !nCount )
	{
		return;
	}

	g_pParticleSystemMgr->ShouldLoadSheets( bLoadSheets );

	for ( int i = 0; i < nCount; ++i )
	{
		// If we've been given a list of particles to reload, only reload those.
		if ( !pFilesToReload || (pFilesToReload && pFilesToReload->IsFileInList( files[i] )) )
		{
			g_pParticleSystemMgr->ReadParticleConfigFile( files[i], true, true );
		}
	}

	g_pParticleSystemMgr->DecommitTempMemory();
}
Exemple #21
0
bool IsValidSteamID(const char *pchSteamID, char *pszErr, int maxerr)
{
    if(!strcmp(pchSteamID, "STEAM_ID_PENDING"))
    {
        return true;
    }

    if(!strcmp(pchSteamID, "BOT"))
    {
        return true;
    }

    if(strncmp(pchSteamID, "STEAM_", 6) && strncmp(pchSteamID, "[U:1:", 5))
    {
        if(pszErr)
            V_snprintf(pszErr, maxerr, "[SOURCEOP] Unexpected SteamID format. Expected STEAM_ or [U:1:###].");
        return false;
    }

    if(!strncmp(pchSteamID, "STEAM_", 6))
    {
        if(!isdigit(pchSteamID[6]))
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected digit after STEAM_");
            return false;
        }
        if(pchSteamID[7] != ':')
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected colon after STEAM_#");
            return false;
        }
        if(!isdigit(pchSteamID[8]))
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected digit after STEAM_#:");
            return false;
        }
        unsigned char middledigit = (pchSteamID[8] - '0');
        if(middledigit != 0 && middledigit != 1)
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected only 0 or 1 after STEAM_#:");
            return false;
        }
        if(pchSteamID[9] != ':')
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected colon after STEAM_#:#");
            return false;
        }
        int steamidlen = strlen(pchSteamID);
        if(steamidlen <= 10)
        {
            if(pszErr)
                V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected at least one digit after STEAM_#:#:");
            return false;
        }

        for(int i = 10; i < steamidlen; i++)
        {
            if(!isdigit(pchSteamID[i]))
            {
                if(pszErr)
                    V_snprintf(pszErr, maxerr, "[SOURCEOP] Expected only digits after STEAM_#:#:");
                return false;
            }
        }
    }
    else
    {
        int steamidlen = strlen( pchSteamID );
        if ( steamidlen <= 5 )
        {
            if ( pszErr )
                V_snprintf( pszErr, maxerr, "[SOURCEOP] Expected at least one digit after [U:1:" );
            return false;
        }

        if ( !isdigit( pchSteamID[3] ) )
        {
            if ( pszErr )
                V_snprintf( pszErr, maxerr, "[SOURCEOP] Expected a digit after [U:" );
            return false;
        }

        if ( pchSteamID[steamidlen - 1] != ']' )
        {
            if ( pszErr )
                V_snprintf( pszErr, maxerr, "[SOURCEOP] The last character must be ']'" );
            return false;
        }

        for ( int i = 5; i < steamidlen; i++ )
        {
            if ( pchSteamID[i] == ']' && i != steamidlen - 1 )
            {
                if ( pszErr )
                    V_snprintf( pszErr, maxerr, "[SOURCEOP] ']' can only be the last character" );
                return false;
            }

            if ( !isdigit( pchSteamID[i] ) && pchSteamID[i] != ']' )
            {
                if ( pszErr )
                    V_snprintf( pszErr, maxerr, "[SOURCEOP] Expected only digits between [U:1: and ]" );
                return false;
            }
        }
    }

    return true;
}
Exemple #22
0
char *V_pretifynum( int64 value )
{
	static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ];
	static int  current;

	char *out = output[ current ];
	current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 );

	*out = 0;

	// Render the leading -, if necessary
	if ( value < 0 )
	{
		char *pchRender = out + V_strlen( out );
		V_snprintf( pchRender, 32, "-" );
		value = -value;
	}

	// Render quadrillions
	if ( value >= 1000000000000 )
	{
		char *pchRender = out + V_strlen( out );
		V_snprintf( pchRender, 32, "%d,", value / 1000000000000 );
	}

	// Render trillions
	if ( value >= 1000000000000 )
	{
		char *pchRender = out + V_strlen( out );
		V_snprintf( pchRender, 32, "%d,", value / 1000000000000 );
	}

	// Render billions
	if ( value >= 1000000000 )
	{
		char *pchRender = out + V_strlen( out );
		V_snprintf( pchRender, 32, "%d,", value / 1000000000 );
	}

	// Render millions
	if ( value >= 1000000 )
	{
		char *pchRender = out + V_strlen( out );
		if ( value >= 1000000000 )
			V_snprintf( pchRender, 32, "%03d,", ( value / 1000000 ) % 1000 );
		else
			V_snprintf( pchRender, 32, "%d,", ( value / 1000000 ) % 1000 );
	}

	// Render thousands
	if ( value >= 1000 )
	{
		char *pchRender = out + V_strlen( out );
		if ( value >= 1000000 )
			V_snprintf( pchRender, 32, "%03d,", ( value / 1000 ) % 1000 );
		else
			V_snprintf( pchRender, 32, "%d,", ( value / 1000 ) % 1000 );
	}

	// Render units
	char *pchRender = out + V_strlen( out );
	if ( value > 1000 )
		V_snprintf( pchRender, 32, "%03d", value % 1000 );
	else
		V_snprintf( pchRender, 32, "%d", value % 1000 );

	return out;
}
Exemple #23
0
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void PySingleToCefValueList( boost::python::object value, CefListValue *result, int i )
{
	boost::python::object jsobject = _cef.attr("JSObject");
	boost::python::object valuetype = fntype( value );

	if( value == boost::python::object() )
	{
		result->SetNull( i );
	}
	else if( valuetype == builtins.attr("int") )
	{
		result->SetInt( i, boost::python::extract<int>(value) );
	}
	else if( valuetype == builtins.attr("float") )
	{
		result->SetDouble( i, boost::python::extract<float>(value) );
	}
	else if( valuetype == builtins.attr("str") )
	{
		const char *pStr = boost::python::extract<const char *>(value);
		result->SetString( i, pStr );
	}
#if PY_VERSION_HEX < 0x03000000
	else if( valuetype == builtins.attr("unicode") )
	{
		const wchar_t *pStr = PyUnicode_AS_UNICODE( value.ptr() );
		if( !pStr )
		{
			PyErr_SetString(PyExc_ValueError, "PyToCefValueList: Invalid unicode object in message list" );
			throw boost::python::error_already_set(); 
		}
		result->SetString( i, pStr );
	}
#endif // PY_VERSION_HEX < 0x03000000
	else if( valuetype == builtins.attr("bool") )
	{
		result->SetBool( i, boost::python::extract<bool>(value) );
	}
#if PY_VERSION_HEX >= 0x03000000
	else if( fnisinstance( value, boost::python::object( builtins.attr("list") ) ) || valuetype == builtins.attr("tuple") || valuetype == builtins.attr("set") || valuetype == builtins.attr("map") )
#else
	else if( fnisinstance( value, boost::python::object( builtins.attr("list") ) ) || valuetype == builtins.attr("tuple") || valuetype == builtins.attr("set") )
#endif // PY_VERSION_HEX >= 0x03000000
	{
		result->SetList( i, PyToCefValueList( value ) );
	}
	else if( fnisinstance( value, boost::python::object( builtins.attr("dict") ) ) )
	{
		result->SetDictionary( i, PyToCefDictionaryValue( value ) );
	}
	else if( valuetype == srcbuiltins.attr("Color") )
	{
		Color c = boost::python::extract<Color>(value);
		result->SetString( i, UTIL_VarArgs("rgba(%d, %d, %d, %.2f)", c.r(), c.g(), c.b(), c.a() / 255.0f) );
	}
	else if( valuetype == jsobject )
	{
		PyJSObject *pJSObject = boost::python::extract< PyJSObject * >( value );
		WarsCefJSObject_t warsCefJSObject;
		V_strncpy( warsCefJSObject.uuid, pJSObject->GetJSObject()->GetIdentifier().ToString().c_str(), sizeof( warsCefJSObject.uuid ) );
			
		CefRefPtr<CefBinaryValue> pRefData = CefBinaryValue::Create( &warsCefJSObject, sizeof( warsCefJSObject ) );
		result->SetBinary( i, pRefData );
	}
	else
	{
		const char *pObjectTypeStr = boost::python::extract<const char *>( boost::python::str( valuetype ) );
		const char *pObjectStr = boost::python::extract<const char *>( boost::python::str( value ) );
		char buf[512];
		V_snprintf( buf, sizeof(buf), "PyToCefValueList: Unsupported type \"%s\" for object \"%s\" in message list", pObjectTypeStr, pObjectStr );
		PyErr_SetString( PyExc_ValueError, buf );
		throw boost::python::error_already_set(); 
	}
}
Exemple #24
0
    bool LoadItem(specialitemload_t const &item)
    {
        unsigned long long profileid = item.steamid.ConvertToUint64();
        char query[1024];

        V_snprintf(query, sizeof(query), "SELECT `id`, `itemdef`, `petname`, `equipped`, `level`, `quality` FROM `specialitems` WHERE `owner` = %llu AND `active` = 'Y' ORDER BY `id` ASC", profileid);
        //Msg("[ITEMDBG] %s\n", query);
        m_SQL->Query(query);

        item.itemmutex->Lock();

        unsigned int index = item.itemlist->Find(profileid);
        if(item.itemlist->IsValidIndex(index))
        {
            // this should be checked first in NetworkIDValidated
            // but this could still happen if two NetworkIDValidated occur for the same ID
            // while items still loading
            Msg("[ITEMDBG] Item list already exists for %s.\n", item.steamid.Render());
            item.itemmutex->Unlock();
            return true;
        }

        item.itemmutex->Unlock();

        CUtlVector<CSpecialItem *> *items = new CUtlVector<CSpecialItem *>;

        CSOPMySQLRow row = m_SQL->NextRow();
        while(!row.IsNull())
        {
            CSpecialItem *newspecialitem = new CSpecialItem;
            newspecialitem->m_iIndex = atoi(row.Column(0));
            V_strncpy(newspecialitem->m_szPetName, row.Column(2), sizeof(newspecialitem->m_szPetName));
            newspecialitem->m_bEquipped = atoi(row.Column(3)) != 0;
            CEconItemView *newitem = new CEconItemView;
            //Msg("[ITEMDBG] Test: %i %i\n", sizeof(CEconItemView), sizeof(CEconItemAttribute));
            newspecialitem->m_pItem = newitem;
            newitem->m_bInitialized = false;
            newitem->m_iEntityLevel = atoi(row.Column(4));
            newitem->m_iEntityQuality = atoi(row.Column(5));
            newitem->m_iGlobalIndex = 0;
            newitem->m_iGlobalIndexHigh = 0;
            newitem->m_iGlobalIndexLow = 0;
            newitem->m_iAccountID = item.steamid.GetAccountID();
            newitem->m_iItemDefinitionIndex = atoi(row.Column(1));
            newitem->m_iPosition = 0;
            newitem->m_pUnk = NULL;
            newitem->m_attributes.m_Attributes.EnsureCapacity(16);

            //Msg("[ITEMDBG] Adding item %i  type %i level %i quality %i\n", newitem->m_iGlobalIndex, newitem->m_iItemDefinitionIndex, newitem->m_iEntityLevel, newitem->m_iEntityQuality);
            items->AddToTail(newspecialitem);

            row = m_SQL->NextRow();
        }

        m_SQL->FreeResult();

        // now go and get all the attributes
        for(int i = 0; i < items->Count(); i++)
        {
            CSpecialItem *curspecialitem = items->Element(i);
            CEconItemView *curitem = curspecialitem->m_pItem;

            V_snprintf(query, sizeof(query), "SELECT `attribdef`, `value` FROM `specialitems_attributes` WHERE `itemid` = %i", (int)curspecialitem->m_iIndex);
            //Msg("[ITEMDBG] %s\n", query);
            m_SQL->Query(query);

            CSOPMySQLRow row = m_SQL->NextRow();
            while(!row.IsNull())
            {
                CEconItemAttribute newAttrib;
                newAttrib.m_iAttribDef = atoi(row.Column(0));
                newAttrib.m_flVal = atof(row.Column(1));
                newAttrib.m_flInitialValue = newAttrib.m_flVal;
                newAttrib.m_nRefundableCurrency = 0;
                newAttrib.m_bSetBonus = false;

                //Msg("[ITEMDBG] Adding attribute to item %i  def %i  val %f\n", (int)curitem->m_iGlobalIndex, newAttrib.m_iAttribDef, newAttrib.m_flVal);
                curitem->m_attributes.m_Attributes.AddToTail(newAttrib);

                row = m_SQL->NextRow();
            }

            m_SQL->FreeResult();
        }

        item.itemmutex->Lock();
        index = item.itemlist->Find(profileid);
        if(item.itemlist->IsValidIndex(index))
        {
            // this should be checked first in NetworkIDValidated
            // but this could still happen if two NetworkIDValidated occur for the same ID
            // while items still loading
            Msg("[ITEMDBG] Item list already exists when inserting for %s.\n", item.steamid.Render());

            // free list
            for(int i = 0; i < items->Count(); i++)
            {
                delete items->Element(i)->m_pItem;
                delete items->Element(i);
            }
            delete items;
        }
        else
        {
            item.itemlist->Insert(profileid, items);
        }
        item.itemmutex->Unlock();
        
        return true;
    }
Exemple #25
0
//-----------------------------------------------------------------------------
//	BugDlg_Submit
//
//-----------------------------------------------------------------------------
bool BugDlg_Submit( HWND hWnd )
{
	char	title[1024];
	char	miscInfo[1024];
	char	basename[MAX_PATH];
	char	filename[MAX_PATH];
	char	positionName[MAX_PATH];
	char	orientationName[MAX_PATH];
	char	buildName[MAX_PATH];
	char	mapName[MAX_PATH];
	bool	bSuccess = false;

	sprintf( positionName, "%f %f %f", g_bug_mapInfo.position[0], g_bug_mapInfo.position[1], g_bug_mapInfo.position[2] );
	SetDlgItemText( g_bug_hWnd, IDC_BUG_POSITION_LABEL, positionName );

	sprintf( orientationName, "%f %f %f", g_bug_mapInfo.angle[0], g_bug_mapInfo.angle[1], g_bug_mapInfo.angle[2] );
	SetDlgItemText( g_bug_hWnd, IDC_BUG_ORIENTATION_LABEL, orientationName );

	sprintf( buildName, "%d", g_bug_mapInfo.build );
	SetDlgItemText( g_bug_hWnd, IDC_BUG_BUILD_LABEL, buildName );

	V_FileBase( g_bug_mapInfo.mapPath, mapName, sizeof( mapName ) );
	char *pExtension = V_stristr( mapName, ".bsp" );
	if ( pExtension )
	{
		*pExtension = '\0';
	}
	pExtension = V_stristr( mapName, ".360" );
	if ( pExtension )
	{
		*pExtension = '\0';
	}

	V_snprintf( miscInfo, sizeof( miscInfo ), "skill %d", g_bug_mapInfo.skill );

	// Stuff bug data files up to server
	g_bug_pReporter->StartNewBugReport();

	g_bug_pReporter->SetOwner( g_bug_pReporter->GetUserNameForDisplayName( g_bug_szOwner ) );
	g_bug_pReporter->SetSubmitter( NULL );

	if ( mapName[0] )
		V_snprintf( title, sizeof( title ), "%s: %s", mapName, g_bug_szTitle );
	else
		V_snprintf( title, sizeof( title ), "%s", g_bug_szTitle );
	g_bug_pReporter->SetTitle( title );

	g_bug_pReporter->SetDescription( g_bug_szDescription );
	g_bug_pReporter->SetLevel( mapName );
	g_bug_pReporter->SetPosition( positionName );
	g_bug_pReporter->SetOrientation( orientationName );
	g_bug_pReporter->SetBuildNumber( buildName );

	g_bug_pReporter->SetSeverity( g_bug_szSeverity );
	g_bug_pReporter->SetPriority( g_bug_szPriority );
	g_bug_pReporter->SetArea( g_bug_szArea );
	g_bug_pReporter->SetMapNumber( g_bug_szMapNumber );
	g_bug_pReporter->SetReportType( g_bug_szReportType );
	g_bug_pReporter->SetMiscInfo( miscInfo );

	g_bug_pReporter->SetDriverInfo( "" );
	g_bug_pReporter->SetExeName( "" );
	g_bug_pReporter->SetGameDirectory( "" );
	g_bug_pReporter->SetRAM( 0 );
	g_bug_pReporter->SetCPU( 0 );
	g_bug_pReporter->SetProcessor( "" );
	g_bug_pReporter->SetDXVersion( 0, 0, 0, 0 );
	g_bug_pReporter->SetOSVersion( "" );
	g_bug_pReporter->ResetIncludedFiles();
	g_bug_pReporter->SetZipAttachmentName( "" );

	if ( g_bug_szScreenshot[0] )
	{
		if ( g_bug_bCompressScreenshot )
		{
			BugDlg_CompressScreenshot();
		}

		// strip the fully qualified path into filename only
		Sys_StripPath( g_bug_szScreenshot, basename, sizeof( basename ) );
		V_snprintf( filename, sizeof( filename ), "%s/BugId/%s", GetRepositoryURL(), basename );
		Sys_NormalizePath( filename, false );
		g_bug_pReporter->SetScreenShot( filename );
	}

	if ( g_bug_szSavegame[0] )
	{
		// strip the fully qualified path into filename only
		Sys_StripPath( g_bug_szSavegame, basename, sizeof( basename ) );
		V_snprintf( filename, sizeof( filename ), "%s/BugId/%s", GetRepositoryURL(), basename );
		Sys_NormalizePath( filename, false );
		g_bug_pReporter->SetSaveGame( filename );
	}

	if ( g_bug_szBSPName[0] )
	{
		// strip the fully qualified path into filename only
		Sys_StripPath( g_bug_szBSPName, basename, sizeof( basename ) );
		V_snprintf( filename, sizeof( filename ), "%s/BugId/%s", GetRepositoryURL(), basename );
		Sys_NormalizePath( filename, false );
		g_bug_pReporter->SetBSPName( filename );
	}
	
	int bugID = -1;

	bSuccess = g_bug_pReporter->CommitBugReport( bugID );
	if ( bSuccess )
	{
		if ( !BugDlg_UploadBugSubmission( bugID, g_bug_szSavegame, g_bug_szScreenshot, g_bug_szBSPName, NULL ) )
		{
			Sys_MessageBox( BUG_ERRORTITLE, "Unable to upload files to bug repository!\n" );
			bSuccess = false;
		}
	}
	else
	{
		Sys_MessageBox( BUG_ERRORTITLE, "Unable to post bug report to database!\n" );
	}

	if ( bSuccess )
	{
		if ( g_Games[g_bug_GameType].bUsesSystem1 )
		{
			ConsoleWindowPrintf( BUG_COLOR, "Bug Reporter: PVCS submission succeeded for bug! (%d)\n", bugID );
		}
		else
		{
			ConsoleWindowPrintf( BUG_COLOR, "Bug Reporter: BugBait submission succeeded for bug!\n" );
		}
	}
	else
	{
		ConsoleWindowPrintf( XBX_CLR_RED, "Bug Reporter: Submission failed\n" );
	}

	return bSuccess;
}
Exemple #26
0
	void CMultiplayRules::GetNextLevelName( char *pszNextMap, int bufsize, bool bRandom /* = false */ )
	{
		const char *mapcfile = mapcyclefile.GetString();
		Assert( mapcfile != NULL );

		// Check the time of the mapcycle file and re-populate the list of level names if the file has been modified
		const int nMapCycleTimeStamp = filesystem->GetPathTime( mapcfile, "GAME" );

		if ( 0 == nMapCycleTimeStamp )
		{
			// Map cycle file does not exist, make a list containing only the current map
			char *szCurrentMapName = new char[32];
			Q_strncpy( szCurrentMapName, STRING(gpGlobals->mapname), 32 );
			m_MapList.AddToTail( szCurrentMapName );
		}
		else
		{
			// If map cycle file has changed or this is the first time through ...
			if ( m_nMapCycleTimeStamp != nMapCycleTimeStamp )
			{
				// Reset map index and map cycle timestamp
				m_nMapCycleTimeStamp = nMapCycleTimeStamp;
				m_nMapCycleindex = 0;

				// Clear out existing map list. Not using Purge() because I don't think that it will do a 'delete []'
				for ( int i = 0; i < m_MapList.Count(); i++ )
				{
					delete [] m_MapList[i];
				}

				m_MapList.RemoveAll();

				// Repopulate map list from mapcycle file
				int nFileLength;
				char *aFileList = (char*)UTIL_LoadFileForMe( mapcfile, &nFileLength );
				if ( aFileList && nFileLength )
				{
					V_SplitString( aFileList, "\n", m_MapList );

					for ( int i = 0; i < m_MapList.Count(); i++ )
					{
						bool bIgnore = false;

						// Strip out the spaces in the name
						StripChar( m_MapList[i] , '\r');
						StripChar( m_MapList[i] , ' ');
						
						if ( !engine->IsMapValid( m_MapList[i] ) )
						{
							bIgnore = true;

							// If the engine doesn't consider it a valid map remove it from the lists
							char szWarningMessage[MAX_PATH];
							V_snprintf( szWarningMessage, MAX_PATH, "Invalid map '%s' included in map cycle file. Ignored.\n", m_MapList[i] );
							Warning( szWarningMessage );
						}
						else if ( !Q_strncmp( m_MapList[i], "//", 2 ) )
						{
							bIgnore = true;
						}

						if ( bIgnore )
						{
							delete [] m_MapList[i];
							m_MapList.Remove( i );
							--i;
						}
					}

					UTIL_FreeFile( (byte *)aFileList );
				}
			}
		}

		// If somehow we have no maps in the list then add the current one
		if ( 0 == m_MapList.Count() )
		{
			char *szDefaultMapName = new char[32];
			Q_strncpy( szDefaultMapName, STRING(gpGlobals->mapname), 32 );
			m_MapList.AddToTail( szDefaultMapName );
		}

		if ( bRandom )
		{
			m_nMapCycleindex = RandomInt( 0, m_MapList.Count() - 1 );
		}

		// Here's the return value
		Q_strncpy( pszNextMap, m_MapList[m_nMapCycleindex], bufsize);
	}
Exemple #27
0
char *V_pretifymem( float value, int digitsafterdecimal /*= 2*/, bool usebinaryonek /*= false*/ )
{
	static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ];
	static int  current;

	float		onekb = usebinaryonek ? 1024.0f : 1000.0f;
	float		onemb = onekb * onekb;

	char *out = output[ current ];
	current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 );

	char suffix[ 8 ];

	// First figure out which bin to use
	if ( value > onemb )
	{
		value /= onemb;
		V_snprintf( suffix, sizeof( suffix ), " MB" );
	}
	else if ( value > onekb )
	{
		value /= onekb;
		V_snprintf( suffix, sizeof( suffix ), " KB" );
	}
	else
	{
		V_snprintf( suffix, sizeof( suffix ), " bytes" );
	}

	char val[ 32 ];

	// Clamp to >= 0
	digitsafterdecimal = max( digitsafterdecimal, 0 );

	// If it's basically integral, don't do any decimals
	if ( FloatMakePositive( value - (int)value ) < 0.00001 )
	{
		V_snprintf( val, sizeof( val ), "%i%s", (int)value, suffix );
	}
	else
	{
		char fmt[ 32 ];

		// Otherwise, create a format string for the decimals
		V_snprintf( fmt, sizeof( fmt ), "%%.%if%s", digitsafterdecimal, suffix );
		V_snprintf( val, sizeof( val ), fmt, value );
	}

	// Copy from in to out
	char *i = val;
	char *o = out;

	// Search for decimal or if it was integral, find the space after the raw number
	char *dot = strstr( i, "." );
	if ( !dot )
	{
		dot = strstr( i, " " );
	}

	// Compute position of dot
	int pos = dot - i;
	// Don't put a comma if it's <= 3 long
	pos -= 3;

	while ( *i )
	{
		// If pos is still valid then insert a comma every third digit, except if we would be
		//  putting one in the first spot
		if ( pos >= 0 && !( pos % 3 ) )
		{
			// Never in first spot
			if ( o != out )
			{
				*o++ = ',';
			}
		}

		// Count down comma position
		pos--;

		// Copy rest of data as normal
		*o++ = *i++;
	}

	// Terminate
	*o = 0;

	return out;
}
IClient *CForwardManager::OnSpectatorConnect(netadr_t & address, int nProtocol, int iChallenge, int iClientChallenge, int nAuthProtocol, const char *pchName, const char *pchPassword, const char *pCookie, int cbCookie)
#endif
{
	if (!pCookie || (size_t)cbCookie < sizeof(uint64))
		RETURN_META_VALUE(MRES_IGNORED, nullptr);

#if SOURCE_ENGINE == SE_CSGO
	// CS:GO doesn't send the player name in pchName, but only in the client info convars.
	// Try to extract the name from the protobuf msg.
	char playerName[MAX_PLAYER_NAME_LENGTH];
	if (ExtractPlayerName(pSplitPlayerConnectVector, playerName, sizeof(playerName)))
		pchName = playerName;
#endif

	char ipString[16];
	V_snprintf(ipString, sizeof(ipString), "%u.%u.%u.%u", address.ip[0], address.ip[1], address.ip[2], address.ip[3]);
	V_strncpy(passwordBuffer, pchPassword, 255);

	// SourceTV doesn't validate steamids?!

	char rejectReason[255];

	m_SpectatorPreConnectFwd->PushString(pchName);
	m_SpectatorPreConnectFwd->PushStringEx(passwordBuffer, 255, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);
	m_SpectatorPreConnectFwd->PushString(ipString);
	m_SpectatorPreConnectFwd->PushStringEx(rejectReason, 255, SM_PARAM_STRING_UTF8 | SM_PARAM_STRING_COPY, SM_PARAM_COPYBACK);

	cell_t retVal = 1;
	m_SpectatorPreConnectFwd->Execute(&retVal);

	IServer *server = META_IFACEPTR(IServer);
	if (retVal == 0)
	{
		if (m_bHasRejectConnectionOffset)
		{
#if SOURCE_ENGINE == SE_CSGO || SOURCE_ENGINE == SE_LEFT4DEAD || SOURCE_ENGINE == SE_LEFT4DEAD2
			SH_MCALL(server, CHLTVServer_RejectConnection)(address, rejectReason);
#else
			SH_MCALL(server, CHLTVServer_RejectConnection)(address, iClientChallenge, rejectReason);
#endif
		}
		RETURN_META_VALUE(MRES_SUPERCEDE, nullptr);
	}

	// Call the original function.
#if SOURCE_ENGINE == SE_CSGO
	IClient *client = SH_MCALL(server, CHLTVServer_ConnectClient)(address, nProtocol, iChallenge, nAuthProtocol, pchName, passwordBuffer, pCookie, cbCookie, pSplitPlayerConnectVector, bUnknown, platform, pUnknown, iUnknown);
#elif SOURCE_ENGINE == SE_LEFT4DEAD || SOURCE_ENGINE == SE_LEFT4DEAD2
	IClient *client = SH_MCALL(server, CHLTVServer_ConnectClient)(address, nProtocol, iChallenge, nAuthProtocol, pchName, passwordBuffer, pCookie, cbCookie, pSplitPlayerConnectVector, bUnknown);
#else
	IClient *client = SH_MCALL(server, CHLTVServer_ConnectClient)(address, nProtocol, iChallenge, iClientChallenge, nAuthProtocol, pchName, passwordBuffer, pCookie, cbCookie);
#endif

	if (!client)
		RETURN_META_VALUE(MRES_SUPERCEDE, nullptr);

	HookClient(client);

	HLTVServerWrapper *wrapper = g_HLTVServers.GetWrapper(server);
	if (wrapper)
	{
		HLTVClientWrapper *clientWrapper = wrapper->GetClient(client->GetPlayerSlot() + 1);
		clientWrapper->Initialize(ipString, pchPassword, client);
	}

	m_SpectatorConnectedFwd->PushCell(client->GetPlayerSlot() + 1);
	m_SpectatorConnectedFwd->Execute();

	// Don't call the hooked function again, just return its value.
	RETURN_META_VALUE(MRES_SUPERCEDE, client);
}
Exemple #29
0
//---------------------------------------------------------------------------------
// This function will load libraries and return true if they load successfully.
//
//---------------------------------------------------------------------------------
void* SPLoadLibrary( IVEngineServer* engine, const char* libraryPath )
{
	DevMsg(1, MSG_PREFIX "Loading library: %s\n", libraryPath);
	char szFullPath[MAX_PATH_LENGTH];
	char szGamePath[MAX_PATH_LENGTH];
	char szError[MAX_PATH_LENGTH];
	V_strncpy(szError, "[SP-LOADER] - No error found\n", MAX_PATH_LENGTH);

	engine->GetGameDir(szGamePath, MAX_PATH_LENGTH);
	GenerateSymlink(szGamePath);

	V_snprintf(szFullPath, sizeof(szFullPath), "%s/addons/source-python/%s",
		szGamePath, libraryPath);

	// Fix up the slahes.
	V_FixSlashes(szFullPath);

#if defined(_WIN32)
	void* hModule = (void *)LoadLibrary(szFullPath);
	if (!hModule)
	{
		// I hate windows programming...
		DWORD nErrorCode = GetLastError();
		LPVOID lpMsgBuf;
		DWORD nBufferLength = FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_FROM_SYSTEM |
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			nErrorCode,
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
			(LPTSTR) &lpMsgBuf,
			0, NULL );

		if(nBufferLength == 0)

		{
			V_snprintf(szError, sizeof(szError),
			   "[SP-LOADER] Could not obtain a valid translation for error. (Code: %d)\n",
			   nErrorCode);
		}
		else
		{
			char szResult[MAX_ERROR_LENGTH];
			memset(szResult, '\0', MAX_ERROR_LENGTH);

			// Too lazy to bring across any windows functions, cast myself from wide to narrow
			for (unsigned int i=0; i < nBufferLength; ++i)
			{
				szResult[i] = static_cast<char>(static_cast<LPCSTR>(lpMsgBuf)[i]);
			}

			V_snprintf(szError, sizeof(szError),
			   "[SP-LOADER] (Code: %d) %s",
			   nErrorCode,
			   szResult/*.c_str()*/);

			LocalFree(lpMsgBuf);
		}
	}
#else
	void* hModule = (void *)dlopen(szFullPath, RTLD_NOW | RTLD_GLOBAL);
	if (!hModule)
	{
		V_snprintf(szError, sizeof(szError), "[SP-LOADER] Error Reported: %s\n",
			dlerror());
	}
#endif

	if( !hModule ) {
		Warning("=========================================================================\n");
		Warning("[SP-LOADER] Could not load library: %s\n", libraryPath);
		Warning(szError);
		Warning("=========================================================================\n");
		return hModule;
	}

	return hModule;
}
//-----------------------------------------------------------------------------
// Generate a tree containing files from a reslist.  Returns TRUE if successful.
//-----------------------------------------------------------------------------
bool LoadReslist( const char *pReslistName, CUtlRBTree< CUtlString, int > *pTree )
{
	CUtlBuffer buffer;
	if ( !scriptlib->ReadFileToBuffer( pReslistName, buffer, true ) )
	{
		return false;
	}

	char szBasename[MAX_PATH];
	V_FileBase( pReslistName, szBasename, sizeof( szBasename ) );

	characterset_t breakSet;
	CharacterSetBuild( &breakSet, "" );

	// parse reslist
	char szToken[MAX_PATH];
	char szBspName[MAX_PATH];
	szBspName[0] = '\0';
	for ( ;; )
	{
		int nTokenSize = buffer.ParseToken( &breakSet, szToken, sizeof( szToken ) );
		if ( nTokenSize <= 0 )
		{
			break;
		}

		// reslists are pc built, filenames can be sloppy
		V_strlower( szToken );
		V_FixSlashes( szToken );
		V_RemoveDotSlashes( szToken );

		// can safely cull filetypes that are ignored by queued loader at runtime
		bool bKeep = false;
		const char *pExt = V_GetFileExtension( szToken );
		if ( !pExt )
		{
			// unknown
			continue;
		}
		else if ( !V_stricmp( pExt, "vmt" ) || 
				!V_stricmp( pExt, "vhv" ) || 
				!V_stricmp( pExt, "mdl" ) || 
				!V_stricmp( pExt, "raw" ) || 
				!V_stricmp( pExt, "wav" ) )
		{
			bKeep = true;
		}
		else if ( !V_stricmp( pExt, "mp3" ) )
		{
			// change to .wav
			V_SetExtension( szToken, ".wav", sizeof( szToken ) );
			bKeep = true;
		}
		else if ( !V_stricmp( pExt, "bsp" ) )
		{
			// reslists erroneously have multiple bsps
			if ( !V_stristr( szToken, szBasename ) )
			{
				// wrong one, cull it
				continue;
			}
			else
			{
				// right one, save it
				strcpy( szBspName, szToken );
				bKeep = true;
			}
		}

		if ( bKeep )
		{
			FindOrAddFileToResourceList( szToken, pTree );
		}
	}

	if ( !szBspName[0] )
	{
		// reslist is not bsp derived, nothing more to do
		return true;
	}

	CUtlVector< CUtlString > bspList;
	bool bOK = GetDependants_BSP( szBspName, &bspList );
	if ( !bOK )
	{
		return false;
	}
	
	// add all the bsp dependants to the resource list
	for ( int i=0; i<bspList.Count(); i++ )
	{
		FindOrAddFileToResourceList( bspList[i].String(), pTree );
	}

	// iterate all the models in the resource list, get all their dependents
	CUtlVector< CUtlString > modelList;
	for ( int i = pTree->FirstInorder(); i != pTree->InvalidIndex(); i = pTree->NextInorder( i ) )
	{
		const char *pExt = V_GetFileExtension( pTree->Element( i ).String() );
		if ( !pExt || V_stricmp( pExt, "mdl" ) )
		{
			continue;
		}

		if ( !GetDependants_MDL( pTree->Element( i ).String(), &modelList ) )
		{
			return false;
		}
	}

	// add all the model dependents to the resource list
	for ( int i=0; i<modelList.Count(); i++ )
	{
		FindOrAddFileToResourceList( modelList[i].String(), pTree );
	}

	// check for optional commentary, include wav dependencies
	char szCommentaryName[MAX_PATH];
	V_ComposeFileName( g_szGamePath, szBspName, szCommentaryName, sizeof( szCommentaryName ) );
	V_StripExtension( szCommentaryName, szCommentaryName, sizeof( szCommentaryName ) );
	V_strncat( szCommentaryName, "_commentary.txt", sizeof( szCommentaryName ) );
	CUtlBuffer commentaryBuffer;
	if ( ReadFileToBuffer( szCommentaryName, commentaryBuffer, true, true ) )
	{
		// any single token may be quite large to due to text
		char szCommentaryToken[8192];
		for ( ;; )
		{
			int nTokenSize = commentaryBuffer.ParseToken( &breakSet, szCommentaryToken, sizeof( szCommentaryToken ) );
			if ( nTokenSize < 0 )
			{
				break;
			}
			if ( nTokenSize > 0 && !V_stricmp( szCommentaryToken, "commentaryfile" ) )
			{
				// get the commentary file
				nTokenSize = commentaryBuffer.ParseToken( &breakSet, szCommentaryToken, sizeof( szCommentaryToken ) );
				if ( nTokenSize > 0 )
				{
					// skip past sound chars
					char *pName = szCommentaryToken;
					while ( *pName && IsSoundChar( *pName ) )
					{
						pName++;
					}
					char szWavFile[MAX_PATH];
					V_snprintf( szWavFile, sizeof( szWavFile ), "sound/%s", pName );
					FindOrAddFileToResourceList( szWavFile, pTree );
				}
			}
		}
	}

	// check for optional blacklist
	char szBlacklist[MAX_PATH];
	V_ComposeFileName( g_szGamePath, "reslistfixes_xbox.xsc", szBlacklist, sizeof( szBlacklist ) );
	CUtlBuffer blacklistBuffer;
	if ( ReadFileToBuffer( szBlacklist, blacklistBuffer, true, true ) )
	{
		for ( ;; )
		{
			int nTokenSize = blacklistBuffer.ParseToken( &breakSet, szToken, sizeof( szToken ) );
			if ( nTokenSize <= 0 )
			{
				break;
			}

			bool bAdd;
			if ( !V_stricmp( szToken, "-" ) )
			{
				bAdd = false;
			}
			else if ( !V_stricmp( szToken, "+" ) )
			{
				bAdd = true;
			}
			else
			{
				// bad syntax, skip line
				Msg( "Bad Syntax, expecting '+' or '-' as first token in reslist fixup file '%s'.\n", szBlacklist );
				continue;
			}

			// get entry
			nTokenSize = blacklistBuffer.ParseToken( &breakSet, szToken, sizeof( szToken ) );
			if ( nTokenSize <= 0 )
			{
				break;
			}

			if ( bAdd )	
			{
				FindOrAddFileToResourceList( szToken, pTree );
			}
			else
			{
				RemoveFileFromResourceList( szToken, pTree );
			}
		}
	}

	return true;
}