bool Serialize( CUtlBuffer &buf, const VMatrix &src ) { if ( buf.IsText() ) { buf.Printf( "\n" ); SerializeFloats( buf, 4, src[0] ); buf.Printf( "\n" ); SerializeFloats( buf, 4, src[1] ); buf.Printf( "\n" ); SerializeFloats( buf, 4, src[2] ); buf.Printf( "\n" ); SerializeFloats( buf, 4, src[3] ); buf.Printf( "\n" ); } else { buf.Put( &src, sizeof(VMatrix) ); } return buf.IsValid(); }
bool LoadStudioCollisionModel( char const* pModelName, CUtlBuffer& buf ) { char tmp[1024]; Q_strncpy( tmp, pModelName, sizeof( tmp ) ); Q_SetExtension( tmp, ".phy", sizeof( tmp ) ); // No luck, gotta build it if (!LoadFile( tmp, buf )) { // this is not an error, the model simply has no PHY file return false; } phyheader_t *header = (phyheader_t *)buf.PeekGet(); if ( header->size != sizeof(*header) || header->solidCount <= 0 ) return false; return true; }
bool BasicGameStats_t::ParseFromBuffer( CUtlBuffer& buf, int iBufferStatsVersion ) { bool bret = true; m_nSecondsToCompleteGame = buf.GetInt(); if ( m_nSecondsToCompleteGame < 0 || m_nSecondsToCompleteGame > 10000000 ) { bret = false; } m_Summary.ParseFromBuffer( buf, iBufferStatsVersion ); int c = buf.GetInt(); if ( c > 1024 || c < 0 ) { bret = false; } for ( int i = 0; i < c; ++i ) { char mapname[ 256 ]; buf.GetString( mapname, sizeof( mapname ) ); BasicGameStatsRecord_t *rec = FindOrAddRecordForMap( mapname ); bool valid= rec->ParseFromBuffer( buf, iBufferStatsVersion ); if ( !valid ) { bret = false; } } if ( iBufferStatsVersion >= GAMESTATS_FILE_VERSION_OLD2 ) { m_nHL2ChaptureUnlocked = (int)buf.GetChar(); m_bSteam = buf.GetChar() ? true : false; } if ( iBufferStatsVersion > GAMESTATS_FILE_VERSION_OLD2 ) { m_bCyberCafe = buf.GetChar() ? true : false; } if ( iBufferStatsVersion > GAMESTATS_FILE_VERSION_OLD3 ) { m_nDXLevel = (int)buf.GetShort(); } return bret; }
bool Unserialize( CUtlBuffer &buf, QAngle &dest ) { if ( buf.IsText() ) { // FIXME: Print this in a way that we never lose precision int nRetVal = buf.Scanf( "%f %f %f", &dest.x, &dest.y, &dest.z ); return (nRetVal == 3) && buf.IsValid(); } dest.x = buf.GetFloat( ); dest.y = buf.GetFloat( ); dest.z = buf.GetFloat( ); return buf.IsValid(); }
bool Unserialize( CUtlBuffer &buf, Color &dest ) { if ( buf.IsText() ) { int r = 0, g = 0, b = 0, a = 255; int nRetVal = buf.Scanf( "%d %d %d %d", &r, &g, &b, &a ); dest.SetColor( r, g, b, a ); return (nRetVal == 4) && buf.IsValid(); } dest[0] = buf.GetUnsignedChar( ); dest[1] = buf.GetUnsignedChar( ); dest[2] = buf.GetUnsignedChar( ); dest[3] = buf.GetUnsignedChar( ); return buf.IsValid(); }
//----------------------------------------------------------------------------- // Get PSD file image resources //----------------------------------------------------------------------------- PSDImageResources PSDGetImageResources( CUtlBuffer &buf ) { int nGet = buf.TellGet(); // Header PSDHeader_t header; buf.Get( &header, sizeof( header ) ); // Then palette unsigned int numBytesPalette = BigLong( buf.GetUnsignedInt() ); buf.SeekGet( CUtlBuffer::SEEK_CURRENT, numBytesPalette ); // Then image resources unsigned int numBytesImgResources = BigLong( buf.GetUnsignedInt() ); PSDImageResources imgres( numBytesImgResources, ( unsigned char * ) buf.PeekGet() ); // Restore the seek buf.SeekGet( CUtlBuffer::SEEK_HEAD, nGet ); return imgres; }
static void PSDReadUncompressedChannels( CUtlBuffer &buf, int nChannelsCount, PSDMode_t mode, PSDPalette_t &palette, Bitmap_t &bitmap ) { unsigned char *pChannelRow = (unsigned char*)_alloca( bitmap.m_nWidth ); for ( int i=0; i<nChannelsCount; ++i ) { int nIndex = s_pChannelIndex[mode][i]; Assert( nIndex != -1 ); unsigned char *pDest = bitmap.m_pBits; for( int j=0; j < bitmap.m_nHeight; ++j ) { buf.Get( pChannelRow, bitmap.m_nWidth ); // Collate the channels together for ( int k = 0; k < bitmap.m_nWidth; ++k, pDest += 4 ) { pDest[nIndex] = pChannelRow[k]; } } } PSDConvertToRGBA8888( nChannelsCount, mode, palette, bitmap ); }
void BasicGameStats_t::SaveToBuffer( CUtlBuffer& buf ) { buf.PutInt( m_nSecondsToCompleteGame ); m_Summary.SaveToBuffer( buf ); int c = m_MapTotals.Count(); buf.PutInt( c ); for ( int i = m_MapTotals.First(); i != m_MapTotals.InvalidIndex(); i = m_MapTotals.Next( i ) ) { char const *name = m_MapTotals.GetElementName( i ); BasicGameStatsRecord_t &rec = m_MapTotals[ i ]; buf.PutString( name ); rec.SaveToBuffer( buf ); } buf.PutChar( (char)m_nHL2ChaptureUnlocked ); buf.PutChar( m_bSteam ? 1 : 0 ); buf.PutChar( m_bCyberCafe ? 1 : 0 ); buf.PutShort( (short)m_nDXLevel ); }
void CNetworkStringTable::WriteStringTable( CUtlBuffer& buf ) { int numstrings = GetNumStrings(); buf.PutInt( numstrings ); for ( int i = 0 ; i < numstrings; i++ ) { buf.PutString( GetString( i ) ); int userDataSize; const void *pUserData = GetStringUserData( i, &userDataSize ); if ( userDataSize > 0 ) { buf.PutChar( 1 ); buf.PutShort( (short)userDataSize ); buf.Put( pUserData, userDataSize ); } else { buf.PutChar( 0 ); } } }
void CSentence::SaveToBuffer( CUtlBuffer& buf ) { #if PHONEME_EDITOR Assert( !m_bIsCached ); int i, j; buf.Printf( "VERSION 1.0\n" ); buf.Printf( "PLAINTEXT\n" ); buf.Printf( "{\n" ); buf.Printf( "%s\n", GetText() ); buf.Printf( "}\n" ); buf.Printf( "WORDS\n" ); buf.Printf( "{\n" ); for ( i = 0; i < m_Words.Size(); i++ ) { CWordTag *word = m_Words[ i ]; Assert( word ); buf.Printf( "WORD %s %.3f %.3f\n", word->GetWord(), word->m_flStartTime, word->m_flEndTime ); buf.Printf( "{\n" ); for ( j = 0; j < word->m_Phonemes.Size(); j++ ) { CPhonemeTag *phoneme = word->m_Phonemes[ j ]; Assert( phoneme ); buf.Printf( "%i %s %.3f %.3f 1\n", phoneme->GetPhonemeCode(), phoneme->GetTag(), phoneme->GetStartTime(), phoneme->GetEndTime() ); } buf.Printf( "}\n" ); } buf.Printf( "}\n" ); buf.Printf( "EMPHASIS\n" ); buf.Printf( "{\n" ); int c = m_EmphasisSamples.Count(); for ( i = 0; i < c; i++ ) { CEmphasisSample *sample = &m_EmphasisSamples[ i ]; Assert( sample ); buf.Printf( "%f %f\n", sample->time, sample->value ); } buf.Printf( "}\n" ); buf.Printf( "OPTIONS\n" ); buf.Printf( "{\n" ); buf.Printf( "voice_duck %d\n", GetVoiceDuck() ? 1 : 0 ); if ( m_bStoreCheckSum ) { buf.Printf( "checksum %d\n", m_uCheckSum ); } buf.Printf( "}\n" ); #else Assert( 0 ); #endif }
//----------------------------------------------------------------------------- // FIXME: assumes that we don't need to do gamma correction. //----------------------------------------------------------------------------- bool WriteToBuffer( unsigned char *pImageData, CUtlBuffer &buffer, int width, int height, ImageFormat srcFormat, ImageFormat dstFormat ) { TGAHeader_t header; // Fix the dstFormat to match what actually is going to go into the file switch( dstFormat ) { case IMAGE_FORMAT_RGB888: dstFormat = IMAGE_FORMAT_BGR888; break; #if defined( _X360 ) case IMAGE_FORMAT_LINEAR_RGB888: dstFormat = IMAGE_FORMAT_LINEAR_BGR888; break; #endif case IMAGE_FORMAT_RGBA8888: dstFormat = IMAGE_FORMAT_BGRA8888; break; } header.id_length = 0; // comment length header.colormap_type = 0; // ??? switch( dstFormat ) { case IMAGE_FORMAT_BGR888: #if defined( _X360 ) case IMAGE_FORMAT_LINEAR_BGR888: #endif header.image_type = 2; // 24/32 bit uncompressed TGA header.pixel_size = 24; break; case IMAGE_FORMAT_BGRA8888: header.image_type = 2; // 24/32 bit uncompressed TGA header.pixel_size = 32; break; case IMAGE_FORMAT_I8: header.image_type = 1; // 8 bit uncompressed TGA header.pixel_size = 8; break; default: return false; break; } header.colormap_index = 0; header.colormap_length = 0; header.colormap_size = 0; header.x_origin = 0; header.y_origin = 0; header.width = ( unsigned short )width; header.height = ( unsigned short )height; header.attributes = 0x20; // Makes it so we don't have to vertically flip the image buffer.PutChar( header.id_length ); buffer.PutChar( header.colormap_type ); buffer.PutChar( header.image_type ); fputLittleShort( header.colormap_index, buffer ); fputLittleShort( header.colormap_length, buffer ); buffer.PutChar( header.colormap_size ); fputLittleShort( header.x_origin, buffer ); fputLittleShort( header.y_origin, buffer ); fputLittleShort( header.width, buffer ); fputLittleShort( header.height, buffer ); buffer.PutChar( header.pixel_size ); buffer.PutChar( header.attributes ); int nSizeInBytes = width * height * ImageLoader::SizeInBytes( dstFormat ); buffer.EnsureCapacity( buffer.TellPut() + nSizeInBytes ); unsigned char *pDst = (unsigned char*)buffer.PeekPut(); if ( !ImageLoader::ConvertImageFormat( pImageData, srcFormat, pDst, dstFormat, width, height ) ) return false; buffer.SeekPut( CUtlBuffer::SEEK_CURRENT, nSizeInBytes ); return true; }
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(); } } } }
//----------------------------------------------------------------------------- // Reads the PSD file into the specified buffer //----------------------------------------------------------------------------- bool PSDReadFileRGBA8888( CUtlBuffer &buf, Bitmap_t &bitmap ) { PSDHeader_t header; buf.Get( &header, sizeof(header) ); if ( BigLong( header.m_nSignature ) != PSD_SIGNATURE ) return false; if ( BigShort( header.m_nVersion ) != 1 ) return false; if ( BigShort( header.m_nDepth ) != 8 ) return false; PSDMode_t mode = (PSDMode_t)BigShort( header.m_nMode ); int nChannelsCount = BigShort( header.m_nChannels ); if ( mode == MODE_MULTICHANNEL || mode == MODE_LAB ) return false; switch ( mode ) { case MODE_RGBA: if ( nChannelsCount < 3 ) return false; break; case MODE_GREYSCALE: case MODE_PALETTIZED: if ( nChannelsCount != 1 && nChannelsCount != 2 ) return false; break; case MODE_CMYK: if ( nChannelsCount < 4 ) return false; break; default: Warning( "Unsupported PSD color mode!\n" ); return false; } int nWidth = BigLong( header.m_nColumns ); int nHeight = BigLong( header.m_nRows ); // Skip parts of memory we don't care about int nColorModeSize = BigLong( buf.GetUnsignedInt() ); Assert( nColorModeSize % 3 == 0 ); unsigned char *pPaletteBits = (unsigned char*)_alloca( nColorModeSize ); PSDPalette_t palette; palette.m_pRed = palette.m_pGreen = palette.m_pBlue = 0; if ( nColorModeSize ) { int nPaletteSize = nColorModeSize / 3; buf.Get( pPaletteBits, nColorModeSize ); palette.m_pRed = pPaletteBits; palette.m_pGreen = palette.m_pRed + nPaletteSize; palette.m_pBlue = palette.m_pGreen + nPaletteSize; } int nImageResourcesSize = BigLong( buf.GetUnsignedInt() ); buf.SeekGet( CUtlBuffer::SEEK_CURRENT, nImageResourcesSize ); int nLayersSize = BigLong( buf.GetUnsignedInt() ); buf.SeekGet( CUtlBuffer::SEEK_CURRENT, nLayersSize ); unsigned short nCompressionType = BigShort( buf.GetShort() ); bitmap.Init( nWidth, nHeight, IMAGE_FORMAT_RGBA8888 ); bool bSecondPassCMYKA = ( nChannelsCount > 4 && mode == MODE_CMYK ); if ( nCompressionType == 0 ) { PSDReadUncompressedChannels( buf, ( nChannelsCount > 4 ) ? 4 : nChannelsCount, mode, palette, bitmap ); } else { // Skip the data that indicates the length of each compressed row in bytes // NOTE: There are two bytes per row per channel unsigned int nLineLengthData = sizeof(unsigned short) * bitmap.m_nHeight * nChannelsCount; buf.SeekGet( CUtlBuffer::SEEK_CURRENT, nLineLengthData ); PSDReadCompressedChannels( buf, ( nChannelsCount > 4 ) ? 4 : nChannelsCount, mode, palette, bitmap ); } // Read the alpha in a second pass for CMYKA if ( bSecondPassCMYKA ) { if ( nCompressionType == 0 ) { PSDReadUncompressedChannels( buf, 1, MODE_COUNT, palette, bitmap ); } else { PSDReadCompressedChannels( buf, 1, MODE_COUNT, palette, bitmap ); } } return true; }
//----------------------------------------------------------------------------- // Converts a buffer from a CRLF buffer to a CR buffer (and back) // Returns false if no conversion was necessary (and outBuf is left untouched) // If the conversion occurs, outBuf will be cleared. //----------------------------------------------------------------------------- bool CUtlBuffer::ConvertCRLF( CUtlBuffer &outBuf ) { if ( !IsText() || !outBuf.IsText() ) return false; if ( ContainsCRLF() == outBuf.ContainsCRLF() ) return false; int nInCount = TellMaxPut(); outBuf.Purge(); outBuf.EnsureCapacity( nInCount ); bool bFromCRLF = ContainsCRLF(); // Start reading from the beginning int nGet = TellGet(); int nPut = TellPut(); int nGetDelta = 0; int nPutDelta = 0; const char *pBase = (const char*)Base(); int nCurrGet = 0; while ( nCurrGet < nInCount ) { const char *pCurr = &pBase[nCurrGet]; if ( bFromCRLF ) { const char *pNext = Q_strnistr( pCurr, "\r\n", nInCount - nCurrGet ); if ( !pNext ) { outBuf.Put( pCurr, nInCount - nCurrGet ); break; } int nBytes = (size_t)pNext - (size_t)pCurr; outBuf.Put( pCurr, nBytes ); outBuf.PutChar( '\n' ); nCurrGet += nBytes + 2; if ( nGet >= nCurrGet - 1 ) { --nGetDelta; } if ( nPut >= nCurrGet - 1 ) { --nPutDelta; } } else { const char *pNext = Q_strnchr( pCurr, '\n', nInCount - nCurrGet ); if ( !pNext ) { outBuf.Put( pCurr, nInCount - nCurrGet ); break; } int nBytes = (size_t)pNext - (size_t)pCurr; outBuf.Put( pCurr, nBytes ); outBuf.PutChar( '\r' ); outBuf.PutChar( '\n' ); nCurrGet += nBytes + 1; if ( nGet >= nCurrGet ) { ++nGetDelta; } if ( nPut >= nCurrGet ) { ++nPutDelta; } } } Assert( nPut + nPutDelta <= outBuf.TellMaxPut() ); outBuf.SeekGet( SEEK_HEAD, nGet + nGetDelta ); outBuf.SeekPut( SEEK_HEAD, nPut + nPutDelta ); return true; }
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 ); }
bool CBaseGameStats::LoadFromFile( void ) { if ( filesystem->FileExists( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID ) ) { char fullpath[ 512 ]; filesystem->RelativePathToFullPath( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID, fullpath, sizeof( fullpath ) ); StatsLog( "Loading stats from '%s'\n", fullpath ); } CUtlBuffer buf; if ( filesystem->ReadFile( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID, buf ) ) { bool bRetVal = true; int version = buf.GetShort(); if ( version > GAMESTATS_FILE_VERSION ) return false; //file is beyond our comprehension // Set global parse version CBGSDriver.m_iLoadedVersion = version; buf.Get( CBGSDriver.m_szLoadedUserID, 16 ); CBGSDriver.m_szLoadedUserID[ sizeof( CBGSDriver.m_szLoadedUserID ) - 1 ] = 0; if ( s_szPseudoUniqueID[ 0 ] != 0 ) { if ( Q_stricmp( CBGSDriver.m_szLoadedUserID, s_szPseudoUniqueID ) ) { //UserID changed, blow away log!!! filesystem->RemoveFile( gamestats->GetStatSaveFileName(), GAMESTATS_PATHID ); filesystem->RemoveFile( GAMESTATS_LOG_FILE, GAMESTATS_PATHID ); Warning( "Userid changed, clearing stats file\n" ); CBGSDriver.m_szLoadedUserID[0] = '\0'; CBGSDriver.m_iLoadedVersion = -1; gamestats->m_BasicStats.Clear(); gamestats->LoadingEvent_PlayerIDDifferentThanLoadedStats(); bRetVal = false; } if ( version <= GAMESTATS_FILE_VERSION_OLD5 ) { gamestats->m_BasicStats.Clear(); bRetVal = false; } else { // Peek ahead in buffer to see if we have the "no default stats" secret flag set. int iCheckForStandardStatsInFile = *( int * )buf.PeekGet(); bool bValid = true; if ( iCheckForStandardStatsInFile != GAMESTATS_STANDARD_NOT_SAVED ) { //the GAMESTATS_STANDARD_NOT_SAVED flag coincides with user completion time, rewind so the gamestats parser can grab it bValid = gamestats->m_BasicStats.ParseFromBuffer( buf, version ); } else { // skip over the flag buf.GetInt(); } if( !bValid ) { m_BasicStats.Clear(); } if( ( buf.TellPut() - buf.TellGet() ) != 0 ) //more data left, must be custom data { gamestats->LoadCustomDataFromBuffer( buf ); } } } return bRetVal; } else { filesystem->RemoveFile( GAMESTATS_LOG_FILE, GAMESTATS_PATHID ); } return false; }
//---------------------------------------------------------------------- // 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; }
//----------------------------------------------------------------------------- // String attribute //----------------------------------------------------------------------------- bool Serialize( CUtlBuffer &buf, const CUtlString &src ) { buf.PutDelimitedString( s_pConv, src.Get() ); return buf.IsValid(); }
//----------------------------------------------------------------------------- // 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; }
size_t CGEWebRequest::WriteData( void *ptr, size_t size, size_t nmemb, void *userdata ) { CUtlBuffer *result = (CUtlBuffer*) userdata; result->PutString( (char*)ptr ); return size * nmemb; }
//----------------------------------------------------------------------------- // 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; }
void CUtlBufferEditor::WriteToBuffer( CUtlBuffer &buf ) { int size = TellPut(); buf.Put( Base(), size ); }
bool CServerRemoteAccess::LookupValue(const char *variable, CUtlBuffer &value) { const char* strval = LookupStringValue(variable); if (strval) { value.PutString(strval); value.PutChar(0); return true; } if (!Q_stricmp(variable, "stats")) { char stats[512]; GetStatsString(stats, sizeof(stats)); value.PutString(stats); value.PutChar(0); return true; } if (!Q_stricmp(variable, "banlist")) { GetUserBanList(value); return true; } if (!Q_stricmp(variable, "playerlist")) { GetPlayerList(value); return true; } if (!Q_stricmp(variable, "maplist")) { GetMapList(value); return true; } if (!Q_stricmp(variable, "uptime")) { value.PutInt(int(Sys_FloatTime() - Host_GetStartTime())); value.PutChar(0); return true; } if (!Q_stricmp(variable, "ipaddress")) { value.PutString(NET_AdrToString(net_local_adr)); value.PutChar(0); return true; } if (!Q_stricmp(variable, "mapcycle")) { int len; void* mapcyclelist = COM_LoadFileForMe(mapcyclefile.string, &len); if (mapcyclelist && len) { value.PutString((char*)mapcyclelist); value.PutChar(0); COM_FreeFile(mapcyclelist); } return true; } value.PutChar(0); return false; }
void CMomRunStats::Deserialize(CUtlBuffer &reader) { SetTotalZones(reader.GetUnsignedChar()); // NOTE: This range checking might result in unread data. if (m_iTotalZones > MAX_ZONES) SetTotalZones(MAX_ZONES); for (int i = 0; i < m_iTotalZones + 1; ++i) { SetZoneJumps(i, reader.GetUnsignedInt()); SetZoneStrafes(i, reader.GetUnsignedInt()); SetZoneStrafeSyncAvg(i, reader.GetFloat()); SetZoneStrafeSync2Avg(i, reader.GetFloat()); SetZoneEnterTick(i, reader.GetUnsignedInt()); SetZoneTicks(i, reader.GetUnsignedInt()); float vel3D = 0.0f, vel2D = 0.0f; vel3D = reader.GetFloat(); vel2D = reader.GetFloat(); SetZoneVelocityMax(i, vel3D, vel2D); vel3D = reader.GetFloat(); vel2D = reader.GetFloat(); SetZoneVelocityAvg(i, vel3D, vel2D); vel3D = reader.GetFloat(); vel2D = reader.GetFloat(); SetZoneEnterSpeed(i, vel3D, vel2D); vel3D = reader.GetFloat(); vel2D = reader.GetFloat(); SetZoneExitSpeed(i, vel3D, vel2D); } }
//----------------------------------------------------------------------------- // Purpose: Finds the value of a particular server variable //----------------------------------------------------------------------------- bool CServerRemoteAccess::LookupValue(const char *variable, CUtlBuffer &value) { Assert(value.IsText()); // first see if it's a cvar const char *strval = LookupStringValue(variable); if (strval) { value.PutString(strval); value.PutChar(0); } else if (!stricmp(variable, "stats")) { char stats[512]; GetStatsString(stats, sizeof(stats)); value.PutString(stats); value.PutChar(0); } else if (!stricmp(variable, "banlist")) { // returns a list of banned users and ip's GetUserBanList(value); } else if (!stricmp(variable, "playerlist")) { GetPlayerList(value); } else if (!stricmp(variable, "maplist")) { GetMapList(value); } else if (!stricmp(variable, "uptime")) { int timeSeconds = (int)(Plat_FloatTime()); value.PutInt(timeSeconds); value.PutChar(0); } else if (!stricmp(variable, "ipaddress")) { char addr[25]; Q_snprintf( addr, sizeof(addr), "%s:%i", net_local_adr.ToString(true), sv.GetUDPPort()); value.PutString( addr ); value.PutChar(0); } else if (!stricmp(variable, "mapcycle")) { ConVarRef mapcycle( "mapcyclefile" ); if ( mapcycle.IsValid() ) { // send the mapcycle list file FileHandle_t f = g_pFileSystem->Open(mapcycle.GetString(), "rb" ); if ( f == FILESYSTEM_INVALID_HANDLE ) return true; int len = g_pFileSystem->Size(f); char *mapcycleData = (char *)_alloca( len+1 ); if ( len && g_pFileSystem->Read( mapcycleData, len, f ) ) { mapcycleData[len] = 0; // Make sure it's null terminated. value.PutString((const char *)mapcycleData); value.PutChar(0); } else { value.PutString( "" ); value.PutChar(0); } g_pFileSystem->Close( f ); } } else { // value not found, null terminate value.PutChar(0); return false; } return true; }
void WritePHXFile( const char *pName, const phyfile_t &file ) { if ( file.header.size != sizeof(file.header) || file.collide.solidCount <= 0 ) return; CUtlBuffer out; char outName[1024]; Q_snprintf( outName, sizeof(outName), "%s", pName ); Q_SetExtension( outName, ".phx", sizeof(outName) ); simplifyparams_t params; params.Defaults(); params.tolerance = (file.collide.solidCount > 1) ? 4.0f : 2.0f; // single solids constraint to AABB for placement help params.addAABBToSimplifiedHull = (file.collide.solidCount == 1) ? true : false; params.mergeConvexElements = true; params.mergeConvexTolerance = 0.025f; Q_FixSlashes(outName); Q_strlower(outName); char *pSearch = Q_strstr( outName,"models\\" ); if ( pSearch ) { char keyname[1024]; pSearch += strlen("models\\"); Q_StripExtension( pSearch, keyname, sizeof(keyname) ); OverrideDefaultsForModel( keyname, params ); } out.Put( &file.header, sizeof(file.header) ); int outSize = 0; bool bStoreSolidNames = file.collide.solidCount > 1 ? true : false; bStoreSolidNames = bStoreSolidNames || HasMultipleBones(outName); vcollide_t *pNewCollide = ConvertVCollideToPHX( &file.collide, params, &outSize, false, bStoreSolidNames); g_TotalOut += file.fileSize; for ( int i = 0; i < pNewCollide->solidCount; i++ ) { int collideSize = physcollision->CollideSize( pNewCollide->solids[i] ); out.PutInt( collideSize ); char *pMem = new char[collideSize]; physcollision->CollideWrite( pMem, pNewCollide->solids[i] ); out.Put( pMem, collideSize ); delete[] pMem; } if (!g_bQuiet) { Msg("%s Compressed %d (%d text) to %d (%d text)\n", outName, file.fileSize, file.collide.descSize, out.TellPut(), pNewCollide->descSize ); } out.Put( pNewCollide->pKeyValues, pNewCollide->descSize ); g_TotalCompress += out.TellPut(); #if 0 //Msg("OLD:\n-----------------------------------\n%s\n", file.collide.pKeyValues ); CPackedPhysicsDescription *pPacked = physcollision->CreatePackedDesc( pNewCollide->pKeyValues, pNewCollide->descSize ); Msg("NEW:\n-----------------------------------\n" ); for ( int i = 0; i < pPacked->m_solidCount; i++ ) { solid_t solid; pPacked->GetSolid( &solid, i ); Msg("index %d\n", solid.index ); Msg("name %s\n", solid.name ); Msg("mass %.2f\n", solid.params.mass ); Msg("surfaceprop %s\n", solid.surfaceprop); Msg("damping %.2f\n", solid.params.damping ); Msg("rotdamping %.2f\n", solid.params.rotdamping ); Msg("drag %.2f\n", solid.params.dragCoefficient ); Msg("inertia %.2f\n", solid.params.inertia ); Msg("volume %.2f\n", solid.params.volume ); } #endif DestroyPHX( pNewCollide ); if ( !g_pFullFileSystem->WriteFile( outName, NULL, out ) ) Warning("Can't write file: %s\n", outName ); }
void CMomRunStats::Serialize(CUtlBuffer &writer) { writer.PutUnsignedChar(m_iTotalZones); for (int i = 0; i < m_iTotalZones + 1; ++i) { //Jumps/Strafes writer.PutUnsignedInt(m_iZoneJumps[i]); writer.PutUnsignedInt(m_iZoneStrafes[i]); //Sync writer.PutFloat(m_flZoneStrafeSyncAvg[i]); writer.PutFloat(m_flZoneStrafeSync2Avg[i]); //Time writer.PutUnsignedInt(m_iZoneEnterTick[i]); writer.PutUnsignedInt(m_iZoneTicks[i]); //Velocity writer.PutFloat(m_flZoneVelocityMax3D[i]); writer.PutFloat(m_flZoneVelocityMax2D[i]); writer.PutFloat(m_flZoneVelocityAvg3D[i]); writer.PutFloat(m_flZoneVelocityAvg2D[i]); writer.PutFloat(m_flZoneEnterSpeed3D[i]); writer.PutFloat(m_flZoneEnterSpeed2D[i]); writer.PutFloat(m_flZoneExitSpeed3D[i]); writer.PutFloat(m_flZoneExitSpeed2D[i]); } }
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; }
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 }
//----------------------------------------------------------------------------- // Does a texture have alpha? //----------------------------------------------------------------------------- static bool DoesTextureUseNormal( const char *pTextureName, const char *pMaterialName, bool &bUsesAlpha, bool &bIsCompressed, int &nSizeInBytes ) { nSizeInBytes = 0; bUsesAlpha = false; if ( IsX360() ) { // not supporting return false; } // Special textures start with '_'.. if ( !pTextureName || ( pTextureName[0] == '_' ) || ( pTextureName[0] == 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 bUsesNormal = false; if ( !pVTFTexture->Unserialize( buf, true ) ) { Warning( "Error reading material \"%s\"\n", pCacheFileName ); } else { if ( pVTFTexture->Flags() & TEXTUREFLAGS_NORMAL ) { bUsesAlpha = false; bUsesNormal = true; bIsCompressed = ImageLoader::IsCompressed( pVTFTexture->Format() ) || ( pVTFTexture->Format() == IMAGE_FORMAT_A8 ); nSizeInBytes = pVTFTexture->ComputeTotalSize(); if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) ) { bUsesAlpha = true; } } } DestroyVTFTexture( pVTFTexture ); g_pFullFileSystem->Close( fileHandle ); return bUsesNormal; }