//-----------------------------------------------------------------------------
// Get the preload data for a vvd file
//-----------------------------------------------------------------------------
bool GetPreloadData_VVD( const char *pFilename, CUtlBuffer &fileBufferIn, CUtlBuffer &preloadBufferOut )
{
	vertexFileHeader_t *pHeader = (vertexFileHeader_t *)fileBufferIn.Base();

	unsigned int id = BigLong( pHeader->id );
	unsigned int version = BigLong( pHeader->version );

	// ensure caller's buffer is clean
	// caller determines preload size, via TellMaxPut()
	preloadBufferOut.Purge();

	if ( id != MODEL_VERTEX_FILE_ID )
	{
		// bad version
		Msg( "Can't preload: '%s', expecting id %d got id %d\n", pFilename, MODEL_VERTEX_FILE_ID, id );
		return false;
	}

	if ( version != MODEL_VERTEX_FILE_VERSION )
	{
		// bad version
		Msg( "Can't preload: '%s', expecting version %d got version %d\n", pFilename, MODEL_VERTEX_FILE_VERSION, version );
		return false;
	}

	unsigned int nPreloadSize = sizeof( vertexFileHeader_t );

	preloadBufferOut.Put( fileBufferIn.Base(), nPreloadSize );

	return true;
}
Esempio n. 2
0
//-----------------------------------------------------------------------------
// Create binary compiled version of VCD. Stores to a dictionary for later
// post processing
//-----------------------------------------------------------------------------
bool CreateTargetFile_VCD( const char *pSourceName, const char *pTargetName, bool bWriteToZip, bool bLittleEndian )
{
	CUtlBuffer sourceBuf;
	if ( !scriptlib->ReadFileToBuffer( pSourceName, sourceBuf ) )
	{
		return false;
	}

	CRC32_t crcSource;
	CRC32_Init( &crcSource );
	CRC32_ProcessBuffer( &crcSource, sourceBuf.Base(), sourceBuf.TellMaxPut() );
	CRC32_Final( &crcSource );

	ParseFromMemory( (char *)sourceBuf.Base(), sourceBuf.TellMaxPut() );

	CChoreoScene *pChoreoScene = ChoreoLoadScene( pSourceName, NULL, &g_SceneTokenProcessor, Msg );
	if ( !pChoreoScene )
	{
		return false;
	}

	int iScene = g_SceneFiles.AddToTail();

	g_SceneFiles[iScene].fileName.Set( pSourceName );

	// Walk all events looking for SPEAK events
	CChoreoEvent *pEvent;
	for ( int i = 0; i < pChoreoScene->GetNumEvents(); ++i )
	{
		pEvent = pChoreoScene->GetEvent( i );
		FindSoundsInEvent( pEvent, g_SceneFiles[iScene].soundList );
	}

	// calc duration
	g_SceneFiles[iScene].msecs = (unsigned int)( pChoreoScene->FindStopTime() * 1000.0f + 0.5f );

	// compile to binary buffer
	g_SceneFiles[iScene].compiledBuffer.SetBigEndian( !bLittleEndian );
	pChoreoScene->SaveToBinaryBuffer( g_SceneFiles[iScene].compiledBuffer, crcSource, &g_ChoreoStringPool );

	unsigned int compressedSize;
	unsigned char *pCompressedBuffer = LZMA_Compress( (unsigned char *)g_SceneFiles[iScene].compiledBuffer.Base(), g_SceneFiles[iScene].compiledBuffer.TellMaxPut(), &compressedSize );
	if ( pCompressedBuffer )
	{
		// replace the compiled buffer with the compressed version
		g_SceneFiles[iScene].compiledBuffer.Purge();
		g_SceneFiles[iScene].compiledBuffer.EnsureCapacity( compressedSize );
		g_SceneFiles[iScene].compiledBuffer.Put( pCompressedBuffer, compressedSize );
		free( pCompressedBuffer );
	}

	delete pChoreoScene;

	return true;
}
Esempio n. 3
0
bool LoadFileIntoBuffer( const char *pFileName, CUtlBuffer &buf )
{
	struct	_stat statBuf;
	if( _stat( pFileName, &statBuf ) != 0 )
	{
		goto error;
	}

	buf.EnsureCapacity( statBuf.st_size );
	FILE *fp;
	fp = fopen( pFileName, "rb" );
	if( !fp )
	{
		goto error;
	}
	
	int nBytesRead = fread( buf.Base(), 1, statBuf.st_size, fp );
	fclose( fp );

	buf.SeekPut( CUtlBuffer::SEEK_HEAD, nBytesRead );
	return true;

error:
	printf( "Can't find file %s\n", pFileName );
	return false;
}
Esempio n. 4
0
bool LoadVTXFile( char const* pModelName, const studiohdr_t *pStudioHdr, CUtlBuffer& buf )
{
	char	filename[MAX_PATH];

	// construct filename
	Q_StripExtension( pModelName, filename, sizeof( filename ) );
	strcat( filename, g_bXBox ? ".xbox.vtx" : ".dx80.vtx" );

	if ( !LoadFile( filename, buf ) )
	{
		Warning( "Error! Unable to load file \"%s\"\n", filename );
		return false;
	}

	OptimizedModel::FileHeader_t* pVtxHdr = (OptimizedModel::FileHeader_t *)buf.Base();

	// Check that it's valid
	if ( pVtxHdr->version != OPTIMIZED_MODEL_FILE_VERSION )
	{
		Warning( "Error! Invalid VTX file version: %d, expected %d \"%s\"\n", pVtxHdr->version, OPTIMIZED_MODEL_FILE_VERSION, filename );
		return false;
	}
	if ( pVtxHdr->checkSum != pStudioHdr->checksum )
	{
		Warning( "Error! Invalid VTX file checksum: %d, expected %d \"%s\"\n", pVtxHdr->checkSum, pStudioHdr->checksum, filename );
		return false;
	}

	return true;
}
Esempio n. 5
0
bool CBaseGameStats::SaveToFileNOW( bool bForceSyncWrite /* = false */ )
{
	if ( !StatsTrackingIsFullyEnabled() )
		return false;

	// this code path is only for old format stats.  Products that use new format take a different path.
	if ( !gamestats->UseOldFormat() )
		return false;

	CUtlBuffer buf;
	buf.PutShort( GAMESTATS_FILE_VERSION );
	buf.Put( s_szPseudoUniqueID, 16 );

	if( ShouldTrackStandardStats() )
		m_BasicStats.SaveToBuffer( buf ); 
	else
		buf.PutInt( GAMESTATS_STANDARD_NOT_SAVED );

	gamestats->AppendCustomDataToSaveBuffer( buf );

	char fullpath[ 512 ] = { 0 };
	if ( filesystem->FileExists( GetStatSaveFileName(), GAMESTATS_PATHID ) )
	{
		filesystem->RelativePathToFullPath( GetStatSaveFileName(), GAMESTATS_PATHID, fullpath, sizeof( fullpath ) );
	}
	else
	{
		// filename is local to game dir for Steam, so we need to prepend game dir for regular file save
		char gamePath[256];
		engine->GetGameDir( gamePath, 256 );
		Q_StripTrailingSlash( gamePath );
		Q_snprintf( fullpath, sizeof( fullpath ), "%s/%s", gamePath, GetStatSaveFileName() );
		Q_strlower( fullpath );
		Q_FixSlashes( fullpath );
	}

	// StatsLog( "SaveToFileNOW '%s'\n", fullpath );

	if( CBGSDriver.m_bShuttingDown || bForceSyncWrite ) //write synchronously
	{
		filesystem->WriteFile( fullpath, GAMESTATS_PATHID, buf );

		StatsLog( "Shut down wrote to '%s'\n", fullpath );
	}
	else
	{
		// Allocate memory for async system to use (and free afterward!!!)
		size_t nBufferSize = buf.TellPut();
		void *pMem = malloc(nBufferSize);
		CUtlBuffer statsBuffer( pMem, nBufferSize );
		statsBuffer.Put( buf.Base(), nBufferSize );

		// Write data async
		filesystem->AsyncWrite( fullpath, statsBuffer.Base(), statsBuffer.TellPut(), true, false );
	}

	return true;
}
Esempio n. 6
0
CefRefPtr<CefResourceHandler> VTFSchemeHandlerFactory::Create(CefRefPtr<CefBrowser> browser,
											CefRefPtr<CefFrame> frame,
											const CefString& scheme_name,
											CefRefPtr<CefRequest> request)
{
	CefRefPtr<CefResourceHandler> pResourceHandler = NULL;

	CefURLParts parts;
	CefParseURL(request->GetURL(), parts);

	std::string strVtfPath = CefString(&parts.path);

	char vtfPath[MAX_PATH];
	V_snprintf( vtfPath, sizeof( vtfPath ), "materials/%s", strVtfPath.c_str() );
	V_FixupPathName( vtfPath, sizeof( vtfPath ), vtfPath );

	if (!filesystem->FileExists(vtfPath))
	{
		Warning( "VTFSchemeHandlerFactory: invalid vtf %s\n", vtfPath );
		return NULL;
	}

	CUtlBuffer imageDataBuffer( 0, filesystem->Size(vtfPath), 0 );
	if( !filesystem->ReadFile( vtfPath, NULL, imageDataBuffer ) ) 
	{
		Warning( "VTFSchemeHandlerFactory: failed to read vtf %s\n", vtfPath );
		return NULL;
	}

	IVTFTexture *pVTFTexture = CreateVTFTexture();
	if( pVTFTexture->Unserialize( imageDataBuffer ) )
	{
		pVTFTexture->ConvertImageFormat( IMAGE_FORMAT_RGB888, false, false );

		if( pVTFTexture->Format() == IMAGE_FORMAT_RGB888 )
		{
			uint8 *pImageData = pVTFTexture->ImageData();

			CUtlBuffer buf;
			VTFHandler_ConvertImageToJPG( buf, pImageData, pVTFTexture->Width(), pVTFTexture->Height() );

			if( buf.Size() > 0 )
			{
				CefRefPtr<CefStreamReader> stream =
					CefStreamReader::CreateForData(static_cast<void*>(buf.Base()), buf.Size());

				pResourceHandler = new CefStreamResourceHandler("image/jpeg", stream);
			}
		}
		else
		{
			Warning( "VTFSchemeHandlerFactory: unable to convert vtf %s to rgb format\n", vtfPath );
		}
	}
	DestroyVTFTexture( pVTFTexture );

	return pResourceHandler;
}
Esempio n. 7
0
bool AStar::Save(IFileSystem *filesystem, const char *Filename)
{
	CUtlBuffer buf;

	AStarNode *Node;
	NodeList_t Links;

	int TotalNumLinks = 0;
	int NodeTotal = Nodes.Count();

	//////////////////////////////////////////////
	// Nodes
	buf.PutInt(NodeTotal);

	for(int i = 0; i < NodeTotal; i++)
	{
		Node = Nodes[i];

		buf.PutFloat(Node->GetPos().x);
		buf.PutFloat(Node->GetPos().y);
		buf.PutFloat(Node->GetPos().z);

		TotalNumLinks += Node->GetLinks().Count();
	}
	//////////////////////////////////////////////

	//////////////////////////////////////////////
	// Links
	buf.PutInt(TotalNumLinks);

	for(int i = 0; i < NodeTotal; i++)
	{
		Node = Nodes[i];
		Links = Node->GetLinks();
		for(int li = 0; li < Links.Count(); li++)
		{
			buf.PutInt(Node->GetID());
			buf.PutInt(Links[li]->GetID());
		}
	}
	//////////////////////////////////////////////

	//////////////////////////////////////////////
	// Write File

	FileHandle_t fh = filesystem->Open(Filename, "wb");
	if(!fh)
	{
		return false;
	}

	filesystem->Write(buf.Base(), buf.TellPut(), fh);
	filesystem->Close(fh);
	//////////////////////////////////////////////

	return true;
}
//-----------------------------------------------------------------------------
// Does a texture have alpha?
//-----------------------------------------------------------------------------
static bool DoesTextureUseAlpha( const char *pTextureName, const char *pMaterialName )
{
	if ( IsX360() )
	{
		// not supporting
		return false;
	}

	// Special textures start with '_'..
	if ( pTextureName[0] == '_' )
		return false;

	// The texture name doubles as the relative file name
	// It's assumed to have already been set by this point	
	// Compute the cache name
	char pCacheFileName[MATERIAL_MAX_PATH];
	Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName );

	CUtlBuffer buf;
	FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" );
	if ( fileHandle == FILESYSTEM_INVALID_HANDLE)
	{
		Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName );
		return false;
	}

	// Check the .vtf for an alpha channel
	IVTFTexture *pVTFTexture = CreateVTFTexture();

	int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION );
	buf.EnsureCapacity( nHeaderSize );

	// read the header first.. it's faster!!
	g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle );
	buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize );

	// Unserialize the header
	bool bUsesAlpha = false;

	if (!pVTFTexture->Unserialize( buf, true ))
	{
		Warning( "Error reading material \"%s\"\n", pCacheFileName );
		g_pFullFileSystem->Close(fileHandle);
	}
	else
	{
		if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) )
		{
			bUsesAlpha = true;
		}
	}

	DestroyVTFTexture( pVTFTexture );
	g_pFullFileSystem->Close( fileHandle );
	return bUsesAlpha;
}
Esempio n. 9
0
bool CBaseGameStats::UploadStatsFileNOW( void )
{
	if( !StatsTrackingIsFullyEnabled() )
		return false;
	
	if ( !filesystem->FileExists( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID ) )
	{
		return false;
	}

	time_t curtime;
	VCRHook_Time( reinterpret_cast<long*>(&curtime) );

	// For now always send updates after every time they run the engine!!
#if 0
#if !defined( _DEBUG )
	int elapsed = curtime - m_tLastUpload;
	if ( elapsed < ONE_DAY_IN_SECONDS )
		return;
#endif
#endif

	CBGSDriver.m_tLastUpload = curtime;

	// Update the registry
#ifndef SWDS
	IRegistry *reg = InstanceRegistry( "Steam" );
	Assert( reg );
	reg->WriteInt( GetStatUploadRegistryKeyName(), CBGSDriver.m_tLastUpload );
	ReleaseInstancedRegistry( reg );
#endif

	CUtlBuffer buf;
	filesystem->ReadFile( GetStatSaveFileName(), GAMESTATS_PATHID, buf );
	unsigned int uBlobSize = buf.TellPut();
	if ( uBlobSize == 0 )
	{
		return false;
	}

	const void *pvBlobData = ( const void * )buf.Base();

	if( gamestatsuploader )
	{
		return gamestatsuploader->UploadGameStats( "",
												   1,
												   uBlobSize,
												   pvBlobData );
	}

	return false;
}
//-----------------------------------------------------------------------------
// Creates a collision model (based on the render geometry!)
//-----------------------------------------------------------------------------
void CVradStaticPropMgr::CreateCollisionModel( char const* pModelName )
{
	CUtlBuffer buf;
	CUtlBuffer bufvtx;
	CUtlBuffer bufphy;

	int i = m_StaticPropDict.AddToTail( );
	m_StaticPropDict[i].m_pModel = 0;

	if (!LoadStudioModel( pModelName, buf ))
	{
		VectorCopy( vec3_origin, m_StaticPropDict[i].m_Mins );
		VectorCopy( vec3_origin, m_StaticPropDict[i].m_Maxs );
		return;
	}

//	if (!LoadStudioModelVtx( pModelName, bufvtx ))
//		return;

	studiohdr_t* pHdr = (studiohdr_t*)buf.Base();
//	OptimizedModel::FileHeader_t* pVtxHdr = (OptimizedModel::FileHeader_t*)bufvtx.Base();

	VectorCopy( pHdr->hull_min, m_StaticPropDict[i].m_Mins );
	VectorCopy( pHdr->hull_max, m_StaticPropDict[i].m_Maxs );

	if ( LoadStudioCollisionModel( pModelName, bufphy ) )
	{
		phyheader_t header;
		bufphy.Get( &header, sizeof(header) );

		vcollide_t *pCollide = &m_StaticPropDict[i].m_loadedModel;
		s_pPhysCollision->VCollideLoad( pCollide, header.solidCount, (const char *)bufphy.PeekGet(), bufphy.TellPut() - bufphy.TellGet() );
		m_StaticPropDict[i].m_pModel = m_StaticPropDict[i].m_loadedModel.solids[0];

		/*
		static int propNum = 0;
		char tmp[128];
		sprintf( tmp, "staticprop%03d.txt", propNum );
		DumpCollideToGlView( pCollide, tmp );
		++propNum;
		*/
	}
	else
	{
		// mark this as unused
		m_StaticPropDict[i].m_loadedModel.solidCount = 0;

	//	CPhysCollide* pPhys = CreatePhysCollide( pHdr, pVtxHdr );
		m_StaticPropDict[i].m_pModel = ComputeConvexHull( pHdr );
	}
}
Esempio n. 11
0
//-----------------------------------------------------------------------------
// Get the preload data for a vhv file
//-----------------------------------------------------------------------------
bool GetPreloadData_VHV( const char *pFilename, CUtlBuffer &fileBufferIn, CUtlBuffer &preloadBufferOut )
{
	HardwareVerts::FileHeader_t *pHeader = (HardwareVerts::FileHeader_t *)fileBufferIn.Base();

	unsigned int version = BigLong( pHeader->m_nVersion );

	// ensure caller's buffer is clean
	// caller determines preload size, via TellMaxPut()
	preloadBufferOut.Purge();

	if ( version != VHV_VERSION )
	{
		// bad version
		Msg( "Can't preload: '%s', expecting version %d got version %d\n", pFilename, VHV_VERSION, version );
		return false;
	}

	unsigned int nPreloadSize = sizeof( HardwareVerts::FileHeader_t );

	preloadBufferOut.Put( fileBufferIn.Base(), nPreloadSize );

	return true;
}
Esempio n. 12
0
//-----------------------------------------------------------------------------
// Get the preload data for a vtx file
//-----------------------------------------------------------------------------
bool GetPreloadData_VTX( const char *pFilename, CUtlBuffer &fileBufferIn, CUtlBuffer &preloadBufferOut )
{
	OptimizedModel::FileHeader_t *pHeader = (OptimizedModel::FileHeader_t *)fileBufferIn.Base();

	unsigned int version = BigLong( pHeader->version );

	// ensure caller's buffer is clean
	// caller determines preload size, via TellMaxPut()
	preloadBufferOut.Purge();

	if ( version != OPTIMIZED_MODEL_FILE_VERSION )
	{
		// bad version
		Msg( "Can't preload: '%s', expecting version %d got version %d\n", pFilename, OPTIMIZED_MODEL_FILE_VERSION, version );
		return false;
	}

	unsigned int nPreloadSize = sizeof( OptimizedModel::FileHeader_t );

	preloadBufferOut.Put( fileBufferIn.Base(), nPreloadSize );

	return true;
}
bool CBaseVMPIFileSystem::WriteFile( const char *pFileName, const char *pPath, CUtlBuffer &buf )
{
	const char *pWriteFlags = "wb";
	if ( buf.IsText() && !buf.ContainsCRLF() )
	{
		pWriteFlags = "wt";
	}

	FileHandle_t fp = Open( pFileName, buf.IsText() ? "wt" : "wb", pPath );
	if ( !fp )
		return false;

	int nBytesWritten = Write( buf.Base(), buf.TellPut(), fp );

	Close( fp );
	return (nBytesWritten != 0);
}
//-----------------------------------------------------------------------------
// Purpose: Generate .360 compiled caption files
//-----------------------------------------------------------------------------
bool CreateTargetFile_CCDAT( const char *pSourceName, const char *pTargetName, bool bWriteToZip )
{
	CUtlBuffer targetBuffer;
	bool bOk = false;

	if ( !scriptlib->ReadFileToBuffer( pSourceName, targetBuffer ) )
	{
		return false;
	}

	if ( SwapClosecaptionFile( targetBuffer.Base() ) )
	{
		bOk = WriteBufferToFile( pTargetName, targetBuffer, bWriteToZip, g_WriteModeForConversions );
	}

	return bOk;
}
Esempio n. 15
0
// Assumed to be set up by calling code
bool AsyncCaption_t::LoadFromFile( const char *pRelativePath )
{
	char pRelativePathFixed[MAX_PATH];
	Q_strncpy( pRelativePathFixed, pRelativePath, sizeof(pRelativePathFixed) );
	Q_FixSlashes( pRelativePathFixed );
	Q_strlower( pRelativePathFixed );
	pRelativePath = pRelativePathFixed;

	if ( Q_IsAbsolutePath( pRelativePath ) )
	{
		Warning( "AsyncCaption_t::LoadFromFile: Fullpath encountered! %s\n", pRelativePath );
	}

	FileHandle_t fh = g_pFullFileSystem->Open( pRelativePath, "rb", "GAME" );
	if ( FILESYSTEM_INVALID_HANDLE == fh )
		return false;

	MEM_ALLOC_CREDIT();

	CUtlBuffer dirbuffer;

	// Read the header
	g_pFullFileSystem->Read( &m_Header, sizeof( m_Header ), fh );
	if ( m_Header.magic != COMPILED_CAPTION_FILEID )
		Error( "Invalid file id for %s\n", pRelativePath );
	if ( m_Header.version != COMPILED_CAPTION_VERSION )
		Error( "Invalid file version for %s\n", pRelativePath );
	if ( m_Header.directorysize < 0 || m_Header.directorysize > 64 * 1024 )
		Error( "Invalid directory size %d for %s\n", m_Header.directorysize, pRelativePath );
	//if ( m_Header.blocksize != MAX_BLOCK_SIZE )
	//	Error( "Invalid block size %d, expecting %d for %s\n", m_Header.blocksize, MAX_BLOCK_SIZE, pchFullPath );

	int directoryBytes = m_Header.directorysize * sizeof( CaptionLookup_t );
	m_CaptionDirectory.EnsureCapacity( m_Header.directorysize );
	dirbuffer.EnsureCapacity( directoryBytes );

	g_pFullFileSystem->Read( dirbuffer.Base(), directoryBytes, fh );
	g_pFullFileSystem->Close( fh );

	m_CaptionDirectory.CopyArray( (const CaptionLookup_t *)dirbuffer.PeekGet(), m_Header.directorysize );
	m_CaptionDirectory.RedoSort( true );

	m_DataBaseFile = pRelativePath;
	return true;
}
Esempio n. 16
0
bool CBaseGameStats::UploadStatsFileNOW( void )
{
	if( !StatsTrackingIsFullyEnabled() || !HaveValidData() || !gamestats->UseOldFormat() )
		return false;

	if ( !filesystem->FileExists( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID ) )
	{
		return false;
	}

	int curtime = Plat_FloatTime();

	CBGSDriver.m_tLastUpload = curtime;

	// Update the registry
#ifndef SWDS
	IRegistry *reg = InstanceRegistry( "Steam" );
	Assert( reg );
	reg->WriteInt( GetStatUploadRegistryKeyName(), CBGSDriver.m_tLastUpload );
	ReleaseInstancedRegistry( reg );
#endif

	CUtlBuffer buf;
	filesystem->ReadFile( GetStatSaveFileName(), GAMESTATS_PATHID, buf );
	unsigned int uBlobSize = buf.TellPut();
	if ( uBlobSize == 0 )
	{
		return false;
	}

	const void *pvBlobData = ( const void * )buf.Base();

	if( gamestatsuploader )
	{
		return gamestatsuploader->UploadGameStats( "",
												   1,
												   uBlobSize,
												   pvBlobData );
	}

	return false;
}
CRC32_t IFaceposerModels::CFacePoserModel::GetBitmapCRC( int sequence )
{
	CStudioHdr *hdr = m_pModel ? m_pModel->GetStudioHdr() : NULL;
	if ( !hdr )
		return (CRC32_t)-1;

	if ( sequence < 0 || sequence >= hdr->GetNumSeq() )
		return (CRC32_t)-1;

	mstudioseqdesc_t &seqdesc = hdr->pSeqdesc( sequence );

	CRC32_t crc;
	CRC32_Init( &crc );

	// For sequences, we'll checsum a bit of data

	CRC32_ProcessBuffer( &crc, (void *)seqdesc.pszLabel(), Q_strlen( seqdesc.pszLabel() ) );
	CRC32_ProcessBuffer( &crc, (void *)seqdesc.pszActivityName(), Q_strlen( seqdesc.pszActivityName() ) );
	CRC32_ProcessBuffer( &crc, (void *)&seqdesc.flags, sizeof( seqdesc.flags ) );
	//CRC32_ProcessBuffer( &crc, (void *)&seqdesc.numevents, sizeof( seqdesc.numevents ) );
	CRC32_ProcessBuffer( &crc, (void *)&seqdesc.numblends, sizeof( seqdesc.numblends ) );
	CRC32_ProcessBuffer( &crc, (void *)seqdesc.groupsize, sizeof( seqdesc.groupsize ) );

	KeyValues *seqKeyValues = new KeyValues("");
	if ( seqKeyValues->LoadFromBuffer( m_pModel->GetFileName( ), m_pModel->GetKeyValueText( sequence ) ) )
	{
		// Yuck, but I need it in a contiguous block of memory... oh well...
		CUtlBuffer buf;
		seqKeyValues->RecursiveSaveToFile( buf, 0 );
		CRC32_ProcessBuffer( &crc, ( void * )buf.Base(), buf.TellPut() );
	}

	seqKeyValues->deleteThis();

	CRC32_Final( &crc );

	return crc;
}
void CCompiledKeyValuesWriter::WriteStringTable( CUtlBuffer& buf )
{
	int i;
	CUtlVector< int >	offsets;

	CUtlBuffer stringBuffer;

	offsets.AddToTail( stringBuffer.TellPut() );

	stringBuffer.PutString( "" );
	// save all the rest
	int c = m_StringTable.GetNumStrings();
	for ( i = 1; i < c; i++)
	{
		offsets.AddToTail( stringBuffer.TellPut() );
		stringBuffer.PutString( m_StringTable.String( i ) );
	}

	buf.Put( offsets.Base(), offsets.Count() * sizeof( int ) );

	buf.PutInt( stringBuffer.TellPut() );
	buf.Put( stringBuffer.Base(), stringBuffer.TellPut() );
}
Esempio n. 19
0
//-----------------------------------------------------------------------------
// Unserialization
//-----------------------------------------------------------------------------
static void UnserializeModelDict( CUtlBuffer& buf )
{
	// Get origin offset for each model...
	int count = buf.GetInt();
	while ( --count >= 0 )
	{
		DetailObjectDictLump_t lump;
		buf.Get( &lump, sizeof(DetailObjectDictLump_t) );
		
		int i = g_ModelCenterOffset.AddToTail();

		CUtlBuffer mdlbuf;
		if (LoadStudioModel( lump.m_Name, mdlbuf ))
		{
			studiohdr_t* pHdr = (studiohdr_t*)mdlbuf.Base();
			VectorAdd( pHdr->hull_min, pHdr->hull_max, g_ModelCenterOffset[i] );
			g_ModelCenterOffset[i] *= 0.5f;
		}
		else
		{
			g_ModelCenterOffset[i].Init(0,0,0);
		}
	}
}
Esempio n. 20
0
void CViewRender::WriteSaveGameScreenshotOfSize( const char *pFilename, int width, int height, bool bCreatePowerOf2Padded/*=false*/,
												 bool bWriteVTF/*=false*/ )
{
#ifndef _X360
	CMatRenderContextPtr pRenderContext( materials );
	pRenderContext->MatrixMode( MATERIAL_PROJECTION );
	pRenderContext->PushMatrix();
	
	pRenderContext->MatrixMode( MATERIAL_VIEW );
	pRenderContext->PushMatrix();

	g_bRenderingScreenshot = true;

	// Push back buffer on the stack with small viewport
	pRenderContext->PushRenderTargetAndViewport( NULL, 0, 0, width, height );

	// render out to the backbuffer
    CViewSetup viewSetup = GetView ( STEREO_EYE_MONO );
	viewSetup.x = 0;
	viewSetup.y = 0;
	viewSetup.width = width;
	viewSetup.height = height;
	viewSetup.fov = ScaleFOVByWidthRatio( viewSetup.fov, ( (float)width / (float)height ) / ( 4.0f / 3.0f ) );
	viewSetup.m_bRenderToSubrectOfLargerScreen = true;

	// draw out the scene
	// Don't draw the HUD or the viewmodel
	RenderView( viewSetup, VIEW_CLEAR_DEPTH | VIEW_CLEAR_COLOR, 0 );

	// get the data from the backbuffer and save to disk
	// bitmap bits
	unsigned char *pImage = ( unsigned char * )malloc( width * height * 3 );

	// Get Bits from the material system
	pRenderContext->ReadPixels( 0, 0, width, height, pImage, IMAGE_FORMAT_RGB888 );

	// Some stuff to be setup dependent on padded vs. not padded
	int nSrcWidth, nSrcHeight;
	unsigned char *pSrcImage;

	// Create a padded version if necessary
	unsigned char *pPaddedImage = NULL;
	if ( bCreatePowerOf2Padded )
	{
		// Setup dimensions as needed
		int nPaddedWidth = SmallestPowerOfTwoGreaterOrEqual( width );
		int nPaddedHeight = SmallestPowerOfTwoGreaterOrEqual( height );

		// Allocate
		int nPaddedImageSize = nPaddedWidth * nPaddedHeight * 3;
		pPaddedImage = ( unsigned char * )malloc( nPaddedImageSize );
		
		// Zero out the entire thing
		V_memset( pPaddedImage, 255, nPaddedImageSize );

		// Copy over each row individually
		for ( int nRow = 0; nRow < height; ++nRow )
		{
			unsigned char *pDst = pPaddedImage + 3 * ( nRow * nPaddedWidth );
			const unsigned char *pSrc = pImage + 3 * ( nRow * width );
			V_memcpy( pDst, pSrc, 3 * width );
		}

		// Setup source data
		nSrcWidth = nPaddedWidth;
		nSrcHeight = nPaddedHeight;
		pSrcImage = pPaddedImage;
	}
	else
	{
		// Use non-padded info
		nSrcWidth = width;
		nSrcHeight = height;
		pSrcImage = pImage;
	}

	// allocate a buffer to write the tga into
	CUtlBuffer buffer;

	bool bWriteResult;
	if ( bWriteVTF )
	{
		// Create and initialize a VTF texture
		IVTFTexture *pVTFTexture = CreateVTFTexture();
		const int nFlags = TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_NOLOD | TEXTUREFLAGS_SRGB;
		if ( pVTFTexture->Init( nSrcWidth, nSrcHeight, 1, IMAGE_FORMAT_RGB888, nFlags, 1, 1 ) )
		{
			// Copy the image data over to the VTF
			unsigned char *pDestBits = pVTFTexture->ImageData();
			int nDstSize = nSrcWidth * nSrcHeight * 3;
			V_memcpy( pDestBits, pSrcImage, nDstSize );

			// Allocate output buffer
			int iMaxVTFSize = 1024 + ( nSrcWidth * nSrcHeight * 3 );
			void *pVTF = malloc( iMaxVTFSize );
			buffer.SetExternalBuffer( pVTF, iMaxVTFSize, 0 );

			// Serialize to the buffer
			bWriteResult = pVTFTexture->Serialize( buffer );
		
			// Free the VTF texture
			DestroyVTFTexture( pVTFTexture );
		}
		else
		{
			bWriteResult = false;
		}
	}
	else
	{
		// Write TGA format to buffer
		int iMaxTGASize = 1024 + ( nSrcWidth * nSrcHeight * 4 );
		void *pTGA = malloc( iMaxTGASize );
		buffer.SetExternalBuffer( pTGA, iMaxTGASize, 0 );

		bWriteResult = TGAWriter::WriteToBuffer( pSrcImage, buffer, nSrcWidth, nSrcHeight, IMAGE_FORMAT_RGB888, IMAGE_FORMAT_RGB888 );
	}

	if ( !bWriteResult )
	{
		Error( "Couldn't write bitmap data snapshot.\n" );
	}
	
	free( pImage );
	free( pPaddedImage );

	// async write to disk (this will take ownership of the memory)
	char szPathedFileName[_MAX_PATH];
	Q_snprintf( szPathedFileName, sizeof(szPathedFileName), "//MOD/%s", pFilename );

	filesystem->AsyncWrite( szPathedFileName, buffer.Base(), buffer.TellPut(), true );

	// restore our previous state
	pRenderContext->PopRenderTargetAndViewport();
	
	pRenderContext->MatrixMode( MATERIAL_PROJECTION );
	pRenderContext->PopMatrix();
	
	pRenderContext->MatrixMode( MATERIAL_VIEW );
	pRenderContext->PopMatrix();

	g_bRenderingScreenshot = false;
#endif
}
Esempio n. 21
0
bool C_ASW_Medal_Store::SaveMedalStore()
{
	if ( !m_bLoaded )
		return false;

	KeyValues *kv = new KeyValues( "CLIENTDAT" );
	
	// output missions/campaigns/kills
	kv->SetInt("MC", m_iMissionsCompleted);
	kv->SetInt("CC", m_iCampaignsCompleted);
	kv->SetInt("AK", m_iAliensKilled);

	kv->SetInt("OMC", m_iOfflineMissionsCompleted);
	kv->SetInt("OCC", m_iOfflineCampaignsCompleted);
	kv->SetInt("OAK", m_iOfflineAliensKilled);

	kv->SetInt( "LPL", m_iXP );
	kv->SetInt( "LPP", m_iPromotion );
	
	KeyValues *pSubSection = new KeyValues("NEWEQUIP");
	char buffer[64];
	if (pSubSection)
	{
		for (int i=0;i<m_NewEquipment.Count();i++)
		{			
			pSubSection->SetInt( "EQUIP", m_NewEquipment[i]);
		}
		kv->AddSubKey(pSubSection);
	}	

	// output player medals
	pSubSection = new KeyValues("LP");
	if (pSubSection)
	{
		for (int i=0;i<m_PlayerMedals.Count();i++)
		{			
			Q_snprintf(buffer, sizeof(buffer), "M%d", i);
			pSubSection->SetInt(buffer, m_PlayerMedals[i]);
		}
		kv->AddSubKey(pSubSection);
	}	

	for (int k=0;k<ASW_NUM_MARINE_PROFILES;k++)
	{
		Q_snprintf(buffer, sizeof(buffer), "LA%d", k);
		pSubSection = new KeyValues(buffer);
		if (pSubSection)
		{			
			for (int i=0;i<m_MarineMedals[k].Count();i++)
			{
				Q_snprintf(buffer, sizeof(buffer), "M%d", i);
				pSubSection->SetInt(buffer, m_MarineMedals[k][i]);				
			}
			kv->AddSubKey(pSubSection);
		}		
	}

	// offline medal store
	pSubSection = new KeyValues("FP");
	if (pSubSection)
	{
		for (int i=0;i<m_OfflinePlayerMedals.Count();i++)
		{			
			Q_snprintf(buffer, sizeof(buffer), "M%d", i);
			pSubSection->SetInt(buffer, m_OfflinePlayerMedals[i]);
		}
		kv->AddSubKey(pSubSection);
	}	

	for (int k=0;k<ASW_NUM_MARINE_PROFILES;k++)
	{
		Q_snprintf(buffer, sizeof(buffer), "FA%d", k);
		pSubSection = new KeyValues(buffer);
		if (pSubSection)
		{			
			for (int i=0;i<m_OfflineMarineMedals[k].Count();i++)
			{
				Q_snprintf(buffer, sizeof(buffer), "M%d", i);
				pSubSection->SetInt(buffer, m_OfflineMarineMedals[k][i]);				
			}
			kv->AddSubKey(pSubSection);
		}		
	}

	CUtlBuffer buf; //( 0, 0, CUtlBuffer::TEXT_BUFFER );
	kv->RecursiveSaveToFile( buf, 0 );

	// pad buffer with zeroes to make a multiple of 8
	int nExtra = buf.TellPut() % 8;
	while ( nExtra != 0 && nExtra < 8 )
	{
		buf.PutChar( 0 );
		nExtra++;
	}
	UTIL_EncodeICE( (unsigned char*) buf.Base(), buf.TellPut(), g_ucMedalStoreEncryptionKey );

	ISteamUser *pSteamUser = steamapicontext ? steamapicontext->SteamUser() : NULL;
	if ( !pSteamUser )
		return false;

	char szMedalFile[ 256 ];
	Q_snprintf( szMedalFile, sizeof( szMedalFile ), "cfg/clientc_%I64u.dat", pSteamUser->GetSteamID().ConvertToUint64() );
	int len = Q_strlen( szMedalFile );
	for ( int i = 0; i < len; i++ )
	{
		if ( szMedalFile[ i ] == ':' )
			szMedalFile[i] = '_';
	}

	bool bResult = filesystem->WriteFile( szMedalFile, "MOD", buf );
	if ( bResult )
	{
	#if defined(NO_STEAM)
		AssertMsg( false, "SteamCloud not available." );
	#else
		ISteamRemoteStorage *pRemoteStorage = SteamClient() ? ( ISteamRemoteStorage * )SteamClient()->GetISteamGenericInterface(
			SteamAPI_GetHSteamUser(), SteamAPI_GetHSteamPipe(), STEAMREMOTESTORAGE_INTERFACE_VERSION ) : NULL;

		if ( asw_steam_cloud.GetBool() && pRemoteStorage )
		{
			WriteFileToRemoteStorage( pRemoteStorage, "PersistentMarines.dat", szMedalFile );
		}
	#endif
	}

	return bResult;
}
Esempio n. 22
0
void CreateDefaultCubemaps( bool bHDR )
{
	memset( g_IsCubemapTexData, 0, sizeof(g_IsCubemapTexData) );

	// NOTE: This implementation depends on the fact that all VTF files contain
	// all mipmap levels
	const char *pSkyboxBaseName = FindSkyboxMaterialName();
	char skyboxMaterialName[MAX_PATH];
	Q_snprintf( skyboxMaterialName, MAX_PATH, "skybox/%s", pSkyboxBaseName );

	IVTFTexture *pSrcVTFTextures[6];

	if( !skyboxMaterialName )
	{
		if( s_DefaultCubemapNames.Count() )
		{
			Warning( "This map uses env_cubemap, and you don't have a skybox, so no default env_cubemaps will be generated.\n" );
		}
		return;
	}

	int unionTextureFlags = 0;
	if( !LoadSrcVTFFiles( pSrcVTFTextures, skyboxMaterialName, &unionTextureFlags, bHDR ) )
	{
		Warning( "Can't load skybox file %s to build the default cubemap!\n", skyboxMaterialName );
		return;
	}
	Msg( "Creating default %scubemaps for env_cubemap using skybox materials:\n   %s*.vmt\n"
		" ! Run buildcubemaps in the engine to get the correct cube maps.\n", bHDR ? "HDR " : "LDR ", skyboxMaterialName );
			
	// Figure out the mip differences between the two textures
	int iMipLevelOffset = 0;
	int tmp = pSrcVTFTextures[0]->Width();
	while( tmp > DEFAULT_CUBEMAP_SIZE )
	{
		iMipLevelOffset++;
		tmp >>= 1;
	}

	// Create the destination cubemap
	IVTFTexture *pDstCubemap = CreateVTFTexture();
	pDstCubemap->Init( DEFAULT_CUBEMAP_SIZE, DEFAULT_CUBEMAP_SIZE, 1,
		pSrcVTFTextures[0]->Format(), unionTextureFlags | TEXTUREFLAGS_ENVMAP, 
		pSrcVTFTextures[0]->FrameCount() );

	// First iterate over all frames
	for (int iFrame = 0; iFrame < pDstCubemap->FrameCount(); ++iFrame)
	{
		// Next iterate over all normal cube faces (we know there's 6 cause it's an envmap)
		for (int iFace = 0; iFace < 6; ++iFace )
		{
			// Finally, iterate over all mip levels in the *destination*
			for (int iMip = 0; iMip < pDstCubemap->MipCount(); ++iMip )
			{
				// Copy the bits from the source images into the cube faces
				unsigned char *pSrcBits = pSrcVTFTextures[iFace]->ImageData( iFrame, 0, iMip + iMipLevelOffset );
				unsigned char *pDstBits = pDstCubemap->ImageData( iFrame, iFace, iMip );
				int iSize = pDstCubemap->ComputeMipSize( iMip );
				int iSrcMipSize = pSrcVTFTextures[iFace]->ComputeMipSize( iMip + iMipLevelOffset );

				// !!! FIXME: Set this to black until HDR cubemaps are built properly!
				memset( pDstBits, 0, iSize );
				continue;

				if ( ( pSrcVTFTextures[iFace]->Width() == 4 ) && ( pSrcVTFTextures[iFace]->Height() == 4 ) ) // If texture is 4x4 square
				{
					// Force mip level 2 to get the 1x1 face
					unsigned char *pSrcBits = pSrcVTFTextures[iFace]->ImageData( iFrame, 0, 2 );
					int iSrcMipSize = pSrcVTFTextures[iFace]->ComputeMipSize( 2 );

					// Replicate 1x1 mip level across entire face
					//memset( pDstBits, 0, iSize ); 
					for ( int i = 0; i < ( iSize / iSrcMipSize ); i++ )
					{
						memcpy( pDstBits + ( i * iSrcMipSize ), pSrcBits, iSrcMipSize ); 
					}
				}
				else if ( pSrcVTFTextures[iFace]->Width() == pSrcVTFTextures[iFace]->Height() ) // If texture is square
				{
					if ( iSrcMipSize != iSize )
					{
						Warning( "%s - ERROR! Cannot copy square face for default cubemap! iSrcMipSize(%d) != iSize(%d)\n", skyboxMaterialName, iSrcMipSize, iSize );
						memset( pDstBits, 0, iSize );
					}
					else
					{
						// Just copy the mip level
						memcpy( pDstBits, pSrcBits, iSize ); 
					}
				}
				else if ( pSrcVTFTextures[iFace]->Width() == pSrcVTFTextures[iFace]->Height()*2 ) // If texture is rectangle 2x wide
				{
					int iMipWidth, iMipHeight, iMipDepth;
					pDstCubemap->ComputeMipLevelDimensions( iMip, &iMipWidth, &iMipHeight, &iMipDepth );
					if ( ( iMipHeight > 1 ) && ( iSrcMipSize*2 != iSize ) )
					{
						Warning( "%s - ERROR building default cube map! %d*2 != %d\n", skyboxMaterialName, iSrcMipSize, iSize );
						memset( pDstBits, 0, iSize );
					}
					else
					{
						// Copy row at a time and repeat last row
						memcpy( pDstBits, pSrcBits, iSize/2 ); 
						//memcpy( pDstBits + iSize/2, pSrcBits, iSize/2 );
						int nSrcRowSize = pSrcVTFTextures[iFace]->RowSizeInBytes( iMip + iMipLevelOffset );
						int nDstRowSize = pDstCubemap->RowSizeInBytes( iMip );
						if ( nSrcRowSize != nDstRowSize )
						{
							Warning( "%s - ERROR building default cube map! nSrcRowSize(%d) != nDstRowSize(%d)!\n", skyboxMaterialName, nSrcRowSize, nDstRowSize );
							memset( pDstBits, 0, iSize );
						}
						else
						{
							for ( int i = 0; i < ( iSize/2 / nSrcRowSize ); i++ )
							{
								memcpy( pDstBits + iSize/2 + i*nSrcRowSize, pSrcBits + iSrcMipSize - nSrcRowSize, nSrcRowSize );
							}
						}
					}
				}
				else
				{
					// ERROR! This code only supports square and rectangluar 2x wide
					Warning( "%s - Couldn't create default cubemap because texture res is %dx%d\n", skyboxMaterialName, pSrcVTFTextures[iFace]->Width(), pSrcVTFTextures[iFace]->Height() );
					memset( pDstBits, 0, iSize );
					return;
				}
			}
		}
	}

	ImageFormat originalFormat = pDstCubemap->Format();
	if( !bHDR )
	{
		// Convert the cube to format that we can apply tools to it...
		pDstCubemap->ConvertImageFormat( IMAGE_FORMAT_DEFAULT, false );
	}

	// Fixup the cubemap facing
	pDstCubemap->FixCubemapFaceOrientation();

	// Now that the bits are in place, compute the spheremaps...
	pDstCubemap->GenerateSpheremap();

	if( !bHDR )
	{
		// Convert the cubemap to the final format
		pDstCubemap->ConvertImageFormat( originalFormat, false );
	}

	// Write the puppy out!
	char dstVTFFileName[1024];
	if( bHDR )
	{
		sprintf( dstVTFFileName, "materials/maps/%s/cubemapdefault.hdr.vtf", mapbase );
	}
	else
	{
		sprintf( dstVTFFileName, "materials/maps/%s/cubemapdefault.vtf", mapbase );
	}

	CUtlBuffer outputBuf;
	if (!pDstCubemap->Serialize( outputBuf ))
	{
		Warning( "Error serializing default cubemap %s\n", dstVTFFileName );
		return;
	}

	IZip *pak = GetPakFile();

	// spit out the default one.
	AddBufferToPak( pak, dstVTFFileName, outputBuf.Base(), outputBuf.TellPut(), false );

	// spit out all of the ones that are attached to world geometry.
	int i;
	for( i = 0; i < s_DefaultCubemapNames.Count(); i++ )
	{
		char vtfName[MAX_PATH];
		VTFNameToHDRVTFName( s_DefaultCubemapNames[i], vtfName, MAX_PATH, bHDR );
		if( FileExistsInPak( pak, vtfName ) )
		{
			continue;
		}
		AddBufferToPak( pak, vtfName, outputBuf.Base(),outputBuf.TellPut(), false );
	}

	// Clean up the textures
	for( i = 0; i < 6; i++ )
	{
		DestroyVTFTexture( pSrcVTFTextures[i] );
	}
	DestroyVTFTexture( pDstCubemap );
}	
void CCompileCaptionsApp::CompileCaptionFile( char const *infile, char const *outfile )
{
	StringIndex_t maxindex = (StringIndex_t)-1;
	int maxunicodesize = 0;
	int totalsize = 0;

	int c = 0;

	int curblock = 0;
	int usedBytes = 0;
	int blockSize = MAX_BLOCK_SIZE;

	int freeSpace = 0;

	CUtlVector< CaptionLookup_t >	directory;
	CUtlBuffer data;

	CUtlRBTree< unsigned int >	hashcollision( 0, 0, DefLessFunc( unsigned int ) );

	for ( StringIndex_t i = g_pVGuiLocalize->GetFirstStringIndex(); i != INVALID_LOCALIZE_STRING_INDEX; i = g_pVGuiLocalize->GetNextStringIndex( i ), ++c )
	{
		char const *entryName = g_pVGuiLocalize->GetNameByIndex( i );
		CaptionLookup_t entry;
		entry.SetHash( entryName );
		
		// 	vprint( 0, "%d / %d:  %s == %u\n", c, i, g_pVGuiLocalize->GetNameByIndex( i ), entry.hash );

		if ( hashcollision.Find( entry.hash ) != hashcollision.InvalidIndex() )
		{
			Error( "Hash name collision on %s!!!\n", g_pVGuiLocalize->GetNameByIndex( i ) );
		}

		hashcollision.Insert( entry.hash );

		const wchar_t *text = g_pVGuiLocalize->GetValueByIndex( i );
		if ( verbose )
		{
			vprint( 0, "Processing: '%30.30s' = '%S'\n", entryName, text );
		}
		int len = text ? ( wcslen( text ) + 1 ) * sizeof( short ) : 0;
		if ( len > maxunicodesize )
		{
			maxindex = i;
			maxunicodesize = len;
		}

		if ( len > blockSize )
		{
			Error( "Caption text file '%s' contains a single caption '%s' of %d bytes (%d is max), change MAX_BLOCK_SIZE in captioncompiler.h to fix!!!\n", g_pVGuiLocalize->GetNameByIndex( i ),
				entryName, len, blockSize );
		}
		totalsize += len;

		if ( usedBytes + len >= blockSize )
		{
			++curblock;

			int leftover = ( blockSize - usedBytes );

			totalsize += leftover;

            freeSpace += leftover;

			while ( --leftover >= 0 )
			{
				data.PutChar( 0 );
			}

			usedBytes = len;
			entry.offset = 0;

			data.Put( (const void *)text, len );
		}
		else
		{
			entry.offset = usedBytes;
			usedBytes += len;
			data.Put( (const void *)text, len );
		}

		entry.length = len;
		entry.blockNum = curblock;

		directory.AddToTail( entry );
	}
	
	int leftover = ( blockSize - usedBytes );
	totalsize += leftover;
	freeSpace += leftover;
	while ( --leftover >= 0 )
	{
		data.PutChar( 0 );
	}

	vprint( 0, "Found %i strings in '%s'\n", c, infile );

	if ( maxindex != INVALID_LOCALIZE_STRING_INDEX )
	{
		vprint( 0, "Longest string '%s' = (%i) bytes average(%.3f)\n%",
			g_pVGuiLocalize->GetNameByIndex( maxindex ), maxunicodesize, (float)totalsize/(float)c );
	}

	vprint( 0, "%d blocks (%d bytes each), %d bytes wasted (%.3f per block average), total bytes %d\n",
		curblock + 1, blockSize, freeSpace, (float)freeSpace/(float)( curblock + 1 ), totalsize );

	vprint( 0, "directory size %d entries, %d bytes, data size %d bytes\n",
		directory.Count(), directory.Count() * sizeof( CaptionLookup_t ), data.TellPut() );

	CompiledCaptionHeader_t header;
	header.magic			= COMPILED_CAPTION_FILEID;
	header.version			= COMPILED_CAPTION_VERSION;
	header.numblocks		= curblock + 1;
	header.blocksize		= blockSize;
	header.directorysize	= directory.Count();
	header.dataoffset		= 0;

	// Now write the outfile
	CUtlBuffer out;
	out.Put( &header, sizeof( header ) );
	out.Put( directory.Base(), directory.Count() * sizeof( CaptionLookup_t ) );
	int curOffset = out.TellPut();
	// Round it up to the next 512 byte boundary
	int nBytesDestBuffer = AlignValue( curOffset, 512 );  // align to HD sector
	int nPadding = nBytesDestBuffer - curOffset;
	while ( --nPadding >= 0 )
	{
		out.PutChar( 0 );
	}
	out.Put( data.Base(), data.TellPut() );

	// Write out a corrected header
	header.dataoffset = nBytesDestBuffer;
	int savePos = out.TellPut();
	out.SeekPut( CUtlBuffer::SEEK_HEAD, 0 );
	out.Put( &header, sizeof( header ) );
	out.SeekPut( CUtlBuffer::SEEK_HEAD, savePos );

	g_pFullFileSystem->WriteFile( outfile, NULL, out );

	// Jeep: this function no longer exisits
	/*if ( bX360 )
	{
		UpdateOrCreateCaptionFile_X360( g_pFullFileSystem, outfile, NULL, true );
	}*/
}
Esempio n. 24
0
//----------------------------------------------------------------------
// Get list of files that a model requires.
//----------------------------------------------------------------------
bool GetDependants_MDL( const char *pModelName, CUtlVector< CUtlString > *pList )
{
	if ( !g_bModPathIsValid )
	{
		Msg( "Indeterminate mod path, Cannot perform BSP conversion\n" );
		return false;
	}

	CUtlBuffer sourceBuf;
	if ( !g_pFullFileSystem->ReadFile( pModelName, "GAME", sourceBuf ) )
	{
		Msg( "Error! Couldn't open file '%s'!\n", pModelName ); 
		return false;
	}

	studiohdr_t *pStudioHdr = (studiohdr_t *)sourceBuf.Base();
	Studio_ConvertStudioHdrToNewVersion( pStudioHdr );
	if ( pStudioHdr->version != STUDIO_VERSION )
	{
		Msg( "Error! Bad Model '%s', Expecting Version (%d), got (%d)\n", pModelName, STUDIO_VERSION, pStudioHdr->version ); 
		return false;
	}

	char szOutName[MAX_PATH];
	if ( pStudioHdr->flags & STUDIOHDR_FLAGS_OBSOLETE )
	{
		V_strncpy( szOutName, "materials/sprites/obsolete.vmt", sizeof( szOutName ) );
		V_FixSlashes( szOutName );
		pList->AddToTail( szOutName );
	}
	else if ( pStudioHdr->textureindex != 0 )
	{
		// iterate each texture
		int	i;
		int	j;
		for ( i = 0; i < pStudioHdr->numtextures; i++ )
		{
			// iterate through all directories until a valid material is found
			bool bFound = false;
			for ( j = 0; j < pStudioHdr->numcdtextures; j++ )
			{
				char szPath[MAX_PATH];
				V_ComposeFileName( "materials", pStudioHdr->pCdtexture( j ), szPath, sizeof( szPath ) );

				// should have been fixed in studiomdl
				// some mdls are ending up with double slashes, borking loads
				int len = strlen( szPath );
				if ( len > 2 && szPath[len-2] == '\\' && szPath[len-1] == '\\' )
				{
					szPath[len-1] = '\0';
				}
			
				V_ComposeFileName( szPath, pStudioHdr->pTexture( i )->pszName(), szOutName, sizeof( szOutName ) ); 
				V_SetExtension( szOutName, ".vmt", sizeof( szOutName ) );

				if ( g_pFullFileSystem->FileExists( szOutName, "GAME" ) )
				{
					bFound = true;
					break;
				}
			}

			if ( bFound )
			{
				pList->AddToTail( szOutName );
			}
		}
	}
	
	return true;
}
Esempio n. 25
0
//-----------------------------------------------------------------------------
// Rebuilds all of a MDL's components.
//-----------------------------------------------------------------------------
static bool GenerateModelFiles( const char *pMdlFilename )
{
	CUtlBuffer	tempBuffer;
	int			fileSize;
	int			paddedSize;
	int			swappedSize;

	// .mdl
	CUtlBuffer mdlBuffer;
	if ( !scriptlib->ReadFileToBuffer( pMdlFilename, mdlBuffer ) )
	{
		return false;
	}
	if ( !Studio_ConvertStudioHdrToNewVersion( (studiohdr_t *)mdlBuffer.Base() ))
	{
		Msg("%s needs to be recompiled\n", pMdlFilename );
	}

	// .vtx
	char szVtxFilename[MAX_PATH];
	V_StripExtension( pMdlFilename, szVtxFilename, sizeof( szVtxFilename ) );
	V_strncat( szVtxFilename, ".dx90.vtx", sizeof( szVtxFilename ) );
	CUtlBuffer vtxBuffer;
	bool bHasVtx = ReadFileToBuffer( szVtxFilename, vtxBuffer, false, true );
	
	// .vvd
	char szVvdFilename[MAX_PATH];
	V_StripExtension( pMdlFilename, szVvdFilename, sizeof( szVvdFilename ) );
	V_strncat( szVvdFilename, ".vvd", sizeof( szVvdFilename ) );
	CUtlBuffer vvdBuffer;
	bool bHasVvd = ReadFileToBuffer( szVvdFilename, vvdBuffer, false, true );

	if ( bHasVtx != bHasVvd )
	{
		// paired resources, either mandates the other
		return false;
	}

	// a .mdl file that has .vtx/.vvd gets re-processed to cull lod data
	if ( bHasVtx && bHasVvd )
	{
		// cull lod if needed
		IMdlStripInfo *pStripInfo = NULL;
		bool bResult = mdllib->StripModelBuffers( mdlBuffer, vvdBuffer, vtxBuffer, &pStripInfo );
		if ( !bResult )
		{
			return false;
		}
		if ( pStripInfo )
		{
			// .vsi
			CUtlBuffer vsiBuffer;
			pStripInfo->Serialize( vsiBuffer );
			pStripInfo->DeleteThis();

			// save strip info for later processing
			char szVsiFilename[MAX_PATH];
			V_StripExtension( pMdlFilename, szVsiFilename, sizeof( szVsiFilename ) );
			V_strncat( szVsiFilename, ".vsi", sizeof( szVsiFilename ) );
			WriteBufferToFile( szVsiFilename, vsiBuffer, false, WRITE_TO_DISK_ALWAYS );
		}
	}

	// .ani processing may further update .mdl buffer
	char szAniFilename[MAX_PATH];
	V_StripExtension( pMdlFilename, szAniFilename, sizeof( szAniFilename ) );
	V_strncat( szAniFilename, ".ani", sizeof( szAniFilename ) );
	CUtlBuffer aniBuffer;
	bool bHasAni = ReadFileToBuffer( szAniFilename, aniBuffer, false, true );
	if ( bHasAni )
	{
		// Some vestigal .ani files exist in the tree, only process valid .ani
		if ( ((studiohdr_t*)mdlBuffer.Base())->numanimblocks != 0 )
		{
			// .ani processing modifies .mdl buffer
			fileSize = aniBuffer.TellPut();
			paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING;
			aniBuffer.EnsureCapacity( paddedSize );
			tempBuffer.EnsureCapacity( paddedSize );
			V_StripExtension( pMdlFilename, szAniFilename, sizeof( szAniFilename ) );
			V_strncat( szAniFilename, ".360.ani", sizeof( szAniFilename ) );
			swappedSize = StudioByteSwap::ByteswapStudioFile( szAniFilename, tempBuffer.Base(), aniBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc );
			if ( swappedSize > 0 )
			{
				// .ani buffer is replaced with swapped data
				aniBuffer.Purge();
				aniBuffer.Put( tempBuffer.Base(), swappedSize );
				WriteBufferToFile( szAniFilename, aniBuffer, false, WRITE_TO_DISK_ALWAYS );
			}
			else
			{
				return false;				
			}
		}
	}

	// .phy
	char szPhyFilename[MAX_PATH];
	V_StripExtension( pMdlFilename, szPhyFilename, sizeof( szPhyFilename ) );
	V_strncat( szPhyFilename, ".phy", sizeof( szPhyFilename ) );
	CUtlBuffer phyBuffer;
	bool bHasPhy = ReadFileToBuffer( szPhyFilename, phyBuffer, false, true );
	if ( bHasPhy )
	{
		fileSize = phyBuffer.TellPut();
		paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING;
		phyBuffer.EnsureCapacity( paddedSize );
		tempBuffer.EnsureCapacity( paddedSize );
		V_StripExtension( pMdlFilename, szPhyFilename, sizeof( szPhyFilename ) );
		V_strncat( szPhyFilename, ".360.phy", sizeof( szPhyFilename ) );
		swappedSize = StudioByteSwap::ByteswapStudioFile( szPhyFilename, tempBuffer.Base(), phyBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc );
		if ( swappedSize > 0 )
		{
			// .phy buffer is replaced with swapped data
			phyBuffer.Purge();
			phyBuffer.Put( tempBuffer.Base(), swappedSize );
			WriteBufferToFile( szPhyFilename, phyBuffer, false, WRITE_TO_DISK_ALWAYS );
		}
		else
		{
			return false;				
		}
	}

	if ( bHasVtx )
	{
		fileSize = vtxBuffer.TellPut();
		paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING;
		vtxBuffer.EnsureCapacity( paddedSize );
		tempBuffer.EnsureCapacity( paddedSize );
		V_StripExtension( pMdlFilename, szVtxFilename, sizeof( szVtxFilename ) );
		V_strncat( szVtxFilename, ".dx90.360.vtx", sizeof( szVtxFilename ) );
		swappedSize = StudioByteSwap::ByteswapStudioFile( szVtxFilename, tempBuffer.Base(), vtxBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc );
		if ( swappedSize > 0 )
		{
			// .vtx buffer is replaced with swapped data
			vtxBuffer.Purge();
			vtxBuffer.Put( tempBuffer.Base(), swappedSize );
			WriteBufferToFile( szVtxFilename, vtxBuffer, false, WRITE_TO_DISK_ALWAYS );
		}
		else
		{
			return false;				
		}
	}

	if ( bHasVvd )
	{
		fileSize = vvdBuffer.TellPut();
		paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING;
		vvdBuffer.EnsureCapacity( paddedSize );
		tempBuffer.EnsureCapacity( paddedSize );
		V_StripExtension( pMdlFilename, szVvdFilename, sizeof( szVvdFilename ) );
		V_strncat( szVvdFilename, ".360.vvd", sizeof( szVvdFilename ) );
		swappedSize = StudioByteSwap::ByteswapStudioFile( szVvdFilename, tempBuffer.Base(), vvdBuffer.PeekGet(), fileSize, (studiohdr_t*)mdlBuffer.Base(), CompressFunc );
		if ( swappedSize > 0 )
		{
			// .vvd buffer is replaced with swapped data
			vvdBuffer.Purge();
			vvdBuffer.Put( tempBuffer.Base(), swappedSize );
			WriteBufferToFile( szVvdFilename, vvdBuffer, false, WRITE_TO_DISK_ALWAYS );
		}
		else
		{
			return false;				
		}
	}

	// swap and write final .mdl
	fileSize = mdlBuffer.TellPut();
	paddedSize = fileSize + BYTESWAP_ALIGNMENT_PADDING;
	mdlBuffer.EnsureCapacity( paddedSize );
	tempBuffer.EnsureCapacity( paddedSize );
	char szMdlFilename[MAX_PATH];
	V_StripExtension( pMdlFilename, szMdlFilename, sizeof( szMdlFilename ) );
	V_strncat( szMdlFilename, ".360.mdl", sizeof( szMdlFilename ) );
	swappedSize = StudioByteSwap::ByteswapStudioFile( szMdlFilename, tempBuffer.Base(), mdlBuffer.PeekGet(), fileSize, NULL, CompressFunc );
	if ( swappedSize > 0 )
	{
		// .mdl buffer is replaced with swapped data
		mdlBuffer.Purge();
		mdlBuffer.Put( tempBuffer.Base(), swappedSize );
		WriteBufferToFile( szMdlFilename, mdlBuffer, false, WRITE_TO_DISK_ALWAYS );
	}
	else
	{
		return false;				
	}

	return true;
}
Esempio n. 26
0
int main( int argc, char **argv )
{
	SpewOutputFunc( VTF2TGAOutputFunc );
	CommandLine()->CreateCmdLine( argc, argv );
	MathLib_Init( 2.2f, 2.2f, 0.0f, 1.0f, false, false, false, false );
	InitDefaultFileSystem();

	const char *pVTFFileName = CommandLine()->ParmValue( "-i" );
	const char *pTGAFileName = CommandLine()->ParmValue( "-o" );
	bool bGenerateMipLevels = CommandLine()->CheckParm( "-mip" ) != NULL;
	if ( !pVTFFileName )
	{
		Usage();
	}

	if ( !pTGAFileName )
	{
		pTGAFileName = pVTFFileName;
	}

	char pCurrentDirectory[MAX_PATH];
	if ( _getcwd( pCurrentDirectory, sizeof(pCurrentDirectory) ) == NULL )
	{
		fprintf( stderr, "Unable to get the current directory\n" );
		return -1;
	}
	Q_StripTrailingSlash( pCurrentDirectory );

	char pBuf[MAX_PATH];
	if ( !Q_IsAbsolutePath( pTGAFileName ) )
	{
		Q_snprintf( pBuf, sizeof(pBuf), "%s\\%s", pCurrentDirectory, pTGAFileName );
	}
	else
	{
		Q_strncpy( pBuf, pTGAFileName, sizeof(pBuf) );
	}
	Q_FixSlashes( pBuf );

	char pOutFileNameBase[MAX_PATH];
	Q_StripExtension( pBuf, pOutFileNameBase, MAX_PATH );

	char pActualVTFFileName[MAX_PATH];
	Q_strncpy( pActualVTFFileName, pVTFFileName, MAX_PATH );
	if ( !Q_strstr( pActualVTFFileName, ".vtf" ) )
	{
		Q_strcat( pActualVTFFileName, ".vtf", MAX_PATH ); 
	}

	FILE *vtfFp = fopen( pActualVTFFileName, "rb" );
	if( !vtfFp )
	{
		Error( "Can't open %s\n", pActualVTFFileName );
		exit( -1 );
	}

	fseek( vtfFp, 0, SEEK_END );
	int srcVTFLength = ftell( vtfFp );
	fseek( vtfFp, 0, SEEK_SET );

	CUtlBuffer buf;
	buf.EnsureCapacity( srcVTFLength );
	int nBytesRead = fread( buf.Base(), 1, srcVTFLength, vtfFp );
	fclose( vtfFp );
	buf.SeekPut( CUtlBuffer::SEEK_HEAD, nBytesRead );

	IVTFTexture *pTex = CreateVTFTexture();
	if (!pTex->Unserialize( buf ))
	{
		Error( "*** Error reading in .VTF file %s\n", pActualVTFFileName );
		exit(-1);
	}
	
	Msg( "vtf width: %d\n", pTex->Width() );
	Msg( "vtf height: %d\n", pTex->Height() );
	Msg( "vtf numFrames: %d\n", pTex->FrameCount() );

	Msg( "TEXTUREFLAGS_POINTSAMPLE=%s\n", ( pTex->Flags() & TEXTUREFLAGS_POINTSAMPLE ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_TRILINEAR=%s\n", ( pTex->Flags() & TEXTUREFLAGS_TRILINEAR ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_CLAMPS=%s\n", ( pTex->Flags() & TEXTUREFLAGS_CLAMPS ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_CLAMPT=%s\n", ( pTex->Flags() & TEXTUREFLAGS_CLAMPT ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_CLAMPU=%s\n", ( pTex->Flags() & TEXTUREFLAGS_CLAMPU ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_BORDER=%s\n", ( pTex->Flags() & TEXTUREFLAGS_BORDER ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_ANISOTROPIC=%s\n", ( pTex->Flags() & TEXTUREFLAGS_ANISOTROPIC ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_HINT_DXT5=%s\n", ( pTex->Flags() & TEXTUREFLAGS_HINT_DXT5 ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_SRGB=%s\n", ( pTex->Flags() & TEXTUREFLAGS_SRGB ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_NORMAL=%s\n", ( pTex->Flags() & TEXTUREFLAGS_NORMAL ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_NOMIP=%s\n", ( pTex->Flags() & TEXTUREFLAGS_NOMIP ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_NOLOD=%s\n", ( pTex->Flags() & TEXTUREFLAGS_NOLOD ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_ALL_MIPS=%s\n", ( pTex->Flags() & TEXTUREFLAGS_ALL_MIPS ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_PROCEDURAL=%s\n", ( pTex->Flags() & TEXTUREFLAGS_PROCEDURAL ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_ONEBITALPHA=%s\n", ( pTex->Flags() & TEXTUREFLAGS_ONEBITALPHA ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_EIGHTBITALPHA=%s\n", ( pTex->Flags() & TEXTUREFLAGS_EIGHTBITALPHA ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_ENVMAP=%s\n", ( pTex->Flags() & TEXTUREFLAGS_ENVMAP ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_RENDERTARGET=%s\n", ( pTex->Flags() & TEXTUREFLAGS_RENDERTARGET ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_DEPTHRENDERTARGET=%s\n", ( pTex->Flags() & TEXTUREFLAGS_DEPTHRENDERTARGET ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_NODEBUGOVERRIDE=%s\n", ( pTex->Flags() & TEXTUREFLAGS_NODEBUGOVERRIDE ) ? "true" : "false" );
	Msg( "TEXTUREFLAGS_SINGLECOPY=%s\n", ( pTex->Flags() & TEXTUREFLAGS_SINGLECOPY ) ? "true" : "false" );
	
	Vector vecReflectivity = pTex->Reflectivity();
	Msg( "vtf reflectivity: %f %f %f\n", vecReflectivity[0], vecReflectivity[1], vecReflectivity[2] );
	Msg( "transparency: " );
	if( pTex->Flags() & TEXTUREFLAGS_EIGHTBITALPHA )
	{
		Msg( "eightbitalpha\n" );
	}
	else if( pTex->Flags() & TEXTUREFLAGS_ONEBITALPHA )
	{
		Msg( "onebitalpha\n" );
	}
	else
	{
		Msg( "noalpha\n" );
	}
	ImageFormat srcFormat = pTex->Format();
	Msg( "vtf format: %s\n", ImageLoader::GetName( srcFormat ) );
		
	int iTGANameLen = Q_strlen( pOutFileNameBase );

	int iFaceCount = pTex->FaceCount();
	int nFrameCount = pTex->FrameCount();
	bool bIsCubeMap = pTex->IsCubeMap();

	int iLastMipLevel = bGenerateMipLevels ? pTex->MipCount() - 1 : 0;
	for( int iFrame = 0; iFrame < nFrameCount; ++iFrame )
	{
		for ( int iMipLevel = 0; iMipLevel <= iLastMipLevel; ++iMipLevel )
		{
			int iWidth, iHeight, iDepth;
			pTex->ComputeMipLevelDimensions( iMipLevel, &iWidth, &iHeight, &iDepth );

			for (int iCubeFace = 0; iCubeFace < iFaceCount; ++iCubeFace)
			{
				for ( int z = 0; z < iDepth; ++z )
				{
					// Construct output filename
					char *pTempNameBuf = (char *)stackalloc( iTGANameLen + 13 );
					Q_strncpy( pTempNameBuf, pOutFileNameBase, iTGANameLen + 1 );
					char *pExt = Q_strrchr( pTempNameBuf, '.' );
					if ( pExt )
					{
						pExt = 0;
					}

					if ( bIsCubeMap )
					{
						Assert( pTex->Depth() == 1 ); // shouldn't this be 1 instead of 0?
						static const char *pCubeFaceName[7] = { "rt", "lf", "bk", "ft", "up", "dn", "sph" };
						Q_strcat( pTempNameBuf, pCubeFaceName[iCubeFace], iTGANameLen + 13 ); 
					}

					if ( nFrameCount > 1 )
					{
						char pTemp[4];
						Q_snprintf( pTemp, 4, "%03d", iFrame );
						Q_strcat( pTempNameBuf, pTemp, iTGANameLen + 13 ); 
					}

					if ( iLastMipLevel != 0 )
					{
						char pTemp[8];
						Q_snprintf( pTemp, 8, "_mip%d", iMipLevel );
						Q_strcat( pTempNameBuf, pTemp, iTGANameLen + 13 ); 
					}

					if ( pTex->Depth() > 1 )
					{
						char pTemp[6];
						Q_snprintf( pTemp, 6, "_z%03d", z );
						Q_strcat( pTempNameBuf, pTemp, iTGANameLen + 13 ); 
					}

					if( srcFormat == IMAGE_FORMAT_RGBA16161616F )
					{
						Q_strcat( pTempNameBuf, ".pfm", iTGANameLen + 13 ); 
					}
					else
					{
						Q_strcat( pTempNameBuf, ".tga", iTGANameLen + 13 ); 
					}

					unsigned char *pSrcImage = pTex->ImageData( iFrame, iCubeFace, iMipLevel, 0, 0, z );

					ImageFormat dstFormat;
					if( srcFormat == IMAGE_FORMAT_RGBA16161616F )
					{
						dstFormat = IMAGE_FORMAT_RGB323232F;
					}
					else
					{
						if( ImageLoader::IsTransparent( srcFormat ) || (srcFormat == IMAGE_FORMAT_ATI1N ) || (srcFormat == IMAGE_FORMAT_ATI2N ))
						{
							dstFormat = IMAGE_FORMAT_BGRA8888;
						}
						else
						{
							dstFormat = IMAGE_FORMAT_BGR888;
						}
					}
				//	dstFormat = IMAGE_FORMAT_RGBA8888;
				//	dstFormat = IMAGE_FORMAT_RGB888;
				//	dstFormat = IMAGE_FORMAT_BGRA8888;
				//	dstFormat = IMAGE_FORMAT_BGR888;
				//	dstFormat = IMAGE_FORMAT_BGRA5551;
				//	dstFormat = IMAGE_FORMAT_BGR565;
				//	dstFormat = IMAGE_FORMAT_BGRA4444;
				//	printf( "dstFormat: %s\n", ImageLoader::GetName( dstFormat ) );
					unsigned char *pDstImage = new unsigned char[ImageLoader::GetMemRequired( iWidth, iHeight, 1, dstFormat, false )];
					if( !ImageLoader::ConvertImageFormat( pSrcImage, srcFormat, 
						pDstImage, dstFormat, iWidth, iHeight, 0, 0 ) )
					{
						Error( "Error converting from %s to %s\n",
							ImageLoader::GetName( srcFormat ), ImageLoader::GetName( dstFormat ) );
						exit( -1 );
					}

					if( dstFormat != IMAGE_FORMAT_RGB323232F )
					{
						if( ImageLoader::IsTransparent( dstFormat ) && ( dstFormat != IMAGE_FORMAT_RGBA8888 ) )
						{
							unsigned char *tmpImage = pDstImage;
							pDstImage = new unsigned char[ImageLoader::GetMemRequired( iWidth, iHeight, 1, IMAGE_FORMAT_RGBA8888, false )];
							if( !ImageLoader::ConvertImageFormat( tmpImage, dstFormat, pDstImage, IMAGE_FORMAT_RGBA8888,
								iWidth, iHeight, 0, 0 ) )
							{
								Error( "Error converting from %s to %s\n",
									ImageLoader::GetName( dstFormat ), ImageLoader::GetName( IMAGE_FORMAT_RGBA8888 ) );
							}
							dstFormat = IMAGE_FORMAT_RGBA8888;
						}
						else if( !ImageLoader::IsTransparent( dstFormat ) && ( dstFormat != IMAGE_FORMAT_RGB888 ) )
						{
							unsigned char *tmpImage = pDstImage;
							pDstImage = new unsigned char[ImageLoader::GetMemRequired( iWidth, iHeight, 1, IMAGE_FORMAT_RGB888, false )];
							if( !ImageLoader::ConvertImageFormat( tmpImage, dstFormat, pDstImage, IMAGE_FORMAT_RGB888,
								iWidth, iHeight, 0, 0 ) )
							{
								Error( "Error converting from %s to %s\n",
									ImageLoader::GetName( dstFormat ), ImageLoader::GetName( IMAGE_FORMAT_RGB888 ) );
							}
							dstFormat = IMAGE_FORMAT_RGB888;
						}

						CUtlBuffer outBuffer;
						TGAWriter::WriteToBuffer( pDstImage, outBuffer, iWidth, iHeight,
							dstFormat, dstFormat );
						if ( !g_pFullFileSystem->WriteFile( pTempNameBuf, NULL, outBuffer ) )
						{
							fprintf( stderr, "unable to write %s\n", pTempNameBuf );
						}
					}
					else
					{
						PFMWrite( ( float * )pDstImage, pTempNameBuf, iWidth, iHeight );
					}
				}
			}
		}
	}

	// leak leak leak leak leak, leak leak, leak leak (Blue Danube)
	return 0;
}
Esempio n. 27
0
HSCRIPT VScriptCompileScript( const char *pszScriptName, bool bWarnMissing )
{
    if ( !g_pScriptVM )
    {
        return NULL;
    }

    static const char *pszExtensions[] =
    {
        "",		// SL_NONE
        ".gm",	// SL_GAMEMONKEY
        ".nut",	// SL_SQUIRREL
        ".lua", // SL_LUA
        ".py",  // SL_PYTHON
    };

    const char *pszVMExtension = pszExtensions[g_pScriptVM->GetLanguage()];
    const char *pszIncomingExtension = V_strrchr( pszScriptName , '.' );
    if ( pszIncomingExtension && V_strcmp( pszIncomingExtension, pszVMExtension ) != 0 )
    {
        Log_Warning( LOG_VScript, "Script file type does not match VM type\n" );
        return NULL;
    }

    CFmtStr scriptPath;
    if ( pszIncomingExtension )
    {
        scriptPath.sprintf( "scripts/vscripts/%s", pszScriptName );
    }
    else
    {
        scriptPath.sprintf( "scripts/vscripts/%s%s", pszScriptName,  pszVMExtension );
    }

    const char *pBase;
    CUtlBuffer bufferScript;

    if ( g_pScriptVM->GetLanguage() == SL_PYTHON )
    {
        // python auto-loads raw or precompiled modules - don't load data here
        pBase = NULL;
    }
    else
    {
        bool bResult = filesystem->ReadFile( scriptPath, "GAME", bufferScript );

        if( !bResult )
        {
            Log_Warning( LOG_VScript, "Script not found (%s) \n", scriptPath.operator const char *() );
            Assert( "Error running script" );
        }

        pBase = (const char *) bufferScript.Base();

        if ( !pBase || !*pBase )
        {
            return NULL;
        }
    }


    const char *pszFilename = V_strrchr( scriptPath, '/' );
    pszFilename++;
    HSCRIPT hScript = g_pScriptVM->CompileScript( pBase, pszFilename );
    if ( !hScript )
    {
        Log_Warning( LOG_VScript, "FAILED to compile and execute script file named %s\n", scriptPath.operator const char *() );
        Assert( "Error running script" );
    }
    return hScript;
}
Esempio n. 28
0
void VMPI_DistributeLightData()
{
	if ( !g_bUseMPI )
		return;

	if ( g_bMPIMaster )
	{
		const char *pVirtualFilename = "--plightdata--";
		
		CUtlBuffer lightFaceData;

		// write out the light data
		lightFaceData.EnsureCapacity( pdlightdata->Count() + (numfaces * (MAXLIGHTMAPS+sizeof(int))) );
		Q_memcpy( lightFaceData.PeekPut(), pdlightdata->Base(), pdlightdata->Count() );
		lightFaceData.SeekPut( CUtlBuffer::SEEK_HEAD, pdlightdata->Count() );

		// write out the relevant face info into the stream
		for ( int i = 0; i < numfaces; i++ )
		{
			for ( int j = 0; j < MAXLIGHTMAPS; j++ )
			{
				lightFaceData.PutChar(g_pFaces[i].styles[j]);
			}
			lightFaceData.PutInt(g_pFaces[i].lightofs);
		}
		VMPI_FileSystem_CreateVirtualFile( pVirtualFilename, lightFaceData.Base(), lightFaceData.TellMaxPut() );

		char cPacketID[2] = { VMPI_VRAD_PACKET_ID, VMPI_SUBPACKETID_PLIGHTDATA_RESULTS };
		VMPI_Send2Chunks( cPacketID, sizeof( cPacketID ), pVirtualFilename, strlen( pVirtualFilename ) + 1, VMPI_PERSISTENT );
	}
	else
	{
		VMPI_SetCurrentStage( "VMPI_DistributeLightData" );

		// Wait until we've received the filename from the master.
		while ( g_LightResultsFilename.Count() == 0 )
		{
			VMPI_DispatchNextMessage();
		}

		// Open 
		FileHandle_t fp = g_pFileSystem->Open( g_LightResultsFilename.Base(), "rb", VMPI_VIRTUAL_FILES_PATH_ID );
		if ( !fp )
			Error( "Can't open '%s' to read lighting info.", g_LightResultsFilename.Base() );

		int size = g_pFileSystem->Size( fp );
		int faceSize = (numfaces*(MAXLIGHTMAPS+sizeof(int)));

		if ( size > faceSize )
		{
			int lightSize = size - faceSize;
			CUtlBuffer faceData;
			pdlightdata->EnsureCount( lightSize );
			faceData.EnsureCapacity( faceSize );

			g_pFileSystem->Read( pdlightdata->Base(), lightSize, fp );
			g_pFileSystem->Read( faceData.Base(), faceSize, fp );
			g_pFileSystem->Close( fp );

			faceData.SeekPut( CUtlBuffer::SEEK_HEAD, faceSize );

			// write out the face data
			for ( int i = 0; i < numfaces; i++ )
			{
				for ( int j = 0; j < MAXLIGHTMAPS; j++ )
				{
					g_pFaces[i].styles[j] = faceData.GetChar();
				}
				g_pFaces[i].lightofs = faceData.GetInt();
			}
		}
	}
}
Esempio n. 29
0
void CreateDefaultCubemaps( bool bHDR )
{
	memset( g_IsCubemapTexData, 0, sizeof(g_IsCubemapTexData) );

	// NOTE: This implementation depends on the fact that all VTF files contain
	// all mipmap levels
	const char *pSkyboxBaseName = FindSkyboxMaterialName();
	char skyboxMaterialName[MAX_PATH];
	Q_snprintf( skyboxMaterialName, MAX_PATH, "skybox/%s", pSkyboxBaseName );

	IVTFTexture *pSrcVTFTextures[6];

	if( !skyboxMaterialName )
	{
		if( s_DefaultCubemapNames.Count() )
		{
			Warning( "This map uses env_cubemap, and you don't have a skybox, so no default env_cubemaps will be generated.\n" );
		}
		return;
	}

	int unionTextureFlags = 0;
	if( !LoadSrcVTFFiles( pSrcVTFTextures, skyboxMaterialName, &unionTextureFlags, bHDR ) )
	{
		Warning( "Can't load skybox file %s to build the default cubemap!\n", skyboxMaterialName );
		return;
	}
	Msg( "Creating default %scubemaps for env_cubemap using skybox materials:\n%s*.vmt\n"
		"Run buildcubemaps in the engine to get the correct cube maps.\n\n", bHDR ? "HDR " : "", skyboxMaterialName );
			
	// Figure out the mip differences between the two textures
	int iMipLevelOffset = 0;
	int tmp = pSrcVTFTextures[0]->Width();
	while( tmp > DEFAULT_CUBEMAP_SIZE )
	{
		iMipLevelOffset++;
		tmp >>= 1;
	}

	// Create the destination cubemap
	IVTFTexture *pDstCubemap = CreateVTFTexture();
	pDstCubemap->Init( DEFAULT_CUBEMAP_SIZE, DEFAULT_CUBEMAP_SIZE, 1,
		pSrcVTFTextures[0]->Format(), unionTextureFlags | TEXTUREFLAGS_ENVMAP, 
		pSrcVTFTextures[0]->FrameCount() );

	// First iterate over all frames
	for (int iFrame = 0; iFrame < pDstCubemap->FrameCount(); ++iFrame)
	{
		// Next iterate over all normal cube faces (we know there's 6 cause it's an envmap)
		for (int iFace = 0; iFace < 6; ++iFace )
		{
			// Finally, iterate over all mip levels in the *destination*
			for (int iMip = 0; iMip < pDstCubemap->MipCount(); ++iMip )
			{
				// Copy the bits from the source images into the cube faces
				unsigned char *pSrcBits = pSrcVTFTextures[iFace]->ImageData( iFrame, 0, iMip + iMipLevelOffset );
				unsigned char *pDstBits = pDstCubemap->ImageData( iFrame, iFace, iMip );
				int iSize = pDstCubemap->ComputeMipSize( iMip );

				memcpy( pDstBits, pSrcBits, iSize ); 
			}
		}
	}

	ImageFormat originalFormat = pDstCubemap->Format();
	if( !bHDR )
	{
		// Convert the cube to format that we can apply tools to it...
		pDstCubemap->ConvertImageFormat( IMAGE_FORMAT_DEFAULT, false );
	}

	// Fixup the cubemap facing
	pDstCubemap->FixCubemapFaceOrientation();

	// Now that the bits are in place, compute the spheremaps...
	pDstCubemap->GenerateSpheremap();

	if( !bHDR )
	{
		// Convert the cubemap to the final format
		pDstCubemap->ConvertImageFormat( originalFormat, false );
	}

	// Write the puppy out!
	char dstVTFFileName[1024];
	if( bHDR )
	{
		sprintf( dstVTFFileName, "materials/maps/%s/cubemapdefault.hdr.vtf", mapbase );
	}
	else
	{
		sprintf( dstVTFFileName, "materials/maps/%s/cubemapdefault.vtf", mapbase );
	}

	CUtlBuffer outputBuf;
	if (!pDstCubemap->Serialize( outputBuf ))
	{
		Warning( "Error serializing default cubemap %s\n", dstVTFFileName );
		return;
	}

	// spit out the default one.
	AddBufferToPack( dstVTFFileName, outputBuf.Base(), outputBuf.TellPut(), false );

	// spit out all of the ones that are attached to world geometry.
	int i;
	for( i = 0; i < s_DefaultCubemapNames.Count(); i++ )
	{
		char vtfName[MAX_PATH];
		VTFNameToHDRVTFName( s_DefaultCubemapNames[i], vtfName, MAX_PATH, bHDR );
		if( FileExistsInPack( vtfName ) )
		{
			continue;
		}
		AddBufferToPack( vtfName, outputBuf.Base(),outputBuf.TellPut(), false );
	}

	// Clean up the textures
	for( i = 0; i < 6; i++ )
	{
		DestroyVTFTexture( pSrcVTFTextures[i] );
	}
	DestroyVTFTexture( pDstCubemap );
}	
Esempio n. 30
0
bool CUDPSocket::SendTo( const netadr_t &recipient, const CUtlBuffer& data  )
{
	return SendTo( recipient, (const byte *)data.Base(), (size_t)data.TellPut() );
}