This commit is contained in:
nephacks
2025-06-04 03:22:50 +02:00
parent f234f23848
commit f12416cffd
14243 changed files with 6446499 additions and 26 deletions

View File

@@ -0,0 +1,770 @@
//======= Copyright © 1996-2008, Valve Corporation, All rights reserved. ======
//
// Purpose: A 2D Slider
//
//=============================================================================
// Valve includes
#include <KeyValues.h>
#include <vgui/MouseCode.h>
#include <vgui/IBorder.h>
#include <vgui/IInput.h>
#include <vgui/ISystem.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include <vgui_controls/Controls.h>
#include <vgui_controls/TextImage.h>
#include <dme_controls/2DSlider.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
//-----------------------------------------------------------------------------
// Statics
//-----------------------------------------------------------------------------
Color C2DSlider::s_TextColor( 208, 143, 40, 192 );
Color C2DSlider::s_NobColor( 0, 63, 98, 255 );
Color C2DSlider::s_TickColor( 0, 79, 182, 255 );
Color C2DSlider::s_TickFillXColor( 0, 63, 0, 255 );
Color C2DSlider::s_TickFillYColor( 0, 0, 98, 255 );
Color C2DSlider::s_TickFillColor( 0, 63, 98, 255 );
Color C2DSlider::s_TrackColor( 31, 31, 31, 255 );
//-----------------------------------------------------------------------------
// Purpose: Create a slider bar with ticks underneath it
//-----------------------------------------------------------------------------
C2DSlider::C2DSlider( Panel *pParent, const char *pName )
: BaseClass( pParent, pName )
{
m_bDrawLabel = true;
m_bIsDragOnRepositionNob = true;
m_bDragging = false;
m_fValue[ kXAxis ] = 0.0f;
m_fValue[ kYAxis ] = 0.0f;
m_fRange[ kXAxis ][ 0 ] = 0.0f;
m_fRange[ kXAxis ][ 1 ] = 1.0f;
m_fRange[ kYAxis ][ 0 ] = 1.0f;
m_fRange[ kYAxis ][ 1 ] = 0.0f;
m_pNobBorder = NULL;
m_pInsetBorder = NULL;
SetNobSize( 7, 7 );
RecomputeNobPosFromValue();
AddActionSignalTarget( this );
SetBlockDragChaining( true );
m_pLabel = new TextImage( pName );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
C2DSlider::~C2DSlider()
{
delete m_pLabel;
}
//-----------------------------------------------------------------------------
// Purpose: Set the value of the slider
//-----------------------------------------------------------------------------
void C2DSlider::SetValueX( float fValueX, bool bTriggerChangeMessage /* = true */ )
{
SetValue( fValueX, GetValueY(), bTriggerChangeMessage );
}
//-----------------------------------------------------------------------------
// Purpose: Set the value of the slider
//-----------------------------------------------------------------------------
float C2DSlider::GetValueX() const
{
return m_fValue[ kXAxis ];
}
//-----------------------------------------------------------------------------
// Purpose: Set the value of the slider
//-----------------------------------------------------------------------------
void C2DSlider::SetValueY( float fValueY, bool bTriggerChangeMessage /* = true */ )
{
SetValue( GetValueX(), fValueY, bTriggerChangeMessage );
}
//-----------------------------------------------------------------------------
// Purpose: Set the value of the slider to one of the ticks.
//-----------------------------------------------------------------------------
float C2DSlider::GetValueY() const
{
return m_fValue[ kYAxis ];
}
//-----------------------------------------------------------------------------
// Purpose: Set the value of the slider to one of the ticks.
//-----------------------------------------------------------------------------
void C2DSlider::SetValue( float fValueX, float fValueY, bool bTriggerChangeMessage )
{
fValueX = RemapValClamped( fValueX, m_fRange[ kXAxis ][ 0 ], m_fRange[ kXAxis ][ 1 ], m_fRange[ kXAxis ][ 0 ], m_fRange[ kXAxis ][ 1 ] );
fValueY = RemapValClamped( fValueY, m_fRange[ kYAxis ][ 0 ], m_fRange[ kYAxis ][ 1 ], m_fRange[ kYAxis ][ 0 ], m_fRange[ kYAxis ][ 1 ] );
if ( fValueX != m_fValue[ kXAxis ] || fValueY != m_fValue[ kYAxis ] )
{
m_fValue[ kXAxis ] = fValueX;
m_fValue[ kYAxis ] = fValueY;
RecomputeNobPosFromValue();
if ( bTriggerChangeMessage )
{
SendSliderMovedMessage();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Return the value of the slider
//-----------------------------------------------------------------------------
void C2DSlider::GetValue( float &fValueX, float &fValueY ) const
{
fValueX = GetValueX();
fValueY = GetValueY();
}
//-----------------------------------------------------------------------------
// Purpose: Set the range of the slider.
//-----------------------------------------------------------------------------
void C2DSlider::SetRange( float fMinX, float fMaxX, float fMinY, float fMaxY, bool bTriggerChangeMessage /* = true */ )
{
m_fRange[ kXAxis ][ 0 ] = fMinX;
m_fRange[ kXAxis ][ 1 ] = fMaxX;
m_fRange[ kYAxis ][ 0 ] = fMinY;
m_fRange[ kYAxis ][ 1 ] = fMaxY;
SetValue( m_fValue[ kXAxis ], m_fValue[ kYAxis ], bTriggerChangeMessage );
}
//-----------------------------------------------------------------------------
// Purpose: Get the max and min values of the slider
//-----------------------------------------------------------------------------
void C2DSlider::GetRange( float &fMinX, float &fMaxX, float &fMinY, float &fMaxY ) const
{
fMinX = m_fRange[ kXAxis ][ 0 ];
fMaxX = m_fRange[ kXAxis ][ 1 ];
fMinY = m_fRange[ kYAxis ][ 0 ];
fMaxY = m_fRange[ kYAxis ][ 1 ];
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetLabelText( const char *pText )
{
m_pLabel->SetText( pText );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetLabelText( const wchar_t *pText )
{
m_pLabel->SetText( pText );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::GetLabelText( wchar_t *pBuffer, int nBufferLen ) const
{
m_pLabel->GetText( pBuffer, nBufferLen );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::GetLabelUnlocalizedText( char *pBuffer, int nBufferLen ) const
{
m_pLabel->GetUnlocalizedText( pBuffer, nBufferLen );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetDrawLabel( bool bState )
{
m_bDrawLabel = bState;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool C2DSlider::IsDrawingLabel() const
{
return m_bDrawLabel;
}
//-----------------------------------------------------------------------------
// Purpose: Get the nob's position ( the ends of each side of the nob )
//-----------------------------------------------------------------------------
void C2DSlider::GetNobPos( int &nX, int &nY )
{
nX = m_nNobPos[ kXAxis ];
nY = m_nNobPos[ kYAxis ];
}
//-----------------------------------------------------------------------------
// Purpose: Respond when the cursor is moved in our window if we are clicking
// and dragging.
//-----------------------------------------------------------------------------
void C2DSlider::OnCursorMoved( int nMouseX, int nMouseY )
{
if ( !m_bDragging )
return;
input()->GetCursorPosition( nMouseX, nMouseY );
ScreenToLocal( nMouseX, nMouseY );
int nTrackX, nTrackY, nTrackWide, nTrackTall;
GetTrackRect( nTrackX, nTrackY, nTrackWide, nTrackTall );
m_nNobPos[ kXAxis ] = clamp( m_nNobDragStartPos[ kXAxis ] + nMouseX - m_nDragStartPos[ kXAxis ], nTrackX, nTrackX + nTrackWide - 1 );
m_nNobPos[ kYAxis ] = clamp( m_nNobDragStartPos[ kYAxis ] + nMouseY - m_nDragStartPos[ kYAxis ], nTrackY, nTrackY + nTrackTall - 1 );
RecomputeValueFromNobPos( false );
Repaint();
SendSliderMovedMessage();
}
//-----------------------------------------------------------------------------
// Purpose: Respond to mouse presses. Trigger Record staring positon.
//-----------------------------------------------------------------------------
void C2DSlider::OnMousePressed( MouseCode /* mouseCode */ )
{
if ( !IsEnabled() )
return;
/*
TODO: Do this in Maya
if ( input()->IsKeyDown( KEY_LSHIFT ) || input()->IsKeyDown( KEY_RSHIFT ) )
return;
if ( input()->IsKeyDown( KEY_LCONTROL ) || input()->IsKeyDown( KEY_LCONTROL ) )
return;
*/
int nMouseX;
int nMouseY;
input()->GetCursorPosition( nMouseX, nMouseY );
ScreenToLocal( nMouseX, nMouseY );
RequestFocus();
bool bStartDragging = false;
bool bPostDragStartSignal = false;
if (
nMouseX >= ( m_nNobPos[ kXAxis ] - m_nNobHalfSize[ kXAxis ] ) &&
nMouseX <= ( m_nNobPos[ kXAxis ] + m_nNobHalfSize[ kXAxis ] ) &&
nMouseY >= ( m_nNobPos[ kYAxis ] - m_nNobHalfSize[ kYAxis ] ) &&
nMouseY <= ( m_nNobPos[ kYAxis ] + m_nNobHalfSize[ kYAxis ] ) )
{
bStartDragging = true;
bPostDragStartSignal = true;
}
else
{
// we clicked elsewhere on the slider; move the nob to that position
int nTrackX, nTrackY, nTrackWide, nTrackTall;
GetTrackRect( nTrackX, nTrackY, nTrackWide, nTrackTall );
m_nNobPos[ kXAxis ] = clamp( nMouseX, nTrackX, nTrackX + nTrackWide - 1 );
m_nNobPos[ kYAxis ] = clamp( nMouseY, nTrackY, nTrackY + nTrackTall - 1 );
RecomputeValueFromNobPos( false );
Repaint();
SendSliderMovedMessage();
m_nNobDragStartPos[ kXAxis ] = nMouseX;
m_nNobDragStartPos[ kYAxis ] = nMouseY;
m_nDragStartPos[ kXAxis ] = nMouseX;
m_nDragStartPos[ kYAxis ] = nMouseY;
OnCursorMoved( nMouseX, nMouseY );
bStartDragging = IsDragOnRepositionNob();
if ( bStartDragging )
{
SendSliderDragStartMessage();
}
}
if ( bStartDragging )
{
// drag the nob
m_bDragging = true;
input()->SetMouseCapture( GetVPanel() );
m_nNobDragStartPos[ kXAxis ] = m_nNobPos[ kXAxis ];
m_nNobDragStartPos[ kYAxis ] = m_nNobPos[ kYAxis ];
m_nDragStartPos[ kXAxis ] = nMouseX;
m_nDragStartPos[ kYAxis ] = nMouseY;
}
if ( bPostDragStartSignal )
{
SendSliderDragStartMessage();
}
}
//-----------------------------------------------------------------------------
// Purpose: Just handle double presses like mouse presses
//-----------------------------------------------------------------------------
void C2DSlider::OnMouseDoublePressed( MouseCode mouseCode )
{
OnMousePressed( mouseCode );
}
//-----------------------------------------------------------------------------
// Purpose: Stop dragging when the mouse is released.
//-----------------------------------------------------------------------------
void C2DSlider::OnMouseReleased( MouseCode /* mouseCode */ )
{
if ( m_bDragging )
{
m_bDragging = false;
input()->SetMouseCapture( 0 );
SendSliderDragEndMessage();
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetNobWidth( int nWidth )
{
m_nNobHalfSize[ kXAxis ] = ( ( nWidth | 1 ) - 1 ) / 2;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int C2DSlider::GetNobWidth() const
{
return m_nNobHalfSize[ kXAxis ] * 2 + 1;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetNobTall( int nTall )
{
m_nNobHalfSize[ kYAxis ] = ( ( nTall | 1 ) - 1 ) / 2;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int C2DSlider::GetNobTall() const
{
return m_nNobHalfSize[ kYAxis ] * 2 + 1;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::SetNobSize( int nWidth, int nTall )
{
SetNobWidth( nWidth );
SetNobTall( nTall );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::GetNobSize( int &nHalfWidth, int &nHalfTall ) const
{
nHalfWidth = GetNobWidth();
nHalfTall = GetNobTall();
}
//-----------------------------------------------------------------------------
// Purpose: If you click on the slider outside of the nob, the nob jumps
// to the click position, and if this setting is enabled, the nob
// is then draggable from the new position until the mouse is released
// Input : state -
//-----------------------------------------------------------------------------
void C2DSlider::SetDragOnRepositionNob( bool bState )
{
m_bIsDragOnRepositionNob = bState;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool C2DSlider::IsDragOnRepositionNob() const
{
return m_bIsDragOnRepositionNob;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool C2DSlider::IsDragged() const
{
return m_bDragging;
}
//-----------------------------------------------------------------------------
// Purpose: Set the size of the slider bar.
// Warning less than 30 pixels tall and everything probably won't fit.
//-----------------------------------------------------------------------------
void C2DSlider::OnSizeChanged( int nWide, int nTall )
{
BaseClass::OnSizeChanged( nWide, nTall );
RecomputeNobPosFromValue();
}
//-----------------------------------------------------------------------------
// Purpose: Draw everything on screen
//-----------------------------------------------------------------------------
void C2DSlider::Paint()
{
DrawNob();
}
//-----------------------------------------------------------------------------
// Purpose: Draw the slider track
//-----------------------------------------------------------------------------
void C2DSlider::PaintBackground()
{
BaseClass::PaintBackground();
int x, y;
int wide,tall;
GetTrackRect( x, y, wide, tall );
surface()->DrawSetColor( s_TrackColor );
surface()->DrawFilledRect( x, y, x + wide + 1, y + tall + 1 );
if ( m_pInsetBorder )
{
m_pInsetBorder->Paint( x, y, x + wide, y + tall );
}
}
//-----------------------------------------------------------------------------
// Purpose: Layout the slider before drawing it on screen.
//-----------------------------------------------------------------------------
void C2DSlider::PerformLayout()
{
BaseClass::PerformLayout();
RecomputeNobPosFromValue();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C2DSlider::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
s_TextColor = pScheme->GetColor( "2DSlider.TextColor", s_TextColor );
s_NobColor = pScheme->GetColor( "2DSlider.NobColor", s_NobColor );
s_TickColor = pScheme->GetColor( "2DSlider.TickColor", s_TickColor );
s_TickFillXColor = pScheme->GetColor( "2DSlider.TickFillXColor", s_TickFillXColor );
s_TickFillYColor = pScheme->GetColor( "2DSlider.TickFillYColor", s_TickFillYColor );
s_TickFillColor = pScheme->GetColor( "2DSlider.TickFillColor", s_TickFillColor );
s_TrackColor = pScheme->GetColor( "2DSlider.TrackColor", s_TrackColor );
m_pLabel->SetColor( s_TextColor );
m_pLabel->SetFont( pScheme->GetFont( "Default" ) );
m_pLabel->ResizeImageToContent();
SetFgColor( s_NobColor );
m_pNobBorder = pScheme->GetBorder( "ButtonBorder" );
m_pInsetBorder = pScheme->GetBorder( "ButtonDepressedBorder" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C2DSlider::ApplySettings( KeyValues *inResourceData )
{
BaseClass::ApplySettings( inResourceData );
SetNobWidth( inResourceData->GetInt( "nobWidth", GetNobWidth() ) );
SetNobTall( inResourceData->GetInt( "nobTall", GetNobTall() ) );
SetDrawLabel( inResourceData->GetBool( "drawLabel", IsDrawingLabel() ) );
wchar_t buf[ BUFSIZ ];
m_pLabel->GetText( buf, ARRAYSIZE( buf ) );
SetLabelText( inResourceData->GetWString( "labelText", buf ) );
SetDragOnRepositionNob( inResourceData->GetBool( "dragOnRepositionNob", IsDragOnRepositionNob() ) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void C2DSlider::GetSettings( KeyValues *outResourceData )
{
BaseClass::GetSettings( outResourceData );
outResourceData->SetInt( "nobWidth", GetNobWidth() );
outResourceData->SetInt( "nobTall", GetNobTall() );
outResourceData->SetBool( "drawLabel", IsDrawingLabel() );
wchar_t buf[ BUFSIZ ];
m_pLabel->GetText( buf, ARRAYSIZE( buf ) );
outResourceData->SetWString( "labelText", buf );
outResourceData->SetBool( "dragOnRepositionNob", IsDragOnRepositionNob() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *C2DSlider::GetDescription()
{
static char buf[ 1024 ];
Q_snprintf( buf, sizeof( buf ), "%s, int nobWidth, int nobTall, bool dragOnRepositionNob", BaseClass::GetDescription() );
return buf;
}
//-----------------------------------------------------------------------------
// Purpose: Handle key presses
//-----------------------------------------------------------------------------
void C2DSlider::OnKeyCodeTyped( KeyCode nKeyCode )
{
switch ( nKeyCode )
{
// for now left and right arrows just open or close submenus if they are there.
case KEY_LEFT:
MoveNobRelative( -1, 0 );
break;
case KEY_RIGHT:
MoveNobRelative( 1, 0 );
break;
case KEY_DOWN:
MoveNobRelative( 0, 1 );
break;
case KEY_UP:
MoveNobRelative( 0, -1 );
break;
case KEY_HOME:
SetValueX( m_fRange[ kXAxis ][ 0 ] );
break;
case KEY_END:
SetValueX( m_fRange[ kXAxis ][ 1 ] );
break;
case KEY_PAGEUP:
SetValueY( m_fRange[ kYAxis ][ 0 ] );
break;
case KEY_PAGEDOWN:
SetValueY( m_fRange[ kYAxis ][ 1 ] );
break;
default:
BaseClass::OnKeyCodeTyped( nKeyCode );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose: Draw the nob part of the slider.
//-----------------------------------------------------------------------------
void C2DSlider::DrawNob()
{
// horizontal nob
int x, y;
int wide,tall;
GetTrackRect( x, y, wide, tall );
surface()->DrawSetColor( s_TickFillXColor );
surface()->DrawFilledRect( x, y, x + m_nNobPos[ kXAxis ], y + m_nNobPos[ kYAxis ] );
surface()->DrawSetColor( s_TickFillYColor );
surface()->DrawFilledRect( x + m_nNobPos[ kXAxis ] + 1, y + m_nNobPos[ kYAxis ] + 1, x + wide + 1, y + tall + 1 );
surface()->DrawSetColor( s_TickFillColor );
surface()->DrawFilledRect( x, y + m_nNobPos[ kYAxis ] + 1, x + m_nNobPos[ kXAxis ], y + tall + 1 );
surface()->DrawSetColor( s_TickFillColor );
surface()->DrawFilledRect( x, y + tall, m_nNobPos[ kXAxis ] + 1, m_nNobPos[ kYAxis ] );
surface()->DrawSetColor( s_TickColor );
surface()->DrawFilledRect( x, m_nNobPos[ kYAxis ], x + wide - 1, m_nNobPos[ kYAxis ] + 1 );
surface()->DrawFilledRect( m_nNobPos[ kXAxis ], y, m_nNobPos[ kXAxis ] + 1, y + tall - 1 );
// Redraw the inset border
if ( m_pInsetBorder )
{
m_pInsetBorder->Paint( x, y, x + wide, y + tall );
}
surface()->DrawSetColor( s_NobColor );
surface()->DrawFilledRect(
m_nNobPos[ kXAxis ] - m_nNobHalfSize[ kXAxis ], m_nNobPos[ kYAxis ] - m_nNobHalfSize[ kYAxis ],
m_nNobPos[ kXAxis ] + m_nNobHalfSize[ kXAxis ] + 1, m_nNobPos[ kYAxis ] + m_nNobHalfSize[ kYAxis ] + 1 );
// border
if ( m_pNobBorder )
{
m_pNobBorder->Paint(
m_nNobPos[ kXAxis ] - m_nNobHalfSize[ kXAxis ], m_nNobPos[ kYAxis ] - m_nNobHalfSize[ kYAxis ],
m_nNobPos[ kXAxis ] + m_nNobHalfSize[ kXAxis ] + 1, m_nNobPos[ kYAxis ] + m_nNobHalfSize[ kYAxis ] + 1 );
}
char buf[ BUFSIZ ];
Q_snprintf( buf, ARRAYSIZE( buf ), "n %02d %02d v %3.1f %3.1f", m_nNobPos[ kXAxis ], m_nNobPos[ kYAxis ], m_fValue[ kXAxis ], m_fValue[ kYAxis ] );
int nLabelWidth, nLabelTall;
m_pLabel->GetContentSize( nLabelWidth, nLabelTall );
// m_pLabel->SetPos( 10, y + MAX( tall, tall - ( tall - nLabelTall ) / 2 ) );
m_pLabel->SetPos( 10, y + ( MAX( 0, tall - nLabelTall ) ) / 2 );
m_pLabel->Paint();
}
//-----------------------------------------------------------------------------
// Purpose: Get the rectangle to draw the slider track in.
//-----------------------------------------------------------------------------
void C2DSlider::GetTrackRect( int &x, int &y, int &w, int &t )
{
x = 0;
y = 0;
GetPaintSize( w, t );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void C2DSlider::MoveNobRelative( int nX, int nY )
{
int x, y, wide, tall;
GetTrackRect( x, y, wide, tall );
m_nNobPos[ kXAxis ] = clamp( m_nNobPos[ kXAxis ] + nX, x, x + wide - 1 );
m_nNobPos[ kYAxis ] = clamp( m_nNobPos[ kYAxis ] + nY, y, y + tall - 1 );
RecomputeValueFromNobPos( true );
}
//-----------------------------------------------------------------------------
// Purpose: Move the nob on the slider in response to changing its value.
//-----------------------------------------------------------------------------
void C2DSlider::RecomputeNobPosFromValue()
{
int x, y, wide, tall;
GetTrackRect( x, y, wide, tall );
m_nNobPos[ kXAxis ] = static_cast< int >( RemapValClamped( m_fValue[ kXAxis ], m_fRange[ kXAxis ][ 0 ], m_fRange[ kXAxis ][ 1 ], x, x + wide - 1 ) );
m_nNobPos[ kYAxis ] = static_cast< int >( RemapValClamped( m_fValue[ kYAxis ], m_fRange[ kYAxis ][ 0 ], m_fRange[ kYAxis ][ 1 ], y, y + tall - 1 ) );
Repaint();
}
//-----------------------------------------------------------------------------
// Purpose: Sync the slider's value up with the nob's position.
//-----------------------------------------------------------------------------
void C2DSlider::RecomputeValueFromNobPos( bool bTriggerChangeMessage /* = true */ )
{
int x, y, wide, tall;
GetTrackRect( x, y, wide, tall );
const float fValueX = RemapValClamped( m_nNobPos[ kXAxis ], x, x + wide - 1, m_fRange[ kXAxis ][ 0 ], m_fRange[ kXAxis ][ 1 ] );
const float fValueY = RemapValClamped( m_nNobPos[ kYAxis ], y, y + tall - 1, m_fRange[ kYAxis ][ 0 ], m_fRange[ kYAxis ][ 1 ] );
SetValue( fValueX, fValueY, bTriggerChangeMessage );
}
//-----------------------------------------------------------------------------
// Purpose: Send a message to interested parties when the slider moves
//-----------------------------------------------------------------------------
void C2DSlider::SendSliderMovedMessage()
{
KeyValues *p2DSliderMoved = new KeyValues( "2DSliderMoved" );
p2DSliderMoved->SetFloat( "valueX", m_fValue[ kXAxis ] );
p2DSliderMoved->SetFloat( "valueY", m_fValue[ kYAxis ] );
PostActionSignal( p2DSliderMoved );
}
//-----------------------------------------------------------------------------
// Purpose: Send a message to interested parties when the user begins dragging the slider
//-----------------------------------------------------------------------------
void C2DSlider::SendSliderDragStartMessage()
{
KeyValues *p2DSliderDragStart = new KeyValues( "2DSliderDragStart" );
p2DSliderDragStart->SetFloat( "valueX", m_fValue[ kXAxis ] );
p2DSliderDragStart->SetFloat( "valueY", m_fValue[ kYAxis ] );
PostActionSignal( p2DSliderDragStart );
}
//-----------------------------------------------------------------------------
// Purpose: Send a message to interested parties when the user ends dragging the slider
//-----------------------------------------------------------------------------
void C2DSlider::SendSliderDragEndMessage()
{
KeyValues *p2DSliderDragEnd = new KeyValues( "2DSliderDragEnd" );
p2DSliderDragEnd->SetFloat( "valueX", m_fValue[ kXAxis ] );
p2DSliderDragEnd->SetFloat( "valueY", m_fValue[ kYAxis ] );
PostActionSignal( p2DSliderDragEnd );
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,67 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeBasePickerPanel.h"
#include "FileSystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/FileOpenDialog.h"
#include "dme_controls/AttributeTextEntry.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeBasePickerPanel::CAttributeBasePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
m_pOpen = new vgui::Button( this, "Open", "...", this, "open" );
// m_pOpen->SetImage( vgui::scheme()->GetImage( "tools/ifm/icon_properties_linkarrow" , false), 0 );
// m_pOpen->SetPaintBorderEnabled( false );
// m_pOpen->SetContentAlignment( vgui::Label::a_center );
}
void CAttributeBasePickerPanel::OnCommand( char const *cmd )
{
if ( !Q_stricmp( cmd, "open" ) )
{
ShowPickerDialog();
}
else
{
BaseClass::OnCommand( cmd );
}
}
void CAttributeBasePickerPanel::PerformLayout()
{
BaseClass::PerformLayout();
int viewWidth, viewHeight;
GetSize( viewWidth, viewHeight );
IImage *arrowImage = vgui::scheme()->GetImage( "tools/ifm/icon_properties_linkarrow" , false);
if( arrowImage )
{
m_pOpen->SetImage( arrowImage , 0 );
m_pOpen->SetPaintBorderEnabled( false );
m_pOpen->SetContentAlignment( vgui::Label::a_center );
m_pOpen->SetBounds( (FirstColumnWidth - ColumnBorderWidth - 16) * 0.5 , ( viewHeight - 16 )* 0.5 , 16, 16 );
}
else
{
m_pOpen->SetBounds( 0, 0, 50, 20 );
}
}

View File

@@ -0,0 +1,162 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeBoolChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "dme_controls/inotifyui.h"
#include "dme_controls/dmecontrols.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Expose DmeEditorAttributeInfo to the scene database
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeEditorBoolChoicesInfo, CDmeEditorBoolChoicesInfo );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
void CDmeEditorBoolChoicesInfo::OnConstruction()
{
// Add a true + false method, default
CreateChoice( "false" );
CreateChoice( "true" );
}
void CDmeEditorBoolChoicesInfo::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Add a choice
//-----------------------------------------------------------------------------
void CDmeEditorBoolChoicesInfo::SetFalseChoice( const char *pChoiceString )
{
//m_Choices[0]->SetValue<CUtlString>( "string", pChoiceString );
CUtlSymbolLarge symbol = g_pDataModel->GetSymbol( pChoiceString );
m_Choices[0]->SetValue<CUtlSymbolLarge>( "string", symbol );
}
void CDmeEditorBoolChoicesInfo::SetTrueChoice( const char *pChoiceString )
{
CUtlSymbolLarge symbol = g_pDataModel->GetSymbol( pChoiceString );
m_Choices[0]->SetValue<CUtlSymbolLarge>( "string", symbol );
}
//-----------------------------------------------------------------------------
// Gets the choices
//-----------------------------------------------------------------------------
const char *CDmeEditorBoolChoicesInfo::GetFalseChoiceString( ) const
{
return GetChoiceString( 0 );
}
const char *CDmeEditorBoolChoicesInfo::GetTrueChoiceString( ) const
{
return GetChoiceString( 1 );
}
//-----------------------------------------------------------------------------
//
// Constructor
//
//-----------------------------------------------------------------------------
CAttributeBoolChoicePanel::CAttributeBoolChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
//-----------------------------------------------------------------------------
// Derived classes can re-implement this to fill the combo box however they like
//-----------------------------------------------------------------------------
void CAttributeBoolChoicePanel::PopulateComboBox( vgui::ComboBox *pComboBox )
{
pComboBox->DeleteAllItems();
CDmeEditorBoolChoicesInfo *pInfo = CastElement<CDmeEditorBoolChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
// Fill in the choices
const char *pFalseChoice = pInfo->GetFalseChoiceString( );
const char *pTrueChoice = pInfo->GetTrueChoiceString( );
// Add the dynamic choices next
if ( pInfo->HasChoiceType() )
{
const char *choices[2];
if ( ElementPropertiesChoices()->GetBoolChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
pFalseChoice = choices[0];
pTrueChoice = choices[1];
}
}
KeyValues *kv = new KeyValues( "entry" );
kv->SetInt( "value", false );
pComboBox->AddItem( pFalseChoice, kv );
kv = new KeyValues( "entry" );
kv->SetInt( "value", true );
pComboBox->AddItem( pTrueChoice, kv );
}
//-----------------------------------------------------------------------------
// Sets the attribute based on the combo box
//-----------------------------------------------------------------------------
void CAttributeBoolChoicePanel::SetAttributeFromComboBox( vgui::ComboBox *pComboBox, KeyValues *pKeyValues )
{
bool bOldValue = GetAttributeValue<bool>();
bool bValue = pKeyValues->GetInt( "value", 0 ) != 0;
if ( bOldValue == bValue )
return;
CUndoScopeGuard guard( NOTIFY_SOURCE_PROPERTIES_TREE, NOTIFY_SETDIRTYFLAG, "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( bValue );
}
//-----------------------------------------------------------------------------
// Sets the combo box from the attribute
//-----------------------------------------------------------------------------
void CAttributeBoolChoicePanel::SetComboBoxFromAttribute( vgui::ComboBox *pComboBox )
{
CDmeEditorBoolChoicesInfo *pInfo = CastElement<CDmeEditorBoolChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
bool bValue = GetAttributeValue<bool>();
// Check the dynamic choices next
if ( pInfo->HasChoiceType() )
{
const char *choices[2];
if ( ElementPropertiesChoices()->GetBoolChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
pComboBox->SetText( choices[ bValue ] );
return;
}
}
pComboBox->SetText( pInfo->GetChoiceString( bValue ) );
}

View File

@@ -0,0 +1,163 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeColorPickerPanel.h"
#include "datamodel/dmelement.h"
#include "vgui_controls/Button.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/colorpickerpanel.h"
#include "tier1/keyvalues.h"
#include "dme_controls/inotifyui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeColorPickerPanel::CAttributeColorPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
m_pOpen = new vgui::Button( this, "Open", "", this, "open" );
}
void CAttributeColorPickerPanel::OnCommand( char const *cmd )
{
if ( !Q_stricmp( cmd, "open" ) )
{
m_InitialColor = GetAttributeValue<Color>();
CColorPickerFrame *pColorPickerDialog = new CColorPickerFrame( this, "Select Color" );
pColorPickerDialog->AddActionSignalTarget( this );
pColorPickerDialog->DoModal( m_InitialColor );
}
else
{
BaseClass::OnCommand( cmd );
}
}
//-----------------------------------------------------------------------------
// Update button color
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::UpdateButtonColor()
{
Color clr = GetAttributeValue<Color>();
clr.SetColor( clr.r(), clr.g(), clr.b(), 255 );
m_pOpen->SetDefaultColor( clr, clr );
m_pOpen->SetArmedColor( clr, clr );
m_pOpen->SetDepressedColor( clr, clr );
}
//-----------------------------------------------------------------------------
// Used to set the current color on the picker button
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::Refresh()
{
BaseClass::Refresh();
UpdateButtonColor();
}
void CAttributeColorPickerPanel::ApplySchemeSettings(IScheme *pScheme)
{
// Need to override the scheme settings for this button
BaseClass::ApplySchemeSettings( pScheme );
UpdateButtonColor();
}
//-----------------------------------------------------------------------------
// Called when the picker gets a new color but apply hasn't happened yet
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::OnPreview( KeyValues *data )
{
{
CDisableUndoScopeGuard guard;
Color c = data->GetColor( "color" );
SetAttributeValue( c );
}
Refresh( );
if ( IsAutoApply() )
{
// NOTE: Don't call Apply since that generates an undo record
CElementTreeNotifyScopeGuard guard( "CAttributeColorPickerPanel::OnPreview", NOTIFY_CHANGE_ATTRIBUTE_VALUE, GetNotify() );
}
else
{
SetDirty( true );
}
}
//-----------------------------------------------------------------------------
// Called when cancel is hit in the picker
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::OnCancelled( )
{
// Restore the initial color
CDisableUndoScopeGuard guard;
SetAttributeValue( m_InitialColor );
Refresh( );
CElementTreeNotifyScopeGuard notify( "CAttributeColorPickerPanel::OnCancelled", NOTIFY_CHANGE_ATTRIBUTE_VALUE, GetNotify() );
SetDirty( false );
}
//-----------------------------------------------------------------------------
// Called when the picker gets a new color
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::OnPicked( KeyValues *data )
{
Color c = data->GetColor( "color" );
if ( c == m_InitialColor )
{
SetDirty( false );
return;
}
// Kind of an evil hack, but "undo" copies the "old value" off for doing undo, and that value is the new value because
// we haven't been tracking undo while manipulating this. So we'll turn off undo and set the value to the original value.
// In effect, all of the wheeling will drop out and it'll look just like we started at the original value and ended up at the
// final value...
{
CDisableUndoScopeGuard guard;
SetAttributeValue( m_InitialColor );
}
{
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( c );
}
if ( IsAutoApply() )
{
Refresh();
SetDirty( false );
}
}
//-----------------------------------------------------------------------------
// Lays out the button position
//-----------------------------------------------------------------------------
void CAttributeColorPickerPanel::PerformLayout()
{
BaseClass::PerformLayout();
int pickerX, pickerY, pickerW, pickerH;
GetPickerBounds( &pickerX, &pickerY, &pickerW, &pickerH );
m_pOpen->SetBounds( pickerX, pickerY, pickerW, pickerH );
}

View File

@@ -0,0 +1,116 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeElementPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "tier1/KeyValues.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
// ----------------------------------------------------------------------------
CAttributeElementPanel::CAttributeElementPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info ), m_pData( 0 )
{
m_pData = new CAttributeTextEntry( this, "AttributeValue" );
m_pData->SetEnabled( !HasFlag( READONLY ) );
m_pData->AddActionSignalTarget(this);
m_pType->SetText( "element" );
m_bShowMemoryUsage = info.m_bShowMemoryUsage;
m_bShowUniqueID = info.m_bShowUniqueID;
}
void CAttributeElementPanel::SetFont( HFont font )
{
BaseClass::SetFont( font );
m_pData->SetFont( font );
m_pType->SetFont( font );
}
void CAttributeElementPanel::Apply()
{
// FIXME: Implement when needed
Assert( 0 );
}
vgui::Panel *CAttributeElementPanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pData );
}
void CAttributeElementPanel::OnCreateDragData( KeyValues *msg )
{
if ( GetPanelElement() )
{
char txt[ 256 ];
m_pData->GetText( txt, sizeof( txt ) );
msg->SetString( "text", txt );
CDmElement *element = NULL;
if ( GetPanelElement()->HasAttribute( GetAttributeName() ) )
{
element = GetElement<CDmElement>( GetAttributeValue<DmElementHandle_t>( ) );
msg->SetInt( "dmeelement", element->GetHandle() );
}
}
}
void CAttributeElementPanel::Refresh()
{
char elemText[ 512 ];
elemText[0] = 0;
CDmElement *element = NULL;
if ( !GetEditorInfo() || !GetEditorInfo()->GetValue<bool>( "hideText" ) )
{
if ( HasAttribute( ) )
{
element = GetAttributeValueElement( );
}
else
{
element = GetPanelElement();
}
}
if ( element )
{
char idstr[ 37 ] = "";
if( m_bShowUniqueID )
{
UniqueIdToString( element->GetId(), idstr, sizeof( idstr ) );
}
if ( m_bShowMemoryUsage )
{
Q_snprintf( elemText, sizeof( elemText ), "%s %s (%.3fMB total / %.3fKB self)", element->GetTypeString(),
idstr, element->EstimateMemoryUsage( TD_DEEP ) / float( 1 << 20 ), element->EstimateMemoryUsage( TD_NONE ) / float( 1 << 10 ) );
}
else
{
Q_snprintf( elemText, sizeof( elemText ), "%s %s", element->GetTypeString(), idstr );
}
}
m_pData->SetText( elemText );
m_pData->SetEnabled(false);
}
void CAttributeElementPanel::PostConstructor()
{
Refresh();
}
// ----------------------------------------------------------------------------

View File

@@ -0,0 +1,182 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeElementPickerPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "datamodel/dmelement.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/ComboBox.h"
#include "dme_controls/dmepicker.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "dme_controls/inotifyui.h"
#include "dme_controls/dmecontrols.h"
#include "dme_controls/dmecontrols_utils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
// ----------------------------------------------------------------------------
CAttributeElementPickerPanel::CAttributeElementPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
m_hEdit = new vgui::Button( this, "Open", "...", this, "open" );
m_pData = new CAttributeTextEntry( this, "AttributeValue" );
m_pData->SetEnabled( !HasFlag( READONLY ) );
m_pData->AddActionSignalTarget(this);
m_pType->SetText( "element" );
m_bShowMemoryUsage = info.m_bShowMemoryUsage;
m_bShowUniqueID = info.m_bShowMemoryUsage;
}
void CAttributeElementPickerPanel::PostConstructor()
{
Refresh();
}
// ----------------------------------------------------------------------------
vgui::Panel *CAttributeElementPickerPanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pData );
}
void CAttributeElementPickerPanel::Apply()
{
// FIXME: Implement when needed
Assert( 0 );
}
void CAttributeElementPickerPanel::Refresh()
{
char elemText[ 512 ];
elemText[0] = 0;
CDmElement *element = NULL;
if ( !GetEditorInfo() || !GetEditorInfo()->GetValue<bool>( "hideText" ) )
{
if ( HasAttribute( ) )
{
element = GetAttributeValueElement( );
}
else
{
element = GetPanelElement();
}
}
if ( element )
{
char idstr[ 37 ] = "";
if( m_bShowUniqueID )
{
UniqueIdToString( element->GetId(), idstr, sizeof( idstr ) );
}
if ( m_bShowMemoryUsage )
{
Q_snprintf( elemText, sizeof( elemText ), "%s %s (%.3fMB total / %.3fKB self)", element->GetTypeString(),
idstr, element->EstimateMemoryUsage( TD_DEEP ) / float( 1 << 20 ), element->EstimateMemoryUsage( TD_NONE ) / float( 1 << 10 ) );
}
else
{
Q_snprintf( elemText, sizeof( elemText ), "%s %s", element->GetTypeString(), idstr );
}
}
m_pData->SetText( elemText );
m_pData->SetEditable( false );
}
//-----------------------------------------------------------------------------
// Called when it's time to show the Dme picker
//-----------------------------------------------------------------------------
void CAttributeElementPickerPanel::ShowPickerDialog()
{
CDmeEditorChoicesInfo *pInfo = CastElement<CDmeEditorChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
// FIXME: Sucky. Should we make GetElementChoiceList return a DmeHandleVec_t?
ElementChoiceList_t choices;
CUtlVector< DmePickerInfo_t > vec;
if ( ElementPropertiesChoices()->GetElementChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
int c = choices.Count();
vec.EnsureCapacity( c );
for ( int i = 0; i < c; ++i )
{
int j = vec.AddToTail( );
vec[j].m_hElement = choices[i].m_pValue->GetHandle();
vec[j].m_pChoiceString = choices[i].m_pChoiceString;
}
}
CDmePickerFrame *pDmePickerDialog = new CDmePickerFrame( this, "Select DME Element" );
pDmePickerDialog->AddActionSignalTarget( this );
pDmePickerDialog->DoModal( vec );
}
//-----------------------------------------------------------------------------
// Called by the dme picker dialog if a dme was selected
//-----------------------------------------------------------------------------
void CAttributeElementPickerPanel::OnDmeSelected( KeyValues *pKeyValues )
{
// We're either going to get an activity or sequence name
CDmElement *pElement = GetElementKeyValue< CDmElement >( pKeyValues, "dme" );
SetAttributeValueElement( pElement );
Refresh( );
}
//-----------------------------------------------------------------------------
// Handle commands
//-----------------------------------------------------------------------------
void CAttributeElementPickerPanel::OnCommand( char const *cmd )
{
if ( !Q_stricmp( cmd, "open" ) )
{
ShowPickerDialog();
}
else
{
BaseClass::OnCommand( cmd );
}
}
//-----------------------------------------------------------------------------
// Layout the panel
//-----------------------------------------------------------------------------
void CAttributeElementPickerPanel::PerformLayout()
{
BaseClass::PerformLayout();
int viewWidth, viewHeight;
GetSize( viewWidth, viewHeight );
IImage *arrowImage = vgui::scheme()->GetImage( "tools/ifm/icon_properties_linkarrow" , false);
if( arrowImage )
{
m_hEdit->SetImage( arrowImage , 0 );
m_hEdit->SetPaintBorderEnabled( false );
m_hEdit->SetContentAlignment( vgui::Label::a_center );
m_hEdit->SetBounds( (FirstColumnWidth - ColumnBorderWidth - 16) * 0.5 , ( viewHeight - 16 )* 0.5 , 16, 16 );
}
else
{
m_hEdit->SetBounds( 0, 0, 100, 20 );
}
}

View File

@@ -0,0 +1,71 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeFilePickerPanel.h"
#include "FileSystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/FileOpenDialog.h"
#include "dme_controls/AttributeTextEntry.h"
#include "vgui/IInput.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Various file picker types
//-----------------------------------------------------------------------------
IMPLEMENT_ATTRIBUTE_FILE_PICKER( CAttributeDmeFilePickerPanel, "Choose DMX file", "DMX", "dmx" );
IMPLEMENT_ATTRIBUTE_FILE_PICKER( CAttributeAviFilePickerPanel, "Choose AVI file", "AVI", "avi" );
IMPLEMENT_ATTRIBUTE_FILE_PICKER( CAttributeShtFilePickerPanel, "Choose Sheet file", "SHT", "sht" );
IMPLEMENT_ATTRIBUTE_FILE_PICKER( CAttributeRawFilePickerPanel, "Choose RAW file", "RAW", "raw" );
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeFilePickerPanel::CAttributeFilePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeFilePickerPanel::~CAttributeFilePickerPanel()
{
}
//-----------------------------------------------------------------------------
// Shows the picker dialog
//-----------------------------------------------------------------------------
void CAttributeFilePickerPanel::ShowPickerDialog()
{
FileOpenDialog *pFileOpenDialog = new FileOpenDialog( this, "Choose file", true );
SetupFileOpenDialog( pFileOpenDialog );
pFileOpenDialog->AddActionSignalTarget( this );
pFileOpenDialog->DoModal( true );
input()->SetAppModalSurface( pFileOpenDialog->GetVPanel() );
}
void CAttributeFilePickerPanel::OnFileSelected( char const *fullpath )
{
if ( !fullpath || !fullpath[ 0 ] )
return;
char relativepath[ 512 ];
g_pFullFileSystem->FullPathToRelativePath( fullpath, relativepath, sizeof( relativepath ) );
// Apply to text panel
m_pData->SetText( relativepath );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,170 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeIntChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "dme_controls/inotifyui.h"
#include "dme_controls/dmecontrols.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Expose DmeEditorAttributeInfo to the scene database
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeEditorIntChoicesInfo, CDmeEditorIntChoicesInfo );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
void CDmeEditorIntChoicesInfo::OnConstruction()
{
}
void CDmeEditorIntChoicesInfo::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Add a choice
//-----------------------------------------------------------------------------
void CDmeEditorIntChoicesInfo::AddChoice( int nValue, const char *pChoiceString )
{
CDmElement *pChoice = CreateChoice( pChoiceString );
pChoice->SetValue( "value", nValue );
}
//-----------------------------------------------------------------------------
// Gets the choices
//-----------------------------------------------------------------------------
int CDmeEditorIntChoicesInfo::GetChoiceValue( int nIndex ) const
{
Assert( ( nIndex < GetChoiceCount() ) && ( nIndex >= 0 ) );
CDmElement *pChoice = m_Choices[nIndex];
if ( !pChoice )
return 0;
return pChoice->GetValue<int>( "value" );
}
//-----------------------------------------------------------------------------
//
// Constructor
//
//-----------------------------------------------------------------------------
CAttributeIntChoicePanel::CAttributeIntChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
//-----------------------------------------------------------------------------
// Derived classes can re-implement this to fill the combo box however they like
//-----------------------------------------------------------------------------
void CAttributeIntChoicePanel::PopulateComboBox( vgui::ComboBox *pComboBox )
{
pComboBox->DeleteAllItems();
CDmeEditorIntChoicesInfo *pInfo = CastElement<CDmeEditorIntChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
// Fill in the choices
int c = pInfo->GetChoiceCount();
for ( int i = 0; i < c; ++i )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetInt( "value", pInfo->GetChoiceValue( i ) );
pComboBox->AddItem( pInfo->GetChoiceString( i ) , kv );
}
// Add the dynamic choices next
if ( pInfo->HasChoiceType() )
{
IntChoiceList_t choices;
if ( ElementPropertiesChoices()->GetIntChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
c = choices.Count();
for ( int i = 0; i < c; ++i )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetInt( "value", choices[i].m_nValue );
pComboBox->AddItem( choices[i].m_pChoiceString, kv );
}
}
}
}
//-----------------------------------------------------------------------------
// Sets the attribute based on the combo box
//-----------------------------------------------------------------------------
void CAttributeIntChoicePanel::SetAttributeFromComboBox( vgui::ComboBox *pComboBox, KeyValues *pKeyValues )
{
int nOldValue = GetAttributeValue<int>();
int nValue = pKeyValues->GetInt( "value", 0 );
if ( nOldValue == nValue )
return;
CUndoScopeGuard guard( NOTIFY_SOURCE_PROPERTIES_TREE, NOTIFY_SETDIRTYFLAG, "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( nValue );
}
//-----------------------------------------------------------------------------
// Sets the combo box from the attribute
//-----------------------------------------------------------------------------
void CAttributeIntChoicePanel::SetComboBoxFromAttribute( vgui::ComboBox *pComboBox )
{
CDmeEditorIntChoicesInfo *pInfo = CastElement<CDmeEditorIntChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
int nValue = GetAttributeValue<int>();
int c = pInfo->GetChoiceCount();
for ( int i = 0; i < c; ++i )
{
if ( nValue == pInfo->GetChoiceValue( i ) )
{
pComboBox->SetText( pInfo->GetChoiceString( i ) );
return;
}
}
// Check the dynamic choices next
if ( pInfo->HasChoiceType() )
{
IntChoiceList_t choices;
if ( ElementPropertiesChoices()->GetIntChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
c = choices.Count();
for ( int i = 0; i < c; ++i )
{
if ( nValue == choices[i].m_nValue )
{
pComboBox->SetText( choices[i].m_pChoiceString );
return;
}
}
}
}
pComboBox->SetText( "Unknown value" );
}

View File

@@ -0,0 +1,91 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeInterpolatorChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "dme_controls/inotifyui.h"
#include "interpolatortypes.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Constructor
//
//-----------------------------------------------------------------------------
CAttributeInterpolatorChoicePanel::CAttributeInterpolatorChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
//-----------------------------------------------------------------------------
// Derived classes can re-implement this to fill the combo box however they like
//-----------------------------------------------------------------------------
void CAttributeInterpolatorChoicePanel::PopulateComboBoxes( vgui::ComboBox *pComboBox[ 2 ] )
{
pComboBox[ 0 ]->DeleteAllItems();
pComboBox[ 1 ]->DeleteAllItems();
// Fill in the choices
int c = NUM_INTERPOLATE_TYPES;
for ( int i = 0; i < c; ++i )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetInt( "value", i );
pComboBox[ 0 ]->AddItem( Interpolator_NameForInterpolator( i, true ) , kv );
kv = new KeyValues( "entry" );
kv->SetInt( "value", i );
pComboBox[ 1 ]->AddItem( Interpolator_NameForInterpolator( i, true ) , kv );
}
}
//-----------------------------------------------------------------------------
// Sets the attribute based on the combo box
//-----------------------------------------------------------------------------
void CAttributeInterpolatorChoicePanel::SetAttributeFromComboBoxes( vgui::ComboBox *pComboBox[ 2 ], KeyValues *pKeyValues[ 2 ] )
{
int nOldValue = GetAttributeValue<int>();
int nValueLeft = pKeyValues[ 0 ]->GetInt( "value", 0 );
int nValueRight= pKeyValues[ 1 ]->GetInt( "value" , 0 );
int nValue = MAKE_CURVE_TYPE( nValueLeft, nValueRight );
// No change
if ( nOldValue == nValue )
return;
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( nValue );
}
//-----------------------------------------------------------------------------
// Sets the combo box from the attribute
//-----------------------------------------------------------------------------
void CAttributeInterpolatorChoicePanel::SetComboBoxesFromAttribute( vgui::ComboBox *pComboBox[ 2 ] )
{
int nValue = GetAttributeValue<int>();
// Decompose
int leftPart = GET_LEFT_CURVE( nValue );
int rightPart = GET_RIGHT_CURVE( nValue );
pComboBox[ 0 ]->SetText( Interpolator_NameForInterpolator( leftPart, true ) );
pComboBox[ 1 ]->SetText( Interpolator_NameForInterpolator( rightPart, true ) );
}

View File

@@ -0,0 +1,66 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =====//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include "dme_controls/AttributeMDLPickerPanel.h"
#include "FileSystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/FileOpenDialog.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/MDLPicker.h"
#include "tier1/keyvalues.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeMDLPickerPanel::CAttributeMDLPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeMDLPickerPanel::~CAttributeMDLPickerPanel()
{
}
//-----------------------------------------------------------------------------
// Called when it's time to show the MDL picker
//-----------------------------------------------------------------------------
void CAttributeMDLPickerPanel::ShowPickerDialog()
{
// Open file
CMDLPickerFrame *pMDLPickerDialog = new CMDLPickerFrame( this, "Select .MDL File" );
pMDLPickerDialog->AddActionSignalTarget( this );
char pszModelName[ 1024 ];
m_pData->GetText( pszModelName, sizeof( pszModelName ) );
pMDLPickerDialog->SetInitialSelection( pszModelName );
pMDLPickerDialog->DoModal( );
}
//-----------------------------------------------------------------------------
// Called when it's time to show the MDL picker
//-----------------------------------------------------------------------------
void CAttributeMDLPickerPanel::OnMDLSelected( KeyValues *pKeyValues )
{
const char *pMDLName = pKeyValues->GetString( "asset", NULL );
if ( !pMDLName || !pMDLName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pMDLName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,109 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =====//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include "dme_controls/AttributeSequencePickerPanel.h"
#include "FileSystem.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/FileOpenDialog.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/MDLPicker.h"
#include "matsys_controls/sequencepicker.h"
#include "tier1/keyvalues.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeSequencePickerPanel::CAttributeSequencePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeSequencePickerPanel::~CAttributeSequencePickerPanel()
{
}
//-----------------------------------------------------------------------------
// Called when it's time to show the MDL picker
//-----------------------------------------------------------------------------
void CAttributeSequencePickerPanel::ShowPickerDialog()
{
CMDLPickerFrame *pMDLPickerDialog = new CMDLPickerFrame( this, "Select .MDL File" );
pMDLPickerDialog->AddActionSignalTarget( this );
pMDLPickerDialog->DoModal( );
}
//-----------------------------------------------------------------------------
// Called when it's time to show the MDL picker
//-----------------------------------------------------------------------------
void CAttributeSequencePickerPanel::OnMDLSelected( KeyValues *pKeyValues )
{
const char *pMDLName = pKeyValues->GetString( "asset", NULL );
char pRelativePath[MAX_PATH];
Q_snprintf( pRelativePath, sizeof(pRelativePath), "models\\%s", pMDLName );
ShowSequencePickerDialog( pRelativePath );
}
//-----------------------------------------------------------------------------
// Called when it's time to show the sequence picker
//-----------------------------------------------------------------------------
void CAttributeSequencePickerPanel::ShowSequencePickerDialog( const char *pMDLName )
{
if ( !pMDLName || !pMDLName[ 0 ] )
return;
// Open file
CSequencePicker::PickType_t pickType = CSequencePicker::PICK_ALL;
const char *pTextType = GetTextType();
if ( pTextType )
{
if ( !Q_stricmp( pTextType, "activityName" ) )
{
pickType = CSequencePicker::PICK_ACTIVITIES;
}
else if ( !Q_stricmp( pTextType, "sequenceName" ) )
{
pickType = CSequencePicker::PICK_SEQUENCES;
}
}
CSequencePickerFrame *pSequencePickerDialog = new CSequencePickerFrame( this, pickType );
pSequencePickerDialog->AddActionSignalTarget( this );
pSequencePickerDialog->DoModal( pMDLName );
}
//-----------------------------------------------------------------------------
// Called when it's time to show the MDL picker
//-----------------------------------------------------------------------------
void CAttributeSequencePickerPanel::OnSequenceSelected( KeyValues *pKeyValues )
{
// We're either going to get an activity or sequence name
const char *pActivityName = pKeyValues->GetString( "activity", NULL );
const char *pSequenceName = pKeyValues->GetString( "sequence", pActivityName );
if ( !pSequenceName || !pSequenceName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pSequenceName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,86 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeSoundPickerPanel.h"
#include "dme_controls/soundpicker.h"
#include "tier1/keyvalues.h"
#include "dme_controls/AttributeTextEntry.h"
#include "datamodel/dmelement.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeSoundPickerPanel::CAttributeSoundPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeSoundPickerPanel::~CAttributeSoundPickerPanel()
{
}
//-----------------------------------------------------------------------------
// Called when it's time to show the sound picker
//-----------------------------------------------------------------------------
void CAttributeSoundPickerPanel::ShowPickerDialog()
{
// Open file
CSoundPicker::PickType_t pickType = CSoundPicker::PICK_ALL;
const char *pTextType = GetTextType();
if ( pTextType )
{
if ( !Q_stricmp( pTextType, "gamesoundName" ) )
{
pickType = CSoundPicker::PICK_GAMESOUNDS;
}
else if ( !Q_stricmp( pTextType, "wavName" ) )
{
pickType = CSoundPicker::PICK_WAVFILES;
}
}
CUtlSymbolLarge symbol = GetAttributeValue<CUtlSymbolLarge>();
const char *pCurrentSound = symbol.String();
CSoundPickerFrame *pSoundPickerDialog = new CSoundPickerFrame( this, "Select sound", pickType );
pSoundPickerDialog->AddActionSignalTarget( this );
if ( pickType == CSoundPicker::PICK_ALL )
{
pickType = CSoundPicker::PICK_NONE;
}
pSoundPickerDialog->DoModal( pickType, pCurrentSound );
}
//-----------------------------------------------------------------------------
// Called when the sound picker has picked a sound
//-----------------------------------------------------------------------------
void CAttributeSoundPickerPanel::OnSoundSelected( KeyValues *pKeyValues )
{
// We're either going to get an activity or sequence name
const char *pGameSoundName = pKeyValues->GetString( "gamesound", NULL );
const char *pSoundName = pKeyValues->GetString( "wav", pGameSoundName );
if ( !pSoundName || !pSoundName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pSoundName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,174 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeStringChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
#include "datamodel/dmelementfactoryhelper.h"
#include "dme_controls/inotifyui.h"
#include "dme_controls/dmecontrols.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Expose DmeEditorAttributeInfo to the scene database
//-----------------------------------------------------------------------------
IMPLEMENT_ELEMENT_FACTORY( DmeEditorStringChoicesInfo, CDmeEditorStringChoicesInfo );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
void CDmeEditorStringChoicesInfo::OnConstruction()
{
}
void CDmeEditorStringChoicesInfo::OnDestruction()
{
}
//-----------------------------------------------------------------------------
// Add a choice
//-----------------------------------------------------------------------------
CDmElement *CDmeEditorStringChoicesInfo::AddChoice( const char *pValueString, const char *pChoiceString )
{
CDmElement *pChoice = CreateChoice( pChoiceString );
pChoice->SetValue( "value", pChoiceString );
return pChoice;
}
//-----------------------------------------------------------------------------
// Gets the choices
//-----------------------------------------------------------------------------
const char *CDmeEditorStringChoicesInfo::GetChoiceValue( int nIndex ) const
{
Assert( ( nIndex < GetChoiceCount() ) && ( nIndex >= 0 ) );
CDmElement *pChoice = m_Choices[nIndex];
if ( !pChoice )
return 0;
CUtlSymbolLarge symbol = pChoice->GetValue< CUtlSymbolLarge >( "value" );
if ( symbol == UTL_INVAL_SYMBOL_LARGE )
return NULL;
return symbol.String();
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeStringChoicePanel::CAttributeStringChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
//-----------------------------------------------------------------------------
// Derived classes can re-implement this to fill the combo box however they like
//-----------------------------------------------------------------------------
void CAttributeStringChoicePanel::PopulateComboBox( vgui::ComboBox *pComboBox )
{
pComboBox->DeleteAllItems();
CDmeEditorStringChoicesInfo *pInfo = CastElement<CDmeEditorStringChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
// Fill in the standard choices first
int c = pInfo->GetChoiceCount();
for ( int i = 0; i < c; ++i )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetString( "value", pInfo->GetChoiceValue( i ) );
pComboBox->AddItem( pInfo->GetChoiceString( i ) , kv );
}
// Add the dynamic choices next
if ( pInfo->HasChoiceType() )
{
StringChoiceList_t choices;
if ( ElementPropertiesChoices()->GetStringChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
c = choices.Count();
for ( int i = 0; i < c; ++i )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetString( "value", choices[i].m_pValue );
pComboBox->AddItem( choices[i].m_pChoiceString, kv );
}
}
}
}
//-----------------------------------------------------------------------------
// Sets the attribute based on the combo box
//-----------------------------------------------------------------------------
void CAttributeStringChoicePanel::SetAttributeFromComboBox( vgui::ComboBox *pComboBox, KeyValues *pKeyValues )
{
CUtlSymbolLarge oldSymbol = GetAttributeValue<CUtlSymbolLarge>();
const char *pOldString = oldSymbol.String();
const char *pNewString = pKeyValues->GetString( "value", "" );
if ( pOldString == pNewString )
return;
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( pNewString );
}
//-----------------------------------------------------------------------------
// Sets the combo box from the attribute
//-----------------------------------------------------------------------------
void CAttributeStringChoicePanel::SetComboBoxFromAttribute( vgui::ComboBox *pComboBox )
{
CDmeEditorStringChoicesInfo *pInfo = CastElement<CDmeEditorStringChoicesInfo>( GetEditorInfo() );
if ( !pInfo )
return;
CUtlSymbolLarge symbol = GetAttributeValue<CUtlSymbolLarge>();
const char *pValue = symbol.String();
int c = pInfo->GetChoiceCount();
for ( int i = 0; i < c; ++i )
{
if ( !Q_stricmp( pValue, pInfo->GetChoiceValue( i ) ) )
{
pComboBox->SetText( pInfo->GetChoiceString( i ) );
return;
}
}
// Check the dynamic choices next
if ( pInfo->HasChoiceType() )
{
StringChoiceList_t choices;
if ( ElementPropertiesChoices()->GetStringChoiceList( pInfo->GetChoiceType(), GetPanelElement(), GetAttributeName(), IsArrayEntry(), choices ) )
{
c = choices.Count();
for ( int i = 0; i < c; ++i )
{
if ( !Q_stricmp( pValue, choices[i].m_pValue ) )
{
pComboBox->SetText( choices[i].m_pChoiceString );
return;
}
}
}
}
pComboBox->SetText( "Unknown value" );
}

View File

@@ -0,0 +1,504 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeTextEntry.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/Menu.h"
#include "datamodel/dmelement.h"
#include "dme_controls/AttributeTextPanel.h"
#include "vgui/MouseCode.h"
#include "vgui/KeyCode.h"
#include "vgui/IInput.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "dme_controls/inotifyui.h"
using namespace vgui;
// ----------------------------------------------------------------------------
// CAttributeTextEntry
CAttributeTextEntry::CAttributeTextEntry( Panel *parent, const char *panelName ) :
BaseClass( parent, panelName ),
m_bValueStored( false ),
m_flOriginalValue( 0.0f )
{
SetDragEnabled( true );
SetDropEnabled( true, 0.5f );
m_szOriginalText[ 0 ] = 0;
AddActionSignalTarget( this );
}
void CAttributeTextEntry::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetBorder(NULL);
//HFont font = pScheme->GetFont( "DmePropertyVerySmall", IsProportional() );
//SetFont(font);
}
//-----------------------------------------------------------------------------
// Returns the parent panel
//-----------------------------------------------------------------------------
inline CAttributeTextPanel *CAttributeTextEntry::GetParentAttributePanel()
{
return static_cast< CAttributeTextPanel * >( GetParent() );
}
//-----------------------------------------------------------------------------
// Drag + drop
//-----------------------------------------------------------------------------
bool CAttributeTextEntry::GetDropContextMenu( Menu *menu, CUtlVector< KeyValues * >& msglist )
{
menu->AddMenuItem( "Drop as Text", "#BxDropText", "droptext", this );
return true;
}
bool CAttributeTextEntry::IsDroppable( CUtlVector< KeyValues * >& msglist )
{
if ( !IsEnabled() )
return false;
if ( msglist.Count() != 1 )
return false;
KeyValues *msg = msglist[ 0 ];
Panel *draggedPanel = ( Panel * )msg->GetPtr( "panel", NULL );
if ( draggedPanel == GetParent() )
return false;
CAttributeTextPanel *pPanel = GetParentAttributePanel();
if ( !pPanel )
return false;
// If a specific text type is specified, then filter if it doesn't match
const char *pTextType = pPanel->GetTextType();
if ( pTextType[0] )
{
const char *pMsgTextType = msg->GetString( "texttype" );
if ( Q_stricmp( pTextType, pMsgTextType ) )
return false;
}
DmAttributeType_t t = pPanel->GetAttributeType();
switch ( t )
{
default:
break;
case AT_ELEMENT:
{
CDmElement *ptr = reinterpret_cast< CDmElement * >( g_pDataModel->GetElement( DmElementHandle_t( msg->GetInt( "root" ) ) ) );
if ( ptr )
{
return true;
}
return false;
}
break;
case AT_ELEMENT_ARRAY:
return false;
}
return true;
}
void CAttributeTextEntry::OnPanelDropped( CUtlVector< KeyValues * >& msglist )
{
if ( msglist.Count() != 1 )
return;
KeyValues *data = msglist[ 0 ];
Panel *draggedPanel = ( Panel * )data->GetPtr( "panel", NULL );
if ( draggedPanel == GetParent() )
return;
CAttributeTextPanel *pPanel = GetParentAttributePanel();
if ( !pPanel )
return;
// If a specific text type is specified, then filter if it doesn't match
const char *pTextType = pPanel->GetTextType();
if ( pTextType[0] )
{
const char *pMsgTextType = data->GetString( "texttype" );
if ( Q_stricmp( pTextType, pMsgTextType ) )
return;
}
const char *cmd = data->GetString( "command" );
if ( !Q_stricmp( cmd, "droptext" ) || !Q_stricmp( cmd, "default" ) )
{
DmAttributeType_t t = pPanel->GetAttributeType();
switch ( t )
{
default:
{
pPanel->SetDirty( true );
SetText( data->GetString( "text" ) );
if ( pPanel->IsAutoApply() )
{
pPanel->Apply();
}
}
break;
case AT_ELEMENT:
{
CDmElement *ptr = reinterpret_cast< CDmElement * >( g_pDataModel->GetElement( DmElementHandle_t( data->GetInt( "root" ) ) ) );
if ( !ptr )
{
break;
}
pPanel->SetDirty( true );
SetText( data->GetString( "text" ) );
if ( pPanel->IsAutoApply() )
{
pPanel->Apply();
}
}
break;
case AT_ELEMENT_ARRAY:
Assert( 0 );
break;
}
}
StoreInitialValue( true );
}
//-----------------------------------------------------------------------------
// Enter causes changes to be applied
//-----------------------------------------------------------------------------
void CAttributeTextEntry::OnKeyCodeTyped(KeyCode code)
{
bool bCtrl = (input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL));
switch ( code )
{
case KEY_ENTER:
{
CAttributeTextPanel *pPanel = GetParentAttributePanel();
if ( !pPanel->IsAutoApply() )
{
pPanel->Apply();
StoreInitialValue( true );
}
else
{
WriteValueToAttribute();
StoreInitialValue( true );
}
}
break;
// Override the base class undo feature, it behaves poorly when typing in data
case KEY_Z:
if ( bCtrl )
{
WriteInitialValueToAttribute( );
break;
}
// NOTE: Fall through to default if it's not Ctrl-Z
default:
BaseClass::OnKeyCodeTyped(code);
break;
}
}
void CAttributeTextEntry::OnTextChanged( KeyValues *data )
{
m_bValueStored = true;
}
//-----------------------------------------------------------------------------
// We'll only create an "undo" record if the values differ upon focus change
//-----------------------------------------------------------------------------
void CAttributeTextEntry::StoreInitialValue( bool bForce )
{
// Already storing value???
if ( m_bValueStored && !bForce )
return;
m_bValueStored = true;
CAttributeTextPanel *pPanel = GetParentAttributePanel();
Assert( pPanel );
switch ( pPanel->GetAttributeType() )
{
case AT_FLOAT:
m_flOriginalValue = pPanel->GetAttributeValue<float>( );
break;
case AT_INT:
m_nOriginalValue = pPanel->GetAttributeValue<int>( );
break;
case AT_BOOL:
m_bOriginalValue = pPanel->GetAttributeValue<bool>( );
break;
default:
GetText( m_szOriginalText, sizeof( m_szOriginalText ) );
break;
}
}
//-----------------------------------------------------------------------------
// Performs undo
//-----------------------------------------------------------------------------
void CAttributeTextEntry::WriteInitialValueToAttribute( )
{
// Already storing value???
if ( !m_bValueStored )
return;
CDisableUndoScopeGuard guard;
CAttributeTextPanel *pPanel = GetParentAttributePanel();
Assert( pPanel );
switch ( pPanel->GetAttributeType() )
{
case AT_FLOAT:
pPanel->SetAttributeValue( m_flOriginalValue );
break;
case AT_INT:
pPanel->SetAttributeValue( m_nOriginalValue );
break;
case AT_BOOL:
pPanel->SetAttributeValue<bool>( m_bOriginalValue );
break;
default:
pPanel->SetAttributeValueFromString( m_szOriginalText );
break;
}
pPanel->SetDirty( false );
pPanel->Refresh();
}
//-----------------------------------------------------------------------------
// We'll only create an "undo" record if the values differ upon focus change
//-----------------------------------------------------------------------------
void CAttributeTextEntry::OnSetFocus()
{
BaseClass::OnSetFocus();
StoreInitialValue();
}
//-----------------------------------------------------------------------------
// Called when focus is lost
//-----------------------------------------------------------------------------
template<class T>
void CAttributeTextEntry::ApplyMouseWheel( T newValue, T originalValue )
{
CAttributeTextPanel *pPanel = GetParentAttributePanel();
// Kind of an evil hack, but "undo" copies the "old value" off for doing undo, and that value is the new value because
// we haven't been tracking undo while manipulating this. So we'll turn off undo and set the value to the original value.
// In effect, all of the wheeling will drop out and it'll look just like we started at the original value and ended up at the
// final value...
{
CDisableUndoScopeGuard guard;
pPanel->SetAttributeValue( originalValue );
}
if ( pPanel->IsAutoApply() )
{
pPanel->Apply();
}
else
{
CElementTreeUndoScopeGuard guard( 0, pPanel->GetNotify(), "Set Attribute Value", "Set Attribute Value" );
pPanel->SetAttributeValue( newValue );
}
}
void CAttributeTextEntry::WriteValueToAttribute()
{
if ( !m_bValueStored )
return;
m_bValueStored = false;
char newText[ MAX_TEXT_LENGTH ];
GetText( newText, sizeof( newText ) );
CAttributeTextPanel *pPanel = GetParentAttributePanel();
Assert( pPanel );
switch (pPanel->GetAttributeType() )
{
case AT_FLOAT:
ApplyMouseWheel( (float)atof(newText), m_flOriginalValue );
break;
case AT_INT:
ApplyMouseWheel( atoi(newText), m_nOriginalValue );
break;
case AT_BOOL:
ApplyMouseWheel( atoi(newText) != 0, m_bOriginalValue );
break;
default:
if ( Q_strcmp( newText, m_szOriginalText ) )
{
pPanel->SetDirty( true );
if ( pPanel->IsAutoApply() )
{
pPanel->Apply();
StoreInitialValue( true );
}
}
else
{
pPanel->SetDirty( false );
}
break;
}
}
//-----------------------------------------------------------------------------
// Called when focus is lost
//-----------------------------------------------------------------------------
void CAttributeTextEntry::OnKillFocus()
{
BaseClass::OnKillFocus();
if ( !IsEnabled() )
return; // don't bother writing data if this attribute is read-only or being driven by a channel
WriteValueToAttribute();
StoreInitialValue();
}
void CAttributeTextEntry::OnMouseWheeled( int delta )
{
// Must have *keyboard* focus for it to work, and alse be writeable and not driven by a channel
if ( !HasFocus() || !IsEnabled() )
{
// Otherwise, let the base class scroll up + down
BaseClass::OnMouseWheeled( delta );
return;
}
CAttributeTextPanel *pPanel = GetParentAttributePanel();
if ( pPanel->GetDirty() )
{
if ( pPanel->IsAutoApply() )
{
pPanel->Apply();
StoreInitialValue( true );
}
else
{
// FIXME: Make this work for non-auto-apply panels
}
}
switch ( pPanel->GetAttributeType() )
{
case AT_FLOAT:
{
float deltaFactor;
if ( input()->IsKeyDown(KEY_LSHIFT) )
{
deltaFactor = ((float)delta) * 10.0f;
}
else if ( input()->IsKeyDown(KEY_LCONTROL) )
{
deltaFactor = ((float)delta) / 100.0;
}
else
{
deltaFactor = ((float)delta) / 10.0;
}
float val = pPanel->GetAttributeValue<float>() + deltaFactor;
if ( input()->IsKeyDown(KEY_LALT) )
{
//val = clamp(val, 0.0, 1.0);
val = (val > 1) ? 1 : ((val < 0) ? 0 : val);
}
{
// Note, these calls to Set won't create Undo Records,
// since we'll check the value in SetFocus/KillFocus so that we
// don't gum up the undo system with hundreds of records...
CDisableUndoScopeGuard guard;
pPanel->SetAttributeValue( val );
}
}
break;
case AT_INT:
{
if ( input()->IsKeyDown(KEY_LSHIFT) )
{
delta *= 10;
}
int val = pPanel->GetAttributeValue<int>() + delta;
{
// Note, these calls to Set won't create Undo Records,
// since we'll check the value in SetFocus/KillFocus so that we
// don't gum up the undo system with hundreds of records...
CDisableUndoScopeGuard guard;
pPanel->SetAttributeValue( val );
}
}
break;
case AT_BOOL:
{
bool val = !pPanel->GetAttributeValue<bool>();
{
// Note, these calls to Set won't create Undo Records,
// since we'll check the value in SetFocus/KillFocus so that we
// don't gum up the undo system with hundreds of records...
CDisableUndoScopeGuard guard;
pPanel->SetAttributeValue( val );
}
}
break;
default:
return;
}
pPanel->Refresh();
if ( pPanel->IsAutoApply() )
{
// NOTE: Don't call Apply since that generates an undo record
CElementTreeNotifyScopeGuard notify( "CAttributeTextEntry::OnMouseWheeled", NOTIFY_CHANGE_ATTRIBUTE_VALUE | NOTIFY_SETDIRTYFLAG, pPanel->GetNotify() );
}
else
{
pPanel->SetDirty( true );
}
//SetDirty(true);
//UpdateTime( m_flLastMouseTime );
//UpdateZoom( -10.0f * delta );
//UpdateTransform();
}
// ----------------------------------------------------------------------------

View File

@@ -0,0 +1,133 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeTextPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "tier1/KeyValues.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "movieobjects/dmechannel.h"
#include "dme_controls/inotifyui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// CAttributeTextPanel constructor
//-----------------------------------------------------------------------------
CAttributeTextPanel::CAttributeTextPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info ), m_pData( 0 ), m_bShowMemoryUsage( info.m_bShowMemoryUsage )
{
m_pData = new CAttributeTextEntry( this, "AttributeValue" );
m_pData->SetEnabled( !HasFlag( READONLY ) && FindChannelTargetingAttribute( GetAttribute() ) == NULL );
m_pData->AddActionSignalTarget(this);
SetAllowKeyBindingChainToParent( false );
}
void CAttributeTextPanel::SetFont( HFont font )
{
BaseClass::SetFont( font );
m_pData->SetFont( font );
}
//-----------------------------------------------------------------------------
// Returns the text type
//-----------------------------------------------------------------------------
const char *CAttributeTextPanel::GetTextType()
{
// If a specific text type is specified, then filter if it doesn't match
CDmeEditorAttributeInfo *pInfo = GetEditorInfo();
const char *pTextType = pInfo ? pInfo->GetValueString( "texttype" ) : NULL;
return pTextType ? pTextType : "";
}
void CAttributeTextPanel::Apply()
{
char txt[ 256 ];
m_pData->GetText( txt, sizeof( txt ) );
// Apply means we no longer look blue
SetDirty( false );
if ( GetAttributeType( ) == AT_UNKNOWN )
{
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValue( "" );
return;
}
char curvalue[ 256 ];
GetAttributeValueAsString( curvalue, sizeof( curvalue ) );
// Only if differnt
if ( Q_strcmp( curvalue, txt ) )
{
CElementTreeUndoScopeGuard guard( NOTIFY_SETDIRTYFLAG, GetNotify(), "Set Attribute Value", "Set Attribute Value" );
SetAttributeValueFromString( txt );
}
}
vgui::Panel *CAttributeTextPanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pData );
}
void CAttributeTextPanel::Refresh()
{
char buf[ 512 ];
if ( IsArrayType( GetAttributeType() ) )
{
int count = GetAttributeArrayCount();
if ( m_bShowMemoryUsage )
{
CDmAttribute *pAttr = GetPanelElement()->GetAttribute( GetAttributeName() );
Q_snprintf( buf, sizeof( buf ), "%d %s (%.3fMB)", count, (count == 1) ? "item" : "items", pAttr->EstimateMemoryUsage( TD_DEEP ) / float( 1 << 20 ) );
}
else
{
Q_snprintf( buf, sizeof( buf ), "%d %s", count, (count == 1) ? "item" : "items" );
}
m_pData->SetText( buf );
m_pData->SetEnabled(false);
}
else if ( GetAttributeType() == AT_ELEMENT )
{
m_pData->SetText( "" );
}
else
{
GetAttributeValueAsString( buf, sizeof( buf ) );
// This is a hack because VMatrix has \n characters in the text and the TextEntry field doesn't show them.
if ( GetAttributeType() == AT_VMATRIX )
{
// Replace \n with ' '
char *p = buf;
while ( *p )
{
if ( *p == '\n' )
*p = ' ';
++p;
}
}
m_pData->SetText( buf );
m_pData->SetEnabled( !HasFlag( READONLY ) && FindChannelTargetingAttribute( GetAttribute() ) == NULL );
}
}
void CAttributeTextPanel::PostConstructor()
{
Refresh();
}

View File

@@ -0,0 +1,380 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeWidgetFactory.h"
#include "tier1/utldict.h"
#include "tier1/KeyValues.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeBooleanPanel.h"
#include "dme_controls/AttributeFilePickerPanel.h"
#include "dme_controls/AttributeBoolChoicePanel.h"
#include "dme_controls/AttributeIntChoicePanel.h"
#include "dme_controls/AttributeStringChoicePanel.h"
#include "dme_controls/AttributeElementPanel.h"
#include "dme_controls/AttributeElementPickerPanel.h"
#include "dme_controls/AttributeMDLPickerPanel.h"
#include "dme_controls/AttributeSequencePickerPanel.h"
#include "dme_controls/AttributeSoundPickerPanel.h"
#include "dme_controls/AttributeAssetPickerPanel.h"
#include "dme_controls/AttributeShaderPickerPanel.h"
#include "dme_controls/AttributeSurfacePropertyPickerPanel.h"
#include "dme_controls/AttributeDetailTypePickerPanel.h"
#include "dme_controls/AttributeColorPickerPanel.h"
#include "dme_controls/AttributeInterpolatorChoicePanel.h"
#include "dme_controls/attributesheetsequencepickerpanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Forward declaration
//-----------------------------------------------------------------------------
class CAttributeWidgetFactoryList;
using namespace vgui;
//-----------------------------------------------------------------------------
// CAttributeWidgetFactoryList class definition
//-----------------------------------------------------------------------------
class CAttributeWidgetFactoryList : public IAttributeWidgetFactoryList
{
public:
// Inherited from IAttributeWidgetFactoryList
virtual IAttributeWidgetFactory *GetWidgetFactory( const char *pWidgetName );
virtual IAttributeWidgetFactory *GetWidgetFactory( CDmElement *object, CDmAttribute *pAttribute, CDmeEditorTypeDictionary *pTypeDictionary );
virtual IAttributeWidgetFactory *GetArrayWidgetFactory( CDmElement *object, CDmAttribute *pAttribute, CDmeEditorTypeDictionary *pTypeDictionary );
virtual void ApplyChanges( vgui::Panel *pWidget, vgui::Panel *pSender = NULL );
virtual void Refresh( vgui::Panel *pWidget, vgui::Panel *pSender = NULL );
// Adds a widget to the factory
void AddWidgetFactory( IAttributeWidgetFactory *pFactory, const char *pWidgetName );
// Finds a widget factory by name
IAttributeWidgetFactory *FindWidgetFactory( const char *pWidgetName );
// Creates a widget using editor attribute info
// vgui::Panel *CreateWidget( vgui::Panel *parent, CDmElement *obj, INotifyUI *pNotify, CDmeEditorAttributeInfo *pWidgetInfo, bool bAutoApply );
private:
CUtlDict< IAttributeWidgetFactory*, unsigned short > m_Factories;
};
//-----------------------------------------------------------------------------
// Singleton instance
//-----------------------------------------------------------------------------
static CAttributeWidgetFactoryList *g_pWidgetFactoryFactoryList;
IAttributeWidgetFactoryList *attributewidgetfactorylist;
CAttributeWidgetFactoryList *GetWidgetFactoryManager()
{
if ( !g_pWidgetFactoryFactoryList )
{
g_pWidgetFactoryFactoryList = new CAttributeWidgetFactoryList;
attributewidgetfactorylist = g_pWidgetFactoryFactoryList;
}
return g_pWidgetFactoryFactoryList;
}
//-----------------------------------------------------------------------------
// Standard implementation of a widget factory
//-----------------------------------------------------------------------------
template < class T >
class CAttributeWidgetFactory : public IAttributeWidgetFactory
{
public:
CAttributeWidgetFactory( const char *pWidgetName )
{
GetWidgetFactoryManager()->AddWidgetFactory( this, pWidgetName );
}
// Backward compat
virtual vgui::Panel *Create( vgui::Panel *pParent, const AttributeWidgetInfo_t &info )
{
CBaseAttributePanel *newPanel = new T( pParent, info );
if ( newPanel )
{
newPanel->PostConstructor();
}
return newPanel;
}
};
//-----------------------------------------------------------------------------
// create all the AttributeWidgetFactorys
//-----------------------------------------------------------------------------
// An Attribute Widget Factory for: text entry
static CAttributeWidgetFactory<CAttributeTextPanel> g_AttributeTextWidgetFactory( "text" );
// An Attribute Widget Factory for: boolean entry
static CAttributeWidgetFactory<CAttributeBooleanPanel> g_AttributeBooleanWidgetFactory( "boolean" );
// An Attribute Widget Factory for: picking files
static CAttributeWidgetFactory<CAttributeDmeFilePickerPanel> g_AttributeFilePickerWidgetFactory( "filepicker" );
// An Attribute Widget Factory for: choosing integers
static CAttributeWidgetFactory<CAttributeBoolChoicePanel> g_AttributeBoolChoiceWidgetFactory( "boolchoice" );
// An Attribute Widget Factory for: choosing integers
static CAttributeWidgetFactory<CAttributeIntChoicePanel> g_AttributeIntChoiceWidgetFactory( "intchoice" );
// An Attribute Widget Factory for: choosing strings
static CAttributeWidgetFactory<CAttributeStringChoicePanel> g_AttributeStringChoiceWidgetFactory( "stringchoice" );
// An Attribute Widget Factory for: elements
static CAttributeWidgetFactory<CAttributeElementPanel> g_AttributeElementWidgetFactory( "element" );
// An Attribute Widget Factory for: picking elements
static CAttributeWidgetFactory<CAttributeElementPickerPanel> g_AttributeElementPickerWidgetFactory( "elementchoice" );
// An Attribute Widget Factory for: picking MDLs
static CAttributeWidgetFactory<CAttributeMDLPickerPanel> g_AttributeMDLPickerWidgetFactory( "mdlpicker" );
// An Attribute Widget Factory for: picking sequences
static CAttributeWidgetFactory<CAttributeSequencePickerPanel> g_AttributeSequencePickerWidgetFactory( "sequencepicker" );
// An Attribute Widget Factory for: picking sounds
static CAttributeWidgetFactory<CAttributeSoundPickerPanel> g_AttributeSoundPickerWidgetFactory( "soundpicker" );
// An Attribute Widget Factory for: picking bsps
static CAttributeWidgetFactory<CAttributeBspPickerPanel> g_AttributeBspPickerWidgetFactory( "bsppicker" );
// An Attribute Widget Factory for: picking vmts
static CAttributeWidgetFactory<CAttributeVmtPickerPanel> g_AttributeVmtPickerWidgetFactory( "vmtpicker" );
// An Attribute Widget Factory for: picking vtfs
static CAttributeWidgetFactory<CAttributeVtfPickerPanel> g_AttributeVtfPickerWidgetFactory( "vtfpicker" );
// An Attribute Widget Factory for: picking tgas
static CAttributeWidgetFactory<CAttributeTgaPickerPanel> g_AttributeTgaPickerWidgetFactory( "tgapicker" );
// An Attribute Widget Factory for: picking shaders
static CAttributeWidgetFactory<CAttributeShaderPickerPanel> g_AttributeShaderPickerWidgetFactory( "shaderpicker" );
// An Attribute Widget Factory for: picking surface properties
static CAttributeWidgetFactory<CAttributeSurfacePropertyPickerPanel> g_AttributeSurfacePropertyPickerWidgetFactory( "surfacepropertypicker" );
// An Attribute Widget Factory for: picking surface properties
static CAttributeWidgetFactory<CAttributeColorPickerPanel> g_AttributeColorPickerWidgetFactory( "colorpicker" );
// An Attribute Widget Factory for: picking avis
static CAttributeWidgetFactory<CAttributeAviFilePickerPanel> g_AttributeAviPickerWidgetFactory( "avipicker" );
// An Attribute Widget Factory for: picking sht
static CAttributeWidgetFactory<CAttributeShtFilePickerPanel> g_AttributeShtPickerWidgetFactory( "shtpicker" );
// An Attribute Widget Factory for: picking detail types
static CAttributeWidgetFactory<CAttributeDetailTypePickerPanel> g_AttributeDetailTypePickerWidgetFactory( "detailtypepicker" );
// An Attribute Widget Factory for: picking color correction lookup files
static CAttributeWidgetFactory<CAttributeRawFilePickerPanel> g_AttributeRawPickerWidgetFactory( "rawpicker" );
// An Attribute Widget Factory for: choosing interpolator types (left and right)
static CAttributeWidgetFactory<CAttributeInterpolatorChoicePanel> g_AttributeInterpolatorChoiceWidgetFactory( "interpolatorchoice" );
// An Attribute Widget Factory for: selecting sheet sequences
static CAttributeWidgetFactory<CAttributeSheetSequencePickerPanel> g_AttributeSheetSequencePickerWidgetFactory( "sheetsequencepicker" );
// Special-case for the second sequence in a double-sequence material
static CAttributeWidgetFactory<CAttributeSheetSequencePickerPanel> g_AttributeSheetSequencePickerWidgetFactorySecond( "sheetsequencepicker_second" );
//-----------------------------------------------------------------------------
// Name-based widget factories
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// g_AttributeWidgetFactories
// Purpose: a mapping of all attribute types to AttributeWidgetFactories
struct DefaultAttributeFactoryEntry_t
{
int attributeType;
IAttributeWidgetFactory *factory;
};
static DefaultAttributeFactoryEntry_t g_AttributeWidgetFactories[] =
{
{ AT_UNKNOWN, NULL },
{ AT_ELEMENT, &g_AttributeElementWidgetFactory },
{ AT_INT, &g_AttributeTextWidgetFactory },
{ AT_FLOAT, &g_AttributeTextWidgetFactory },
{ AT_BOOL, &g_AttributeBooleanWidgetFactory },
{ AT_STRING, &g_AttributeTextWidgetFactory },
{ AT_VOID, &g_AttributeTextWidgetFactory },
{ AT_TIME, &g_AttributeTextWidgetFactory },
{ AT_COLOR, &g_AttributeColorPickerWidgetFactory },
{ AT_VECTOR2, &g_AttributeTextWidgetFactory },
{ AT_VECTOR3, &g_AttributeTextWidgetFactory },
{ AT_VECTOR4, &g_AttributeTextWidgetFactory },
{ AT_QANGLE, &g_AttributeTextWidgetFactory },
{ AT_QUATERNION, &g_AttributeTextWidgetFactory },
{ AT_VMATRIX, &g_AttributeTextWidgetFactory },
{ AT_ELEMENT_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_INT_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_FLOAT_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_BOOL_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_STRING_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_VOID_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_TIME_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_COLOR_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_VECTOR2_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_VECTOR3_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_VECTOR4_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_QANGLE_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_QUATERNION_ARRAY, &g_AttributeTextWidgetFactory },
{ AT_VMATRIX_ARRAY, &g_AttributeTextWidgetFactory },
};
//-----------------------------------------------------------------------------
//
// CAttributeWidgetFactoryList
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Adds a widget to the factory
//-----------------------------------------------------------------------------
void CAttributeWidgetFactoryList::AddWidgetFactory( IAttributeWidgetFactory *pFactory, const char *pWidgetName )
{
m_Factories.Insert( pWidgetName, pFactory );
}
//-----------------------------------------------------------------------------
// Finds a widget factory by name
//-----------------------------------------------------------------------------
IAttributeWidgetFactory *CAttributeWidgetFactoryList::FindWidgetFactory( const char *pWidgetName )
{
unsigned short i = m_Factories.Find( pWidgetName );
if ( i != m_Factories.InvalidIndex() )
return m_Factories[i];
return NULL;
}
//-----------------------------------------------------------------------------
// Returns a factory requested by name
//-----------------------------------------------------------------------------
IAttributeWidgetFactory *CAttributeWidgetFactoryList::GetWidgetFactory( const char *pWidgetName )
{
return FindWidgetFactory( pWidgetName );
}
//-----------------------------------------------------------------------------
// Returns a factory used to create widget for the attribute passed in
//-----------------------------------------------------------------------------
IAttributeWidgetFactory *CAttributeWidgetFactoryList::GetWidgetFactory( CDmElement *object,
CDmAttribute *pAttribute, CDmeEditorTypeDictionary *pTypeDictionary )
{
if ( !object )
return NULL;
DmAttributeType_t attributeType = pAttribute->GetType();
IAttributeWidgetFactory *pFactory = g_AttributeWidgetFactories[ attributeType ].factory;
// Override behavior with editor info, if it exists
if ( pTypeDictionary )
{
const char *pAttributeName = pAttribute->GetName();
CDmeEditorAttributeInfo *pEditorInfo = pTypeDictionary->GetAttributeInfo( object, pAttributeName );
if ( pEditorInfo )
{
if ( !pEditorInfo->m_bIsVisible )
return NULL;
if ( pEditorInfo->GetWidgetName() )
{
IAttributeWidgetFactory *pOverriddenFactory = g_pWidgetFactoryFactoryList->FindWidgetFactory( pEditorInfo->GetWidgetName() );
if ( pOverriddenFactory )
{
pFactory = pOverriddenFactory;
}
}
}
}
return pFactory;
}
//-----------------------------------------------------------------------------
// Returns a factory used to create widgets for entries in an attribute array
//-----------------------------------------------------------------------------
IAttributeWidgetFactory *CAttributeWidgetFactoryList::GetArrayWidgetFactory( CDmElement *object,
CDmAttribute *pAttribute, CDmeEditorTypeDictionary *pTypeDictionary )
{
if ( !object )
return NULL;
DmAttributeType_t attributeType = ArrayTypeToValueType( pAttribute->GetType() );
IAttributeWidgetFactory *pFactory = g_AttributeWidgetFactories[ attributeType ].factory;
// Override behavior with editor info, if it exists
if ( pTypeDictionary )
{
CDmeEditorAttributeInfo *pEditorInfo = pTypeDictionary->GetAttributeArrayInfo( object, pAttribute->GetName() );
if ( pEditorInfo )
{
if ( !pEditorInfo->m_bIsVisible )
return NULL;
if ( pEditorInfo->GetWidgetName() )
{
IAttributeWidgetFactory *pOverriddenFactory = g_pWidgetFactoryFactoryList->FindWidgetFactory( pEditorInfo->GetWidgetName() );
if ( pOverriddenFactory )
{
pFactory = pOverriddenFactory;
}
}
}
}
return pFactory;
}
//-----------------------------------------------------------------------------
// Applies changes to a widget
//-----------------------------------------------------------------------------
void CAttributeWidgetFactoryList::ApplyChanges( vgui::Panel *pWidget, vgui::Panel *pSender )
{
CBaseAttributePanel *pPanel = dynamic_cast< CBaseAttributePanel *>( pWidget );
if ( pPanel && pPanel->GetDirty() )
{
Assert( !pPanel->IsAutoApply() );
vgui::ipanel()->SendMessage( pWidget->GetVPanel(), new KeyValues( "ApplyChanges" ), pSender ? pSender->GetVPanel() : NULL );
}
}
//-----------------------------------------------------------------------------
// Refreshes a widget when attributes change
//-----------------------------------------------------------------------------
void CAttributeWidgetFactoryList::Refresh( vgui::Panel *pWidget, vgui::Panel *pSender )
{
if ( pWidget )
{
vgui::ipanel()->SendMessage( pWidget->GetVPanel(), new KeyValues( "Refresh" ), pSender ? pWidget->GetVPanel() : NULL );
}
}

View File

@@ -0,0 +1,595 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/BaseAnimSetAttributeSliderPanel.h"
#include "movieobjects/dmechannel.h"
#include "movieobjects/dmeanimationset.h"
#include "vgui_controls/TextImage.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/Slider.h"
#include "vgui_controls/PanelListPanel.h"
#include "dme_controls/BaseAnimSetPresetFaderPanel.h"
#include "dme_controls/BaseAnimationSetEditor.h"
#include "dme_controls/attributeslider.h"
#include "dme_controls/dmecontrols_utils.h"
#include "vgui/ISurface.h"
#include "vgui/ISystem.h"
#include "vgui/IInput.h"
#include "vgui/IVgui.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
#define ANIMATION_SET_EDITOR_ATTRIBUTESLIDERS_BUTTONTRAY_HEIGHT 32
const int FREE_SLIDER_LIST = 1500;
//-----------------------------------------------------------------------------
//
// CPresetSideFilterSlider class begins
//
//-----------------------------------------------------------------------------
class CPresetSideFilterSlider : public Slider
{
DECLARE_CLASS_SIMPLE( CPresetSideFilterSlider, Slider );
public:
CPresetSideFilterSlider( CBaseAnimSetAttributeSliderPanel *pParent, const char *panelName );
virtual ~CPresetSideFilterSlider();
float GetPos();
void SetPos( float frac );
protected:
virtual void Paint();
virtual void PaintBackground();
virtual void ApplySchemeSettings( IScheme *scheme );
virtual void GetTrackRect( int &x, int &y, int &w, int &h );
virtual void OnMousePressed(MouseCode code);
virtual void OnMouseDoublePressed(MouseCode code);
private:
CBaseAnimSetAttributeSliderPanel *m_pParent;
Color m_ZeroColor;
Color m_TextColor;
Color m_TextColorFocus;
TextImage *m_pName;
};
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CPresetSideFilterSlider::CPresetSideFilterSlider( CBaseAnimSetAttributeSliderPanel *parent, const char *panelName ) :
BaseClass( (Panel *)parent, panelName ), m_pParent( parent )
{
SetRange( 0, 1000 );
SetDragOnRepositionNob( true );
SetPos( 0.5f );
SetPaintBackgroundEnabled( true );
m_pName = new TextImage( "Preset Side Filter" );
SetBgColor( Color( 128, 128, 128, 128 ) );
m_ZeroColor = Color( 33, 33, 33, 255 );
m_TextColor = Color( 200, 200, 200, 255 );
m_TextColorFocus = Color( 208, 143, 40, 255 );
}
CPresetSideFilterSlider::~CPresetSideFilterSlider()
{
delete m_pName;
}
void CPresetSideFilterSlider::OnMousePressed(MouseCode code)
{
if ( code == MOUSE_RIGHT )
{
SetPos( 0.5f );
return;
}
BaseClass::OnMousePressed( code );
}
void CPresetSideFilterSlider::OnMouseDoublePressed(MouseCode code)
{
if ( code == MOUSE_LEFT )
{
SetPos( 0.5f );
return;
}
BaseClass::OnMouseDoublePressed( code );
}
float CPresetSideFilterSlider::GetPos()
{
return GetValue() * 0.001f;
}
void CPresetSideFilterSlider::SetPos( float frac )
{
SetValue( (int)( frac * 1000.0f + 0.5f ), false );
}
void CPresetSideFilterSlider::ApplySchemeSettings( IScheme *scheme )
{
BaseClass::ApplySchemeSettings( scheme );
m_pName->SetFont( scheme->GetFont( "DefaultBold" ) );
m_pName->SetColor( m_TextColor );
m_pName->ResizeImageToContent();
SetFgColor( Color( 194, 120, 0, 255 ) );
SetThumbWidth( 3 );
}
void CPresetSideFilterSlider::GetTrackRect( int &x, int &y, int &w, int &h )
{
GetSize( w, h );
x = 0;
y = 2;
h -= 4;
}
void CPresetSideFilterSlider::Paint()
{
// horizontal nob
int x, y;
int wide,tall;
GetTrackRect( x, y, wide, tall );
Color col = GetFgColor();
surface()->DrawSetColor( col );
surface()->DrawFilledRect( _nobPos[0], 1, _nobPos[1], GetTall() - 1 );
surface()->DrawSetColor( m_ZeroColor );
surface()->DrawFilledRect( _nobPos[0] - 1, y + 1, _nobPos[0], y + tall - 1 );
}
void CPresetSideFilterSlider::PaintBackground()
{
int w, h;
GetSize( w, h );
int tx, ty, tw, th;
GetTrackRect( tx, ty, tw, th );
surface()->DrawSetColor( m_ZeroColor );
surface()->DrawFilledRect( tx, ty, tx + tw, ty + th );
int cw, ch;
m_pName->SetColor( _dragging ? m_TextColorFocus : m_TextColor );
m_pName->GetContentSize( cw, ch );
m_pName->SetPos( ( w - cw ) * 0.5f, ( h - ch ) * 0.5f );
m_pName->Paint();
}
//-----------------------------------------------------------------------------
//
// CBaseAnimSetAttributeSliderPanel begins
//
//-----------------------------------------------------------------------------
CBaseAnimSetAttributeSliderPanel::CBaseAnimSetAttributeSliderPanel( vgui::Panel *parent, const char *className, CBaseAnimationSetEditor *editor ) :
BaseClass( parent, className ),
m_pController( NULL )
{
m_hEditor = editor;
m_pLeftRightBoth[ 0 ] = new Button( this, "AttributeSliderLeftOnly", "", this, "OnLeftOnly" );
m_pLeftRightBoth[ 1 ] = new Button( this, "AttributeSliderRightOnly", "", this, "OnRightOnly" );
m_pPresetSideFilter = new CPresetSideFilterSlider( this, "PresetSideFilter" );
m_Sliders = new PanelListPanel( this, "AttributeSliders" );
m_Sliders->SetFirstColumnWidth( 0 );
m_Sliders->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, ANIMATION_SET_EDITOR_ATTRIBUTESLIDERS_BUTTONTRAY_HEIGHT,
0, 0
);
m_Sliders->SetVerticalBufferPixels( 0 );
m_pController = editor->GetController();
m_pController->AddControlSelectionChangedListener( this );
ivgui()->AddTickSignal( GetVPanel(), 0 );
InitFreeSliderList( FREE_SLIDER_LIST );
}
void CBaseAnimSetAttributeSliderPanel::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "OnLeftOnly" ) )
{
m_pPresetSideFilter->SetPos( 0.0f );
return;
}
if ( !Q_stricmp( pCommand, "OnRightOnly" ) )
{
m_pPresetSideFilter->SetPos( 1.0f );
return;
}
BaseClass::OnCommand( pCommand );
}
void CBaseAnimSetAttributeSliderPanel::ApplySchemeSettings( IScheme *scheme )
{
BaseClass::ApplySchemeSettings( scheme );
m_Sliders->SetBgColor( Color( 42, 42, 42, 255 ) );
}
void CBaseAnimSetAttributeSliderPanel::PerformLayout()
{
BaseClass::PerformLayout();
int w, h;
GetSize( w, h );
int availH = ANIMATION_SET_EDITOR_ATTRIBUTESLIDERS_BUTTONTRAY_HEIGHT;
int btnSize = 9;
m_pLeftRightBoth[ 0 ]->SetBounds( 15, ( availH - btnSize ) / 2, btnSize, btnSize );
m_pLeftRightBoth[ 1 ]->SetBounds( w - 15, ( availH - btnSize ) / 2, btnSize, btnSize );
m_pPresetSideFilter->SetBounds( 23 + btnSize, 4, w - 38 - 2 * btnSize, availH - 8 );
}
void CBaseAnimSetAttributeSliderPanel::OnTick()
{
BaseClass::OnTick();
bool bVisible = IsVisible();
if ( bVisible )
{
// chain up and see if any parent panel is hiding us
VPANEL p = GetVParent();
while ( p )
{
if ( !ipanel()->IsVisible(p) )
{
bVisible = false;
break;
}
p = ipanel()->GetParent(p);
}
}
if ( !bVisible )
{
OnThink();
}
}
//-----------------------------------------------------------------------------
// Purpose: Determines:
// a) are we holding the ctrl key still, if so
// figures out the crossfade amount of each preset slider with non-zero influence
// b) not holding control, then just see if we are previewing whichever preset the mouse is over
// Input : -
//-----------------------------------------------------------------------------
void CBaseAnimSetAttributeSliderPanel::OnThink()
{
BaseClass::OnThink();
m_pController->UpdatePreviewSliderValues();
m_pController->UpdatePreviewSliderTimes();
ApplySliderValues( false );
UpdateSliderDependencyFlags();
}
void CBaseAnimSetAttributeSliderPanel::ChangeAnimationSetClip( CDmeFilmClip *pFilmClip )
{
RebuildSliderLists();
}
void CBaseAnimSetAttributeSliderPanel::RebuildSliderLists()
{
int c = m_SliderList.Count();
for ( int i = 0 ; i < c; ++i )
{
FreeSlider( m_SliderList[ i ] );
}
m_SliderList.RemoveAll();
m_Sliders->RemoveAll();
CUtlVector< CDmElement * > controlList;
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
while ( CDmeAnimationSet *pAnimSet = traversal.Next() )
{
const CDmaElementArray< CDmElement > &controls = pAnimSet->GetControls();
// Now create sliders for all known controls, nothing visible by default
int controlCount = controls.Count();
for ( int ci = 0 ; ci < controlCount; ++ci )
{
CDmElement *control = controls[ ci ];
if ( !control )
continue;
controlList.AddToTail( control );
}
}
for ( int i = 0; i < controlList.Count(); ++i )
{
CDmElement *control = controlList[ i ];
CAttributeSlider *slider = AllocateSlider();
slider->Init( control, false );
slider->SetVisible( false );
m_SliderList.AddToTail( slider );
// Transform controls get two separate sliders, one for position and one for rotation.
// This is something of an artifact of having separate controls for position and rotation,
// but it is useful for value type in to have a separate slider for each.
CDmeTransformControl *pTransformControl = CastElement< CDmeTransformControl >( control );
if ( pTransformControl )
{
CAttributeSlider *pOrientationSlider = AllocateSlider();
pOrientationSlider->Init( control, true );
pOrientationSlider->SetVisible( false );
m_SliderList.AddToTail( pOrientationSlider );
}
}
}
void CBaseAnimSetAttributeSliderPanel::OnControlsAddedOrRemoved()
{
bool changed = false;
int nSliderIndex = 0;
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
while ( CDmeAnimationSet *pAnimSet = traversal.Next() )
{
// See if every slider is the same as before
const CDmaElementArray< CDmElement > &controls = pAnimSet->GetControls();
int controlCount = controls.Count();
for ( int i = 0 ; i < controlCount; ++i )
{
CDmElement *control = controls[ i ];
if ( !control )
continue;
if ( nSliderIndex >= m_SliderList.Count() )
{
changed = true;
break;
}
CAttributeSlider *pSlider = m_SliderList[ nSliderIndex++ ];
if ( pSlider->GetControl() != control )
{
changed = true;
break;
}
if ( IsTransformControl( control ) )
{
// Transform controls add two sliders so make sure the
// next slider refers to the transform control as well.
pSlider = m_SliderList[ nSliderIndex++ ];
if ( pSlider->GetControl() != control )
{
changed = true;
break;
}
continue;
}
if ( pSlider->IsStereo() != IsStereoControl( control ) )
{
changed = true;
break;
}
}
}
changed = changed || nSliderIndex != m_SliderList.Count();
if ( !changed )
return;
RebuildSliderLists();
}
void CBaseAnimSetAttributeSliderPanel::OnControlSelectionChanged()
{
bool visibleSlidersChanged = false;
// Walk through all sliders and show only those in the symbol table
int c = m_SliderList.Count();
for ( int i = 0; i < c; ++i )
{
CAttributeSlider *pSlider = m_SliderList[ i ];
CDmElement* pSliderControl = pSlider->GetControl();
TransformComponent_t nComponentFlags = m_pController->GetSelectionComponentFlags( pSliderControl );
// If the slider is transform control slider determine if it is the
// slider for the position or rotation and mask the flags accordingly.
LogComponents_t nLogComponentFlags = SelectionInfo_t::ConvertTransformFlagsToLogFlags( nComponentFlags, pSlider->IsOrientation() );
bool bShowSlider = nComponentFlags != 0;
if ( pSlider->IsVisible() != bShowSlider )
{
pSlider->SetVisible( bShowSlider );
visibleSlidersChanged = true;
}
if ( pSlider->VisibleComponents() != nLogComponentFlags )
{
pSlider->SetVisibleComponents( nLogComponentFlags );
}
}
// If nothing changed then nothing else needs to be done
if ( !visibleSlidersChanged )
return;
// If the visibility of entire sliders changed then
// the slider visibility list must be updated.
m_Sliders->RemoveAll();
for ( int i = 0; i < c; ++i )
{
CAttributeSlider *slider = m_SliderList[ i ];
if ( slider->IsVisible() )
{
m_Sliders->AddItem( NULL, slider );
}
}
}
void CBaseAnimSetAttributeSliderPanel::GetTypeInValueForControl( CDmElement *pControl, bool bOrientation, AttributeValue_t &controlValue, const AttributeValue_t &sliderValue )
{
CDmeTransformControl *pTransformControl = CastElement< CDmeTransformControl >( pControl );
if ( pTransformControl && bOrientation )
{
const Quaternion &q = sliderValue.m_Quaternion;
QAngle ang;
QuaternionAngles( q, ang );
controlValue.m_Vector.x = ang.x;
controlValue.m_Vector.y = ang.y;
controlValue.m_Vector.z = ang.z;
}
else
{
controlValue = sliderValue;
}
}
void CBaseAnimSetAttributeSliderPanel::UpdatePreview( char const *pchFormat, ... )
{
}
bool CBaseAnimSetAttributeSliderPanel::ApplySliderValues( bool bForce )
{
bool bValuesChanged = m_pController->ApplySliderValues( bForce );
if ( bValuesChanged )
{
UpdatePreview( "ApplySliderValues\n" );
}
return bValuesChanged;
}
//-----------------------------------------------------------------------------
// Purpose: Update the slider flags specifying if a slider is dependency of the
// currently active slider.
//-----------------------------------------------------------------------------
void CBaseAnimSetAttributeSliderPanel::UpdateSliderDependencyFlags() const
{
bool ctrlDown = input()->IsKeyDown( KEY_LCONTROL ) || input()->IsKeyDown( KEY_RCONTROL );
CAttributeSlider *pPrimarySlider = ctrlDown ? m_pController->GetActiveAttributeSlider() : NULL;
int nSliders = m_SliderList.Count();
for ( int iSlider = 0; iSlider < nSliders; ++iSlider )
{
CAttributeSlider *pSlider = m_SliderList[ iSlider ];
if ( !pSlider )
continue;
pSlider->SetDependent( pPrimarySlider ? pPrimarySlider->IsDependent( pSlider ) : false );
}
}
void CBaseAnimSetAttributeSliderPanel::SetupForPreset( FaderPreview_t &fader )
{
// Nothing special here
}
float CBaseAnimSetAttributeSliderPanel::GetBalanceSliderValue()
{
return m_pPresetSideFilter->GetPos();
}
int CBaseAnimSetAttributeSliderPanel::FindSliderIndexForControl( const CDmElement *control )
{
int c = m_SliderList.Count();
for ( int i = 0; i < c; ++i )
{
if ( m_SliderList[ i ]->GetControl() == control )
return i;
}
return -1;
}
CAttributeSlider *CBaseAnimSetAttributeSliderPanel::FindSliderForControl( const CDmElement *control )
{
int i = FindSliderIndexForControl( control );
if ( i < 0 )
return NULL;
return m_SliderList[ i ];
}
bool CBaseAnimSetAttributeSliderPanel::GetSliderValues( AttributeValue_t *pValue, int nIndex )
{
Assert( pValue );
Assert( nIndex >= 0 && nIndex < m_SliderList.Count() );
CAttributeSlider *pSlider = m_SliderList[ nIndex ];
CAttributeSlider *pAttrSlider = m_pController->GetActiveAttributeSlider();
bool shiftDown = input()->IsKeyDown( KEY_LSHIFT ) || input()->IsKeyDown( KEY_RSHIFT );
bool bPreviewingAttrSlider = pAttrSlider == pSlider && shiftDown;
bool bGetPreview = bPreviewingAttrSlider || m_pController->WasPreviouslyHoldingPresetPreviewKey() || m_pController->IsPresetFaderBeingDragged();
*pValue = bGetPreview ? pSlider->GetPreview() : pSlider->GetValue();
return pSlider->IsVisible();
}
void CBaseAnimSetAttributeSliderPanel::DispatchCurve( int nCurveType )
{
// Nothing, handled by SFM
}
void CBaseAnimSetAttributeSliderPanel::InitFreeSliderList( int nCount )
{
for ( int i = 0; i < nCount; ++i )
{
CAttributeSlider *slider = new CAttributeSlider( this );
slider->SetVisible( false );
m_FreeSliderList.AddToTail( slider );
}
}
CAttributeSlider *CBaseAnimSetAttributeSliderPanel::AllocateSlider()
{
int c = m_FreeSliderList.Count();
if ( c > 0 )
{
CAttributeSlider *slider = m_FreeSliderList[ c - 1 ];
m_FreeSliderList.Remove( c - 1 );
slider->SetVisible( true );
return slider;
}
// Add a new one
CAttributeSlider *slider = new CAttributeSlider( this );
slider->SetVisible( true );
return slider;
}
void CBaseAnimSetAttributeSliderPanel::FreeSlider( CAttributeSlider *slider )
{
slider->SetVisible( false );
m_FreeSliderList.AddToTail( slider );
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,295 @@
//====== Copyright © 1996-2006, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/BaseAnimationSetEditor.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/Splitter.h"
#include "vgui_controls/Menu.h"
#include "studio.h"
#include "dme_controls/BaseAnimSetAttributeSliderPanel.h"
#include "dme_controls/BaseAnimSetPresetFaderPanel.h"
#include "dme_controls/BaseAnimSetControlGroupPanel.h"
#include "dme_controls/dmecontrols_utils.h"
#include "movieobjects/dmechannel.h"
#include "movieobjects/dmeanimationset.h"
#include "movieobjects/dmegamemodel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
#define ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT 38
#define ANIMATION_SET_BUTTON_INSET 0
CBaseAnimationSetEditor::CBaseAnimationSetEditor( vgui::Panel *parent, const char *className, CBaseAnimationSetControl *pAnimationSetController ) :
BaseClass( parent, className ),
m_Layout( LAYOUT_SPLIT ),
m_pController( pAnimationSetController )
{
// SETUP_PANEL( this );
//#pragma warning( disable: 4355 )
m_pController->SetAnimationSetEditorPanel( this );
//#pragma warning( default: 4355 )
PostMessage( GetVPanel(), new KeyValues( "OnChangeLayout", "value", m_Layout ) );
}
CBaseAnimationSetEditor::~CBaseAnimationSetEditor()
{
}
CBaseAnimationSetControl *CBaseAnimationSetEditor::GetController()
{
return m_pController;
}
void CBaseAnimationSetEditor::CreateToolsSubPanels()
{
m_hControlGroup = new CBaseAnimSetControlGroupPanel( (Panel *)NULL, "AnimSetControlGroup", this, false );
m_hPresetFader = new CBaseAnimSetPresetFaderPanel( (Panel *)NULL, "AnimSetPresetFader", this );
m_hAttributeSlider = new CBaseAnimSetAttributeSliderPanel( (Panel *)NULL, "AnimSetAttributeSliderPanel", this );
}
void CBaseAnimationSetEditor::ChangeLayout( EAnimSetLayout_t newLayout )
{
m_Layout = newLayout;
// Make sure these don't get blown away...
m_hControlGroup->SetParent( (Panel *)NULL );
m_hPresetFader->SetParent( (Panel *)NULL );
m_hAttributeSlider->SetParent( (Panel *)NULL );
delete m_Splitter.Get();
m_Splitter = NULL;
CUtlVector< Panel * > list;
list.AddToTail( m_hControlGroup.Get() );
list.AddToTail( m_hPresetFader.Get() );
list.AddToTail( m_hAttributeSlider.Get() );
Splitter *sub = NULL;
switch ( m_Layout )
{
default:
case LAYOUT_SPLIT:
{
m_Splitter = new Splitter( this, "AnimSetEditorMainSplitter", SPLITTER_MODE_VERTICAL, 1 );
m_Splitter->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT,
0, 0
);
m_Splitter->SetBounds( 0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT, GetWide(), GetTall() - ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT );
m_Splitter->SetSplitterColor( Color(32, 32, 32, 255) );
// m_Splitter->EnableBorders( false );
m_hControlGroup->SetParent( m_Splitter->GetChild( 0 ) );
m_hControlGroup->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
sub = new Splitter( m_Splitter->GetChild( 1 ), "AnimSetEditorSubSplitter", SPLITTER_MODE_HORIZONTAL, 1 );
sub->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
m_hPresetFader->SetParent( sub->GetChild( 0 ) );
m_hPresetFader->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
m_hAttributeSlider->SetParent( sub->GetChild( 1 ) );
m_hAttributeSlider->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
}
break;
case LAYOUT_VERTICAL:
{
m_Splitter = new Splitter( this, "AnimSetEditorMainSplitter", SPLITTER_MODE_VERTICAL, 2 );
m_Splitter->SetSplitterColor( Color(32, 32, 32, 255) );
m_Splitter->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT,
0, 0
);
m_Splitter->SetBounds( 0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT, GetWide(), GetTall() - ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT );
for ( int i = 0; i < list.Count(); ++i )
{
list[ i ]->SetParent( m_Splitter->GetChild( i ) );
list[ i ]->SetSize( m_Splitter->GetChild( i )->GetWide(), m_Splitter->GetChild( i )->GetTall() );
list[ i ]->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
}
m_Splitter->EvenlyRespaceSplitters();
}
break;
case LAYOUT_HORIZONTAL:
{
m_Splitter = new Splitter( this, "AnimSetEditorMainSplitter", SPLITTER_MODE_HORIZONTAL, 2 );
m_Splitter->SetSplitterColor( Color(32, 32, 32, 255) );
m_Splitter->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT,
0, 0
);
m_Splitter->SetBounds( 0, ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT, GetWide(), GetTall() - ANIMATION_SET_EDITOR_BUTTONTRAY_HEIGHT );
for ( int i = 0; i < list.Count(); ++i )
{
list[ i ]->SetParent( m_Splitter->GetChild( i ) );
list[ i ]->SetSize( m_Splitter->GetChild( i )->GetWide(), m_Splitter->GetChild( i )->GetTall() );
list[ i ]->SetAutoResize
(
Panel::PIN_TOPLEFT,
Panel::AUTORESIZE_DOWNANDRIGHT,
0, 0,
0, 0
);
}
m_Splitter->EvenlyRespaceSplitters();
}
break;
}
if ( sub )
{
sub->OnSizeChanged( sub->GetWide(), sub->GetTall() );
sub->EvenlyRespaceSplitters();
}
}
void CBaseAnimationSetEditor::OnChangeLayout( int value )
{
ChangeLayout( ( EAnimSetLayout_t )value );
}
void CBaseAnimationSetEditor::OnOpenContextMenu( KeyValues *params )
{
if ( m_hContextMenu.Get() )
{
delete m_hContextMenu.Get();
m_hContextMenu = NULL;
}
m_hContextMenu = new Menu( this, "ActionMenu" );
m_hContextMenu->AddMenuItem( "#BxAnimSetSplitLayout", new KeyValues( "OnChangeLayout", "value", (int)LAYOUT_SPLIT ), this );
m_hContextMenu->AddMenuItem( "#BxAnimSetVerticalLayout", new KeyValues( "OnChangeLayout", "value", (int)LAYOUT_VERTICAL ), this );
m_hContextMenu->AddMenuItem( "#BxAnimSetHorizontalLayout", new KeyValues( "OnChangeLayout", "value", (int)LAYOUT_HORIZONTAL ), this );
Panel *rpanel = reinterpret_cast< Panel * >( params->GetPtr( "contextlabel" ) );
if ( rpanel )
{
// force the menu to compute required width/height
m_hContextMenu->PerformLayout();
m_hContextMenu->PositionRelativeToPanel( rpanel, Menu::DOWN, 0, true );
}
else
{
Menu::PlaceContextMenu( this, m_hContextMenu.Get() );
}
}
void CBaseAnimationSetEditor::OpenTreeViewContextMenu( KeyValues *pItemData )
{
}
void CBaseAnimationSetEditor::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
// Have to manually apply settings here if they aren't attached in hierarchy
if ( m_hControlGroup->GetParent() != this )
{
m_hControlGroup->ApplySchemeSettings( pScheme );
}
if ( m_hPresetFader->GetParent() != this )
{
m_hPresetFader->ApplySchemeSettings( pScheme );
}
if ( m_hAttributeSlider->GetParent() != this )
{
m_hAttributeSlider->ApplySchemeSettings( pScheme );
}
}
CBaseAnimSetControlGroupPanel *CBaseAnimationSetEditor::GetControlGroup()
{
return m_hControlGroup.Get();
}
CBaseAnimSetPresetFaderPanel *CBaseAnimationSetEditor::GetPresetFader()
{
return m_hPresetFader.Get();
}
CBaseAnimSetAttributeSliderPanel *CBaseAnimationSetEditor::GetAttributeSlider()
{
return m_hAttributeSlider.Get();
}
void CBaseAnimationSetEditor::OnControlsAddedOrRemoved()
{
m_pController->OnControlsAddedOrRemoved();
if ( m_hControlGroup )
{
m_hControlGroup->OnControlsAddedOrRemoved();
}
if ( m_hAttributeSlider )
{
m_hAttributeSlider->OnControlsAddedOrRemoved();
}
}
void CBaseAnimationSetEditor::ChangeAnimationSetClip( CDmeFilmClip *pFilmClip )
{
m_pController->ChangeAnimationSetClip( pFilmClip );
if ( m_hControlGroup )
{
m_hControlGroup->ChangeAnimationSetClip( pFilmClip );
}
if ( m_hAttributeSlider )
{
m_hAttributeSlider->ChangeAnimationSetClip( pFilmClip );
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,91 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/BaseAttributeChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CBaseAttributeChoicePanel::CBaseAttributeChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info ), m_pData( 0 )
{
SetDropEnabled( false );
m_pData = new vgui::ComboBox( this, "AttributeValue", 10, false );
m_pData->SetEnabled( !HasFlag( FATTRIB_READONLY ) );
m_pData->AddActionSignalTarget( this );
}
//-----------------------------------------------------------------------------
// Called after the constructor is finished
//-----------------------------------------------------------------------------
void CBaseAttributeChoicePanel::PostConstructor()
{
BaseClass::PostConstructor();
PopulateComboBox( m_pData );
Refresh();
}
void CBaseAttributeChoicePanel::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
HFont font = pScheme->GetFont( "DmePropertyVerySmall", IsProportional() );
m_pData->SetFont(font);
}
vgui::Panel *CBaseAttributeChoicePanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pData );
}
//-----------------------------------------------------------------------------
// Called when it is time to set the attribute from the combo box state
//-----------------------------------------------------------------------------
void CBaseAttributeChoicePanel::Apply( )
{
KeyValues *kv = m_pData->GetActiveItemUserData();
SetAttributeFromComboBox( m_pData, kv );
}
//-----------------------------------------------------------------------------
// Called when it is time to set the combo box from the attribute
//-----------------------------------------------------------------------------
void CBaseAttributeChoicePanel::Refresh()
{
SetComboBoxFromAttribute( m_pData );
}
//-----------------------------------------------------------------------------
// Called when the text in the panel changes
//-----------------------------------------------------------------------------
void CBaseAttributeChoicePanel::OnTextChanged( Panel *panel )
{
if ( IsAutoApply() )
{
Apply();
}
else
{
SetDirty(true);
}
}

View File

@@ -0,0 +1,127 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/BaseAttributeDoubleChoicePanel.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/ComboBox.h"
#include "datamodel/dmelement.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
CDoubleComboBoxContainerPanel::CDoubleComboBoxContainerPanel( vgui::Panel *parent, char const *name ) :
BaseClass( parent, name )
{
m_pBoxes[ 0 ] = m_pBoxes[ 1 ] = NULL;
}
void CDoubleComboBoxContainerPanel::AddComboBox( int slot, vgui::ComboBox *box )
{
m_pBoxes[ slot ] = box;
}
void CDoubleComboBoxContainerPanel::PerformLayout()
{
BaseClass::PerformLayout();
int w, h;
GetSize( w, h );
if ( m_pBoxes[ 0 ] )
{
m_pBoxes[ 0 ]->SetBounds( 0, 0, w/2, h );
}
if ( m_pBoxes[ 1 ] )
{
m_pBoxes[ 1 ]->SetBounds( w/2, 0, w/2, h );
}
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CBaseAttributeDoubleChoicePanel::CBaseAttributeDoubleChoicePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
SetDropEnabled( false );
m_pContainerPanel = new CDoubleComboBoxContainerPanel( this, "Container" );
m_pData[0] = new vgui::ComboBox( m_pContainerPanel, "AttributeValue", 10, false );
m_pData[0]->SetEnabled( !HasFlag( FATTRIB_READONLY ) );
m_pData[0]->AddActionSignalTarget( this );
m_pContainerPanel->AddComboBox( 0, m_pData[ 0 ] );
m_pData[1] = new vgui::ComboBox( m_pContainerPanel, "AttributeValue", 10, false );
m_pData[1]->SetEnabled( !HasFlag( FATTRIB_READONLY ) );
m_pData[1]->AddActionSignalTarget( this );
m_pContainerPanel->AddComboBox( 1, m_pData[ 1 ] );
}
//-----------------------------------------------------------------------------
// Called after the constructor is finished
//-----------------------------------------------------------------------------
void CBaseAttributeDoubleChoicePanel::PostConstructor()
{
BaseClass::PostConstructor();
PopulateComboBoxes( m_pData );
Refresh();
}
void CBaseAttributeDoubleChoicePanel::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
HFont font = pScheme->GetFont( "DmePropertyVerySmall", IsProportional() );
m_pData[0]->SetFont(font);
m_pData[1]->SetFont(font);
}
vgui::Panel *CBaseAttributeDoubleChoicePanel::GetDataPanel()
{
return static_cast< vgui::Panel * >( m_pContainerPanel );
}
//-----------------------------------------------------------------------------
// Called when it is time to set the attribute from the combo box state
//-----------------------------------------------------------------------------
void CBaseAttributeDoubleChoicePanel::Apply( )
{
Assert( m_pData[ 0 ] && m_pData[ 1 ] );
KeyValues *kv[ 2 ];
kv[ 0 ] = m_pData[ 0 ]->GetActiveItemUserData();
kv[ 1 ] = m_pData[ 1 ]->GetActiveItemUserData();
SetAttributeFromComboBoxes( m_pData, kv );
}
//-----------------------------------------------------------------------------
// Called when it is time to set the combo box from the attribute
//-----------------------------------------------------------------------------
void CBaseAttributeDoubleChoicePanel::Refresh()
{
SetComboBoxesFromAttribute( m_pData );
}
//-----------------------------------------------------------------------------
// Called when the text in the panel changes
//-----------------------------------------------------------------------------
void CBaseAttributeDoubleChoicePanel::OnTextChanged( Panel *panel )
{
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,363 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose: base class for all element attribute panels
// An attribute panel is a one line widget that can be used by a list
// or tree control.
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/BaseAttributePanel.h"
#include "dme_controls/attributewidgetfactory.h"
#include "tier1/KeyValues.h"
#include "vgui_controls/Label.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "dme_controls/inotifyui.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Lessfunc for columns.
//-----------------------------------------------------------------------------
bool CBaseAttributePanel::ColInfoLessFunc( const CBaseAttributePanel::colinfo_t& lhs, const CBaseAttributePanel::colinfo_t& rhs )
{
return lhs.panel < rhs.panel;
}
//-----------------------------------------------------------------------------
// CBaseAttributePanel constructor
//-----------------------------------------------------------------------------
CBaseAttributePanel::CBaseAttributePanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info.m_pAttributeName ),
m_pType( 0 ),
m_hObject( info.m_pElement ),
m_hEditorInfo( info.m_pEditorInfo ),
m_hEditorTypeDict( info.m_pEditorTypeDictionary ),
m_pNotify( info.m_pNotify ),
m_nArrayIndex( info.m_nArrayIndex ),
m_ColumnSize( 0, 0, ColInfoLessFunc )
{
Assert( info.m_pElement );
InitializeFlags( info );
Assert( info.m_pAttributeName );
Q_strncpy( m_szAttributeName, info.m_pAttributeName, sizeof( m_szAttributeName ) );
m_pType = new Label( this, "AttributeType", "" );
SetColumnSize( m_pType, 100 );
CDmAttribute *pAttribute = info.m_pElement->GetAttribute( info.m_pAttributeName );
m_AttributeType = pAttribute ? pAttribute->GetType() : AT_UNKNOWN;
if ( m_nArrayIndex >= 0 )
{
m_AttributeType = ArrayTypeToValueType( m_AttributeType );
}
m_pType->SetText( g_pDataModel->GetAttributeNameForType( m_AttributeType ) );
m_hFont = NULL;
// These are draggable
SetDragEnabled( true );
}
//-----------------------------------------------------------------------------
// This only exists so every class always can chain PostConstructors
//-----------------------------------------------------------------------------
void CBaseAttributePanel::PostConstructor()
{
}
//-----------------------------------------------------------------------------
// Initializes flags from the attribute editor info
//-----------------------------------------------------------------------------
void CBaseAttributePanel::InitializeFlags( const AttributeWidgetInfo_t &info )
{
m_nFlags = 0;
if ( info.m_pEditorInfo )
{
if ( info.m_pEditorInfo->m_bHideType )
{
m_nFlags |= HIDETYPE;
}
if ( info.m_pEditorInfo->m_bHideValue )
{
m_nFlags |= HIDEVALUE;
}
if ( info.m_pEditorInfo->m_bIsReadOnly )
{
m_nFlags |= READONLY;
}
}
CDmAttribute *pAttribute = info.m_pElement->GetAttribute( info.m_pAttributeName );
if ( pAttribute && pAttribute->IsFlagSet( FATTRIB_READONLY ) )
{
m_nFlags |= READONLY;
}
if ( info.m_bAutoApply )
{
m_nFlags |= AUTOAPPLY;
}
}
//-----------------------------------------------------------------------------
// Returns the editor info
//-----------------------------------------------------------------------------
CDmeEditorTypeDictionary *CBaseAttributePanel::GetEditorTypeDictionary()
{
return m_hEditorTypeDict;
}
CDmeEditorAttributeInfo *CBaseAttributePanel::GetEditorInfo()
{
return m_hEditorInfo;
}
//-----------------------------------------------------------------------------
// Does the element have the attribute we're attempting to reference?
//-----------------------------------------------------------------------------
bool CBaseAttributePanel::HasAttribute() const
{
return GetPanelElement()->HasAttribute( m_szAttributeName );
}
//-----------------------------------------------------------------------------
// Returns the attribute array count
//-----------------------------------------------------------------------------
int CBaseAttributePanel::GetAttributeArrayCount() const
{
CDmrGenericArrayConst array( GetPanelElement(), m_szAttributeName );
return array.IsValid() ? array.Count() : -1;
}
//-----------------------------------------------------------------------------
// Sets the font
//-----------------------------------------------------------------------------
void CBaseAttributePanel::SetFont( HFont font )
{
m_hFont = font;
m_pType->SetFont(font);
}
//-----------------------------------------------------------------------------
// Applies scheme settings
//-----------------------------------------------------------------------------
void CBaseAttributePanel::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
// set the color of the "type" column
m_pType->SetFgColor( Color ( 160, 160, 160, 255 ) );
if ( GetDirty() )
{
SetBgColor( pScheme->GetColor( "AttributeWidget.DirtyBgColor", Color( 100, 100, 200, 63 ) ) );
}
else
{
SetBgColor( pScheme->GetColor( "Panel.BgColor", Color( 0, 0, 0, 0 ) ) );
}
HFont font = pScheme->GetFont( "DmePropertyVerySmall", IsProportional() );
// m_pType->SetFont(font);
if ( !m_hFont )
{
m_hFont = font;
}
SetFont( m_hFont );
}
//-----------------------------------------------------------------------------
// Gets/Sets the attribute value from a string
//-----------------------------------------------------------------------------
void CBaseAttributePanel::SetAttributeValueFromString( const char *pString )
{
if ( m_nArrayIndex < 0 )
{
GetPanelElement()->SetValueFromString( m_szAttributeName, pString );
}
else
{
CDmrGenericArray array( GetPanelElement(), m_szAttributeName );
array.SetFromString( m_nArrayIndex, pString );
}
}
bool CBaseAttributePanel::GetAttributeValueAsString( char *pBuf, int nLength )
{
CDmElement *pElement = m_hObject.Get();
if ( !pElement )
{
*pBuf = '\0';
return false;
}
if ( m_nArrayIndex < 0 )
{
pElement->GetValueAsString( m_szAttributeName, pBuf, nLength );
}
else
{
CDmrGenericArray array( pElement, m_szAttributeName );
array.GetAsString( m_nArrayIndex, pBuf, nLength );
}
return true;
}
CDmAttribute *CBaseAttributePanel::GetAttribute()
{
CDmElement *pElement = m_hObject.Get();
if ( !pElement )
return NULL;
return pElement->GetAttribute( m_szAttributeName );
}
//-----------------------------------------------------------------------------
// Helper to get/set the attribute value for elements
//-----------------------------------------------------------------------------
CDmElement *CBaseAttributePanel::GetAttributeValueElement()
{
return GetElement< CDmElement >( GetAttributeValue<DmElementHandle_t>( ) );
}
void CBaseAttributePanel::SetAttributeValueElement( CDmElement *pElement )
{
return SetAttributeValue( pElement->GetHandle() );
}
void CBaseAttributePanel::SetDirty( bool dirty )
{
SetFlag( DIRTY, dirty );
InvalidateLayout( false, true );
}
void CBaseAttributePanel::SetColumnSize( Panel *panel, int width )
{
colinfo_t search;
search.panel = panel;
int idx = m_ColumnSize.Find( search );
if ( idx == m_ColumnSize.InvalidIndex() )
{
idx = m_ColumnSize.Insert( search );
}
m_ColumnSize[ idx ].width = width;
}
int CBaseAttributePanel::GetSizeForColumn( Panel *panel )
{
colinfo_t search;
search.panel = panel;
int idx = m_ColumnSize.Find( search );
if ( idx == m_ColumnSize.InvalidIndex() )
{
return 100;
}
return m_ColumnSize[ idx ].width;
}
void CBaseAttributePanel::GetPickerBounds( int *x, int *y, int *w, int *h )
{
int viewX, viewY, viewWidth, viewHeight;
GetBounds( viewX, viewY, viewWidth, viewHeight );
*x = ColumnBorderWidth;
*w = PickerWidth;
*y = MAX(0, ceil((viewHeight - PickerHeight) * 0.5)) + 1;
*h = PickerHeight;
}
//-----------------------------------------------------------------------------
// Creates a widget using editor attribute info
//-----------------------------------------------------------------------------
void CBaseAttributePanel::PerformLayout()
{
BaseClass::PerformLayout();
vgui::Panel *valuePanel = GetDataPanel();
if ( valuePanel && HasFlag( HIDEVALUE ) )
{
valuePanel->SetVisible( false );
}
vgui::Panel *typePanel = m_pType;
if ( typePanel && HasFlag( HIDETYPE ) )
{
typePanel->SetVisible( false );
}
int viewWidth, viewHeight;
GetSize( viewWidth, viewHeight );
if( typePanel->IsVisible() && valuePanel->IsVisible() )
{
valuePanel->SetBounds(
FirstColumnWidth,
1,
viewWidth - FirstColumnWidth - ColumnBorderWidth - TypeColumnWidth - ColumnBorderWidth,
viewHeight );
typePanel->SetBounds(
viewWidth - TypeColumnWidth,
1,
TypeColumnWidth,
viewHeight );
}
else if( typePanel->IsVisible() )
{
typePanel->SetBounds( FirstColumnWidth, 1, viewWidth - FirstColumnWidth - ColumnBorderWidth - ColumnBorderWidth, viewHeight);
}
else if( valuePanel->IsVisible() )
{
valuePanel->SetBounds( FirstColumnWidth, 1, viewWidth - FirstColumnWidth - ColumnBorderWidth - ColumnBorderWidth, viewHeight);
}
}
void CBaseAttributePanel::OnApplyChanges()
{
Assert( !IsAutoApply() );
Apply();
SetDirty(false);
}
void CBaseAttributePanel::OnRefresh()
{
Refresh();
}
void CBaseAttributePanel::OnCreateDragData( KeyValues *msg )
{
if ( GetPanelElement() )
{
msg->SetInt( "root", GetPanelElement() ? GetPanelElement()->GetHandle() : DMELEMENT_HANDLE_INVALID );
msg->SetString( "type", g_pDataModel->GetAttributeNameForType( m_AttributeType ) );
msg->SetString( "attributename", m_szAttributeName );
if ( m_nArrayIndex >= 0 )
{
msg->SetInt( "arrayIndex", m_nArrayIndex );
}
if ( m_AttributeType != AT_ELEMENT && m_AttributeType != AT_ELEMENT_ARRAY )
{
char pTemp[512];
GetAttributeValueAsString( pTemp, sizeof( pTemp ) );
msg->SetString( "text", pTemp );
}
}
}

View File

@@ -0,0 +1,370 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include <math.h>
#include <dme_controls/ChannelGraphPanel.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <vgui/IVGui.h>
#include "vgui/IInput.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
DECLARE_BUILD_FACTORY( CChannelGraphPanel );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CChannelGraphPanel::CChannelGraphPanel( Panel *parent, const char *name )
: BaseClass( parent, name ), m_font( 0 ),
m_graphMinTime( 0 ), m_graphMaxTime( 0 ),
m_graphMinValue( 0.0f ), m_graphMaxValue( 0.0f ),
m_nMouseStartX( -1 ), m_nMouseStartY( -1 ),
m_nMouseLastX( -1 ), m_nMouseLastY( -1 ),
m_nTextBorder( 2 ), m_nGraphOriginX( 40 ), m_nGraphOriginY( 10 )
{
}
void CChannelGraphPanel::SetChannel( CDmeChannel *pChannel )
{
m_hChannel = pChannel;
CDmeLog *pLog = m_hChannel->GetLog();
m_graphMinTime = pLog->GetBeginTime();
m_graphMaxTime = pLog->GetEndTime();
m_graphMinValue = FLT_MAX;
m_graphMaxValue = -FLT_MAX;
int nComponents = NumComponents( pLog->GetDataType() );
int nKeys = pLog->GetKeyCount();
for ( int k = 0; k < nKeys; ++k )
{
DmeTime_t t = pLog->GetKeyTime( k );
for ( int i = 0; i < nComponents; ++i )
{
float f = pLog->GetComponent( t, i );
m_graphMinValue = MIN( m_graphMinValue, f );
m_graphMaxValue = MAX( m_graphMaxValue, f );
}
}
}
//-----------------------------------------------------------------------------
// input methods
//-----------------------------------------------------------------------------
void CChannelGraphPanel::OnSizeChanged( int newWide, int newTall ) // called after the size of a panel has been changed
{
int wide = newWide - m_nGraphOriginX;
int tall = newTall - m_nGraphOriginY;
m_flTimeToPixel = wide / ( m_graphMaxTime - m_graphMinTime ).GetSeconds();
m_flValueToPixel = tall / ( m_graphMaxValue - m_graphMinValue );
}
void CChannelGraphPanel::OnMousePressed( MouseCode code )
{
BaseClass::OnMousePressed( code );
if ( code != MOUSE_LEFT )
return;
vgui::input()->GetCursorPos( m_nMouseStartX, m_nMouseStartY );
ScreenToLocal( m_nMouseStartX, m_nMouseStartY );
m_nMouseLastX = m_nMouseStartX;
m_nMouseLastY = m_nMouseStartY;
input()->SetMouseCapture( GetVPanel() );
}
void CChannelGraphPanel::OnMouseReleased( MouseCode code )
{
BaseClass::OnMouseReleased( code );
if ( code != MOUSE_LEFT )
return;
m_nMouseStartX = m_nMouseStartY = -1;
m_nMouseLastX = m_nMouseLastY = -1;
input()->SetMouseCapture( NULL );
}
void CChannelGraphPanel::OnCursorMoved( int mx, int my )
{
BaseClass::OnCursorMoved( mx, my );
if ( !vgui::input()->IsMouseDown( MOUSE_LEFT ) )
return;
bool bInValueLegend = m_nMouseStartX < m_nGraphOriginX;
bool bInTimeLegend = m_nMouseStartY > GetTall() - m_nGraphOriginY - 1;
if ( bInTimeLegend && bInValueLegend )
{
bInTimeLegend = bInValueLegend = false;
}
int dx = mx - m_nMouseLastX;
int dy = my - m_nMouseLastY;
if ( bInTimeLegend )
{
if ( abs( dy ) > abs( dx ) )
{
m_graphMinTime -= DmeTime_t( dy / m_flTimeToPixel );
m_graphMaxTime += DmeTime_t( dy / m_flTimeToPixel );
m_flTimeToPixel = ( GetWide() - m_nGraphOriginX ) / ( m_graphMaxTime - m_graphMinTime ).GetSeconds();
int x = mx = m_nMouseLastX;
int y = my = m_nMouseLastY;
LocalToScreen( x, y );
vgui::input()->SetCursorPos( x, y );
}
else
{
m_graphMinTime -= DmeTime_t( dx / m_flTimeToPixel );
m_graphMaxTime -= DmeTime_t( dx / m_flTimeToPixel );
}
}
else if ( bInValueLegend )
{
if ( abs( dx ) > abs( dy ) )
{
m_graphMinValue += dx / m_flValueToPixel;
m_graphMaxValue -= dx / m_flValueToPixel;
m_flValueToPixel = ( GetTall() - m_nGraphOriginY ) / ( m_graphMaxValue - m_graphMinValue );
int x = mx = m_nMouseLastX;
int y = my = m_nMouseLastY;
LocalToScreen( x, y );
vgui::input()->SetCursorPos( x, y );
}
else
{
m_graphMinValue += dy / m_flValueToPixel;
m_graphMaxValue += dy / m_flValueToPixel;
}
}
m_nMouseLastX = mx;
m_nMouseLastY = my;
}
void CChannelGraphPanel::OnMouseWheeled( int delta )
{
// TODO - zoom in around current time?
}
//-----------------------------------------------------------------------------
// Purpose: lays out the graph
//-----------------------------------------------------------------------------
void CChannelGraphPanel::PerformLayout()
{
BaseClass::PerformLayout();
}
float GetDisplayIncrement( int windowpixels, int fontpixels, float valuerange, int *pDecimalPlaces = NULL )
{
float ratio = valuerange * fontpixels / ( windowpixels );
int nPower = ( int )ceil( log10( ratio ) );
if ( pDecimalPlaces )
{
*pDecimalPlaces = MAX( 0, -nPower );
}
return pow( 10.0f, nPower );
}
int CChannelGraphPanel::TimeToPixel( DmeTime_t time )
{
return m_nGraphOriginX + ( int )floor( m_flTimeToPixel * ( time - m_graphMinTime ).GetSeconds() + 0.5f );
}
int CChannelGraphPanel::ValueToPixel( float flValue )
{
return m_nGraphOriginY + ( int )floor( m_flValueToPixel * ( flValue - m_graphMinValue ) + 0.5f );
}
//-----------------------------------------------------------------------------
// Purpose: draws the graph
//-----------------------------------------------------------------------------
void CChannelGraphPanel::Paint()
{
// estimate the size of the graph marker text
int wide = GetWide() - m_nGraphOriginX;
int tall = GetTall() - m_nGraphOriginY;
int textwidth = 40, textheight = 10;
surface()->GetTextSize( m_font, L"999.999", textwidth, textheight );
// draw current time marker
DmeTime_t curtime = m_hChannel->GetCurrentTime();
if ( curtime >= m_graphMinTime && curtime <= m_graphMaxTime )
{
Color cyan( 0, 255, 255, 255 );
surface()->DrawSetColor( cyan );
int x = TimeToPixel( curtime );
surface()->DrawLine( x, 0, x, GetTall() - m_nGraphOriginY - 1 );
}
// draw left/bottom graph border
Color black( 0, 0, 0, 255 );
surface()->DrawSetColor( black );
surface()->DrawLine( m_nGraphOriginX, GetTall() - m_nGraphOriginY - 1, GetWide(), GetTall() - m_nGraphOriginY - 1 );
surface()->DrawLine( m_nGraphOriginX, GetTall() - m_nGraphOriginY - 1, m_nGraphOriginX, 0 );
surface()->DrawSetTextColor( black );
surface()->DrawSetTextFont( m_font );
// draw graph tickmarks and values along the left border
int nDecimalPlaces = 0;
float flValueIncrement = GetDisplayIncrement( tall, ( int )( 1.5f * textheight ), m_graphMaxValue - m_graphMinValue, &nDecimalPlaces );
int nMinValueIndex = ( int )ceil ( m_graphMinValue / flValueIncrement );
int nMaxValueIndex = ( int )floor( m_graphMaxValue / flValueIncrement );
float flValue = nMinValueIndex * flValueIncrement;
for ( int i = nMinValueIndex; i <= nMaxValueIndex; ++i, flValue += flValueIncrement )
{
wchar_t pFormat[ 32 ];
_snwprintf( pFormat, ARRAYSIZE( pFormat ), L"%%.%df", nDecimalPlaces );
wchar_t wstring[ 32 ];
_snwprintf( wstring, ARRAYSIZE( wstring ), pFormat, flValue );
int tw = 0, th = 0;
surface()->GetTextSize( m_font, wstring, tw, th );
int y = GetTall() - ValueToPixel( flValue ) - 1;
surface()->DrawSetTextPos( m_nGraphOriginX - m_nTextBorder - tw, y - textheight / 2 );
surface()->DrawPrintText( wstring, wcslen( wstring ) );
surface()->DrawLine( m_nGraphOriginX - m_nTextBorder, y, m_nGraphOriginX, y );
}
// draw graph tickmarks and times along the bottom border
float flTimeIncrement = GetDisplayIncrement( wide, textwidth, ( m_graphMaxTime - m_graphMinTime ).GetSeconds(), &nDecimalPlaces );
int nMinTimeIndex = ( int )ceil ( m_graphMinTime.GetSeconds() / flTimeIncrement );
int nMaxTimeIndex = ( int )floor( m_graphMaxTime.GetSeconds() / flTimeIncrement );
float flTime = nMinTimeIndex * flTimeIncrement;
for ( int i = nMinTimeIndex; i <= nMaxTimeIndex; ++i, flTime += flTimeIncrement )
{
wchar_t pFormat[ 32 ];
_snwprintf( pFormat, ARRAYSIZE( pFormat ), L"%%.%df", nDecimalPlaces );
wchar_t wstring[ 32 ];
_snwprintf( wstring, ARRAYSIZE( wstring ), pFormat, flTime );
int tw = 0, th = 0;
surface()->GetTextSize( m_font, wstring, tw, th );
int x = TimeToPixel( DmeTime_t( flTime ) );
surface()->DrawSetTextPos( x - tw / 2, GetTall() - m_nGraphOriginY + m_nTextBorder - 1 );
surface()->DrawPrintText( wstring, wcslen( wstring ) );
surface()->DrawLine( x, GetTall() - m_nGraphOriginY + m_nTextBorder - 1, x, GetTall() - m_nGraphOriginY - 1 );
}
static Color s_componentColors[] =
{
Color( 255, 0, 0, 255 ),
Color( 0, 255, 0, 255 ),
Color( 0, 0, 255, 255 ),
Color( 0, 0, 0, 255 ),
};
CDmeLog *pLog = m_hChannel->GetLog();
int nComponents = NumComponents( pLog->GetDataType() );
int nKeys = pLog->GetKeyCount();
// draw plotted graph
for ( int i = 0; i < nComponents; ++i )
{
Color &color = s_componentColors[ i % ARRAYSIZE( s_componentColors ) ];
surface()->DrawSetColor( color );
int lastx = -1;
int lasty = -1;
for ( int k = 0; k < nKeys; ++k )
{
DmeTime_t t = pLog->GetKeyTime( k );
float f = pLog->GetComponent( t, i );
int x = TimeToPixel( t );
int y = GetTall() - ValueToPixel( f ) - 1;
if ( k )
{
surface()->DrawLine( lastx, lasty, x, y );
}
surface()->DrawLine( x-1, y, x+1, y );
surface()->DrawLine( x, y-1, x, y+1 );
lastx = x;
lasty = y;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: sets up colors
//-----------------------------------------------------------------------------
void CChannelGraphPanel::ApplySchemeSettings(IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
m_font = pScheme->GetFont( "DefaultVerySmall" );
surface()->GetTextSize( m_font, L"999.9", m_nGraphOriginX, m_nGraphOriginY );
m_nGraphOriginX += 2 * m_nTextBorder;
m_nGraphOriginY += 2 * m_nTextBorder;
SetFgColor(GetSchemeColor("CChannelGraphPanel.FgColor", pScheme));
SetBgColor(GetSchemeColor("CChannelGraphPanel.BgColor", pScheme));
SetBorder(pScheme->GetBorder("ButtonDepressedBorder"));
}
//-----------------------------------------------------------------------------
//
// CChannelGraphFrame methods
//
//-----------------------------------------------------------------------------
CChannelGraphFrame::CChannelGraphFrame( Panel *parent, const char *pTitle )
: BaseClass( parent, "CChannelGraphFrame" )
{
SetTitle( pTitle, true );
SetSizeable( true );
SetCloseButtonVisible( true );
SetMinimumSize( 200, 100 );
SetVisible( true );
SetSize( 400, 200 );
SetPos( 100, 100 );
m_pChannelGraph = new CChannelGraphPanel( this, "ChannelGraph" );
SetScheme( vgui::scheme()->LoadSchemeFromFile( "Resource/BoxRocket.res", "BoxRocket" ) );
}
void CChannelGraphFrame::SetChannel( CDmeChannel *pChannel )
{
m_pChannelGraph->SetChannel( pChannel );
}
void CChannelGraphFrame::OnCommand( const char *cmd )
{
BaseClass::OnCommand( cmd );
m_pChannelGraph->OnCommand( cmd );
}
void CChannelGraphFrame::PerformLayout()
{
BaseClass::PerformLayout();
int border = 5;
int iWidth, iHeight;
GetSize( iWidth, iHeight );
m_pChannelGraph->SetPos( border, GetCaptionHeight() + border );
m_pChannelGraph->SetSize( iWidth - 2 * border, iHeight - GetCaptionHeight() - 2 * border );
}

View File

@@ -0,0 +1,488 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/DmeSourceDCCFilePanel.h"
#include "dme_controls/DmePanel.h"
#include "movieobjects/dmedccmakefile.h"
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/ListPanel.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/InputDialog.h"
#include "vgui_controls/MessageBox.h"
#include "vgui/keycode.h"
#include "tier1/keyvalues.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Hook into the dme panel editor system
//
//-----------------------------------------------------------------------------
IMPLEMENT_DMEPANEL_FACTORY( CDmeSourceDCCFilePanel, DmeSourceDCCFile, "DmeSourceDCCFileDefault", "Maya/XSI Source File Editor", true );
//-----------------------------------------------------------------------------
// Sort by MDL name
//-----------------------------------------------------------------------------
static int __cdecl DccObjectSortFunc( vgui::ListPanel *pPanel, const ListPanelItem &item1, const ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString( "dccobject" );
const char *string2 = item2.kv->GetString( "dccobject" );
return Q_stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor, destructor
//-----------------------------------------------------------------------------
CDmeSourceDCCFilePanel::CDmeSourceDCCFilePanel( vgui::Panel *pParent, const char *pPanelName ) :
BaseClass( pParent, pPanelName )
{
m_pRootDCCObjects = new vgui::ListPanel( this, "DCCObjectList" );
m_pRootDCCObjects->AddColumnHeader( 0, "dccobject", "Maya/XSI Object Name", 100, 0 );
m_pRootDCCObjects->AddActionSignalTarget( this );
m_pRootDCCObjects->SetSortFunc( 0, DccObjectSortFunc );
m_pRootDCCObjects->SetSortColumn( 0 );
// m_pRootDCCObjects->SetSelectIndividualCells( true );
m_pRootDCCObjects->SetEmptyListText("No sources");
// m_pRootDCCObjects->SetDragEnabled( true );
m_pDCCObjectBrowser = new vgui::Button( this, "DCCObjectBrowser", "...", this, "OnBrowseDCCObject" );
m_pDCCObjectName = new vgui::TextEntry( this, "DCCObjectName" );
m_pDCCObjectName->SendNewLine( true );
m_pDCCObjectName->AddActionSignalTarget( this );
m_pAddDCCObject = new vgui::Button( this, "AddDCCObjectButton", "Add", this, "OnAddDCCObject" );
m_pRemoveDCCObject = new vgui::Button( this, "RemoveDCCObjectButton", "Remove", this, "OnRemoveDCCObject" );
m_pApplyChanges = new vgui::Button( this, "ApplyChangesButton", "Apply", this, "OnApplyChanges" );
// Load layout settings; has to happen before pinning occurs in code
LoadControlSettings( "resource/DmeSourceDCCFilePanel.res" );
}
CDmeSourceDCCFilePanel::~CDmeSourceDCCFilePanel()
{
}
//-----------------------------------------------------------------------------
// Marks the file as dirty (or not)
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::SetDirty()
{
PostActionSignal( new KeyValues( "DmeElementChanged" ) );
}
//-----------------------------------------------------------------------------
// Refresh the source list
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::RefreshDCCObjectList( )
{
m_pRootDCCObjects->RemoveAll();
if ( !m_hSourceDCCFile.Get() )
return;
int nCount = m_hSourceDCCFile->m_RootDCCObjects.Count();
for ( int i = 0; i < nCount; ++i )
{
KeyValues *pItemKeys = new KeyValues( "node", "dccobject", m_hSourceDCCFile->m_RootDCCObjects.Get(i) );
pItemKeys->SetInt( "dccObjectIndex", i );
m_pRootDCCObjects->AddItem( pItemKeys, 0, false, false );
}
m_pRootDCCObjects->SortList();
}
//-----------------------------------------------------------------------------
// Resets the state
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::SetDmeElement( CDmeSourceDCCFile *pSourceDCCFile )
{
m_hSourceDCCFile = pSourceDCCFile;
bool bEnabled = ( pSourceDCCFile != NULL );
m_pDCCObjectBrowser->SetEnabled( bEnabled );
m_pAddDCCObject->SetEnabled( bEnabled );
m_pRemoveDCCObject->SetEnabled( bEnabled );
m_pApplyChanges->SetEnabled( bEnabled );
if ( !bEnabled )
{
m_pRootDCCObjects->RemoveAll();
m_pDCCObjectName->SetText( "" );
return;
}
RefreshDCCObjectList();
}
//-----------------------------------------------------------------------------
// Called when a list panel's selection changes
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnItemSelectionChanged( )
{
int nCount = m_pRootDCCObjects->GetSelectedItemsCount();
bool bEnabled = ( nCount > 0 );
bool bMultiselect = ( nCount > 1 );
m_pDCCObjectBrowser->SetEnabled( bEnabled && !bMultiselect );
m_pDCCObjectName->SetEnabled( bEnabled && !bMultiselect );
m_pApplyChanges->SetEnabled( bEnabled && !bMultiselect );
m_pRemoveDCCObject->SetEnabled( bEnabled );
if ( !bEnabled || bMultiselect )
{
m_pDCCObjectName->SetText( "" );
return;
}
int nItemID = m_pRootDCCObjects->GetSelectedItem( 0 );
KeyValues *pKeyValues = m_pRootDCCObjects->GetItem( nItemID );
m_pDCCObjectName->SetText( pKeyValues->GetString( "dccobject" ) );
}
//-----------------------------------------------------------------------------
// Called when a list panel's selection changes
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnItemSelected( KeyValues *kv )
{
Panel *pPanel = (Panel *)kv->GetPtr( "panel", NULL );
if ( pPanel == m_pRootDCCObjects )
{
OnItemSelectionChanged();
return;
}
}
//-----------------------------------------------------------------------------
// Called when a list panel's selection changes
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnItemDeselected( KeyValues *kv )
{
Panel *pPanel = (Panel *)kv->GetPtr( "panel", NULL );
if ( pPanel == m_pRootDCCObjects )
{
OnItemSelectionChanged();
return;
}
}
//-----------------------------------------------------------------------------
// Called when return is hit in a text entry field
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnTextNewLine( KeyValues *kv )
{
if ( !m_hSourceDCCFile.Get() )
return;
Panel *pPanel = (Panel *)kv->GetPtr( "panel", NULL );
if ( pPanel == m_pDCCObjectName )
{
OnDCCObjectNameChanged();
return;
}
}
//-----------------------------------------------------------------------------
// Selects a particular DCC object
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::SelectDCCObject( int nDCCObjectIndex )
{
if ( nDCCObjectIndex < 0 )
{
m_pRootDCCObjects->ClearSelectedItems();
return;
}
int nItemID = m_pRootDCCObjects->FirstItem();
for ( ; nItemID != m_pRootDCCObjects->InvalidItemID(); nItemID = m_pRootDCCObjects->NextItem( nItemID ) )
{
KeyValues *kv = m_pRootDCCObjects->GetItem( nItemID );
if ( kv->GetInt( "dccObjectIndex", -1 ) != nDCCObjectIndex )
continue;
m_pRootDCCObjects->SetSingleSelectedItem( nItemID );
break;
}
}
//-----------------------------------------------------------------------------
// Called when we're browsing for a DCC object and one was selected
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnDCCObjectAdded( const char *pDCCObjectName, KeyValues *pContextKeys )
{
if ( !m_hSourceDCCFile.Get() )
return;
if ( CheckForDuplicateNames( pDCCObjectName ) )
return;
int nIndex = -1;
{
CDisableUndoScopeGuard guard;
nIndex = m_hSourceDCCFile->m_RootDCCObjects.AddToTail( pDCCObjectName );
}
SetDirty( );
RefreshDCCObjectList( );
SelectDCCObject( nIndex );
}
//-----------------------------------------------------------------------------
// Called when the file open dialog for browsing source files selects something
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnInputCompleted( KeyValues *kv )
{
const char *pDCCObjectName = kv->GetString( "text", NULL );
if ( !pDCCObjectName )
return;
KeyValues *pDialogKeys = kv->FindKey( "ChangeDCCObject" );
if ( pDialogKeys )
{
m_pDCCObjectName->SetText( pDCCObjectName );
OnDCCObjectNameChanged();
return;
}
pDialogKeys = kv->FindKey( "AddDCCObject" );
if ( pDialogKeys )
{
OnDCCObjectAdded( pDCCObjectName, pDialogKeys );
return;
}
}
//-----------------------------------------------------------------------------
// Shows the DCC object browser (once we have one)
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::ShowDCCObjectBrowser( const char *pTitle, const char *pPrompt, KeyValues *pDialogKeys )
{
InputDialog *pInput = new InputDialog( this, pTitle, pPrompt );
pInput->SetMultiline( false );
pInput->DoModal( pDialogKeys );
}
//-----------------------------------------------------------------------------
// Called when the button to add a file is clicked
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnAddDCCObject( )
{
if ( m_hSourceDCCFile.Get() )
{
KeyValues *pDialogKeys = new KeyValues( "AddDCCObject" );
ShowDCCObjectBrowser( "Add DCC Object", "Enter DCC object name to add", pDialogKeys );
}
}
//-----------------------------------------------------------------------------
// Called when the button to browse for a source file is clicked
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnBrowseDCCObject( )
{
int nCount = m_pRootDCCObjects->GetSelectedItemsCount();
if ( nCount == 0 || !m_hSourceDCCFile.Get() )
return;
int nItemID = m_pRootDCCObjects->GetSelectedItem( 0 );
KeyValues *pKeyValues = m_pRootDCCObjects->GetItem( nItemID );
int nDCCObjectIndex = pKeyValues->GetInt( "dccObjectIndex", -1 );
KeyValues *pDialogKeys = new KeyValues( "ChangeDCCObject", "dccObjectIndex", nDCCObjectIndex );
ShowDCCObjectBrowser( "Edit Maya/XSI Object", "Enter new name of Maya/XSI object", pDialogKeys );
}
//-----------------------------------------------------------------------------
// Called when the source file name changes
//-----------------------------------------------------------------------------
bool CDmeSourceDCCFilePanel::CheckForDuplicateNames( const char *pDCCObjectName, int nDCCObjectSkipIndex )
{
// Look for the existence of this source already
if ( pDCCObjectName[0] )
{
int nCount = m_hSourceDCCFile->m_RootDCCObjects.Count();
for ( int i = 0; i < nCount; ++i )
{
if ( i == nDCCObjectSkipIndex )
continue;
if ( !Q_stricmp( pDCCObjectName, m_hSourceDCCFile->m_RootDCCObjects[i] ) )
{
vgui::MessageBox *pError = new vgui::MessageBox( "#DmeSourceDCCFile_DuplicateSourceTitle", "#DmeSourceDCCFile_DuplicateSourceText", GetParent() );
pError->DoModal();
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Called when the source file name changes
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnDCCObjectNameChanged()
{
int nCount = m_pRootDCCObjects->GetSelectedItemsCount();
if ( nCount == 0 || !m_hSourceDCCFile.Get() )
return;
int nItemID = m_pRootDCCObjects->GetSelectedItem( 0 );
KeyValues *pKeyValues = m_pRootDCCObjects->GetItem( nItemID );
int nDCCObjectIndex = pKeyValues->GetInt( "dccObjectIndex", -1 );
if ( nDCCObjectIndex < 0 )
return;
char pDCCObjectName[MAX_PATH];
m_pDCCObjectName->GetText( pDCCObjectName, sizeof(pDCCObjectName) );
if ( CheckForDuplicateNames( pDCCObjectName, nDCCObjectIndex ) )
return;
{
CDisableUndoScopeGuard guard;
m_hSourceDCCFile->m_RootDCCObjects.Set( nDCCObjectIndex, pDCCObjectName );
}
pKeyValues->SetString( "dccobject", pDCCObjectName );
m_pRootDCCObjects->ApplyItemChanges( nItemID );
m_pRootDCCObjects->SortList();
SetDirty( );
}
//-----------------------------------------------------------------------------
// Used for sorting below
//-----------------------------------------------------------------------------
static int IntCompare( const void *pSrc1, const void *pSrc2 )
{
int i1 = *(int*)pSrc1;
int i2 = *(int*)pSrc2;
return i1 - i2;
}
//-----------------------------------------------------------------------------
// Called when the button to remove a DCC object is clicked
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnRemoveDCCObject( )
{
int nCount = m_pRootDCCObjects->GetSelectedItemsCount();
if ( nCount == 0 || !m_hSourceDCCFile.Get() )
return;
int nSelectedCount = 0;
int *pDCCObjectIndex = (int*)alloca( nCount*sizeof(int) );
for ( int i = 0; i < nCount; ++i )
{
int nItemID = m_pRootDCCObjects->GetSelectedItem( i );
KeyValues *pKeyValues = m_pRootDCCObjects->GetItem( nItemID );
int nDCCObjectIndex = pKeyValues->GetInt( "dccObjectIndex", -1 );
if ( nDCCObjectIndex < 0 )
continue;
pDCCObjectIndex[nSelectedCount++] = nDCCObjectIndex;
}
if ( nSelectedCount == 0 )
return;
// Sort the object indices so we can remove them all
qsort( pDCCObjectIndex, nSelectedCount, sizeof(int), IntCompare );
// Update the selection to be reasonable after deletion
int nItemID = m_pRootDCCObjects->GetSelectedItem( 0 );
int nRow = m_pRootDCCObjects->GetItemCurrentRow( nItemID );
Assert( nRow >= 0 );
{
CDisableUndoScopeGuard guard;
// Because we sorted it above, removes will occur properly
for ( int i = nSelectedCount; --i >= 0; )
{
m_hSourceDCCFile->m_RootDCCObjects.Remove( pDCCObjectIndex[i] );
}
SetDirty( );
}
RefreshDCCObjectList();
int nVisibleRowCount = m_pRootDCCObjects->GetItemCount();
if ( nVisibleRowCount == 0 )
return;
if ( nRow >= nVisibleRowCount )
{
nRow = nVisibleRowCount - 1;
}
int nNewItemID = m_pRootDCCObjects->GetItemIDFromRow( nRow );
m_pRootDCCObjects->SetSingleSelectedItem( nNewItemID );
}
//-----------------------------------------------------------------------------
// Called when a key is typed
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnKeyCodeTyped( vgui::KeyCode code )
{
if ( code == KEY_DELETE )
{
OnRemoveDCCObject();
return;
}
BaseClass::OnKeyCodeTyped( code );
}
//-----------------------------------------------------------------------------
// Command handler
//-----------------------------------------------------------------------------
void CDmeSourceDCCFilePanel::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "OnBrowseDCCObject" ) )
{
OnBrowseDCCObject();
return;
}
if ( !Q_stricmp( pCommand, "OnAddDCCObject" ) )
{
OnAddDCCObject();
return;
}
if ( !Q_stricmp( pCommand, "OnRemoveDCCObject" ) )
{
OnRemoveDCCObject();
return;
}
if ( !Q_stricmp( pCommand, "OnApplyChanges" ) )
{
OnDCCObjectNameChanged();
return;
}
BaseClass::OnCommand( pCommand );
}

View File

@@ -0,0 +1,143 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/DmeSourceSkinPanel.h"
#include "dme_controls/DmePanel.h"
#include "movieobjects/dmemdlmakefile.h"
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/CheckButton.h"
#include "tier1/keyvalues.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Hook into the dme panel editor system
//
//-----------------------------------------------------------------------------
IMPLEMENT_DMEPANEL_FACTORY( CDmeSourceSkinPanel, DmeSourceSkin, "DmeSourceSkinDefault", "MDL Skin Editor", true );
//-----------------------------------------------------------------------------
// Purpose: Constructor, destructor
//-----------------------------------------------------------------------------
CDmeSourceSkinPanel::CDmeSourceSkinPanel( vgui::Panel *pParent, const char *pPanelName ) :
BaseClass( pParent, pPanelName )
{
m_pSkinName = new vgui::TextEntry( this, "SkinName" );
m_pSkinName->AddActionSignalTarget( this );
m_pScale = new vgui::TextEntry( this, "Scale" );
m_pScale->AddActionSignalTarget( this );
m_pFlipTriangles = new vgui::CheckButton( this, "FlipTriangles", "" );
m_pFlipTriangles->AddActionSignalTarget( this );
// Load layout settings; has to happen before pinning occurs in code
LoadControlSettings( "resource/DmeSourceSkinPanel.res" );
}
CDmeSourceSkinPanel::~CDmeSourceSkinPanel()
{
}
//-----------------------------------------------------------------------------
// Marks the file as dirty (or not)
//-----------------------------------------------------------------------------
void CDmeSourceSkinPanel::SetDirty()
{
PostActionSignal( new KeyValues( "DmeElementChanged" ) );
}
//-----------------------------------------------------------------------------
// Resets the state
//-----------------------------------------------------------------------------
void CDmeSourceSkinPanel::SetDmeElement( CDmeSourceSkin *pSourceSkin )
{
m_hSourceSkin = pSourceSkin;
bool bEnabled = (pSourceSkin != NULL);
m_pSkinName->SetEnabled( bEnabled );
m_pScale->SetEnabled( bEnabled );
m_pFlipTriangles->SetEnabled( bEnabled );
if ( !bEnabled )
{
m_pSkinName->SetText( "" );
m_pScale->SetText( "" );
m_pFlipTriangles->SetSelected( false );
return;
}
char pBuf[32];
Q_snprintf( pBuf, sizeof(pBuf), "%.3f", pSourceSkin->m_flScale.Get() );
m_pSkinName->SetText( pSourceSkin->m_SkinName );
m_pScale->SetText( pBuf );
m_pFlipTriangles->SetSelected( pSourceSkin->m_bFlipTriangles );
}
//-----------------------------------------------------------------------------
// Command handler
//-----------------------------------------------------------------------------
void CDmeSourceSkinPanel::OnCheckButtonChecked( int nChecked )
{
if ( !m_hSourceSkin.Get() )
return;
bool bFlipTriangles = ( nChecked != 0 );
if ( bFlipTriangles != m_hSourceSkin->m_bFlipTriangles )
{
m_hSourceSkin->m_bFlipTriangles = bFlipTriangles;
SetDirty();
}
}
//-----------------------------------------------------------------------------
// Called when something is typed in a text entry field
//-----------------------------------------------------------------------------
void CDmeSourceSkinPanel::OnTextChanged( KeyValues *kv )
{
if ( !m_hSourceSkin.Get() )
return;
Panel *pPanel = (Panel *)kv->GetPtr( "panel", NULL );
if ( pPanel == m_pSkinName )
{
char pTextBuf[256];
m_pSkinName->GetText( pTextBuf, sizeof( pTextBuf) );
if ( Q_stricmp( pTextBuf, m_hSourceSkin->m_SkinName ) )
{
m_hSourceSkin->m_SkinName = pTextBuf;
SetDirty();
}
return;
}
if ( pPanel == m_pScale )
{
char pTextBuf[256];
m_pScale->GetText( pTextBuf, sizeof( pTextBuf) );
float flScale = atoi( pTextBuf );
if ( flScale != m_hSourceSkin->m_flScale )
{
m_hSourceSkin->m_flScale = flScale;
SetDirty();
}
return;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "KeyValues.h"
#include "dme_controls/ElementPropertiesTree.h"
#include "datamodel/dmelement.h"
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/ComboBox.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/PanelListPanel.h"
#include "FactoryOverloads.h"
void CFactoryOverloads::AddOverload(
char const *attributeName,
IAttributeWidgetFactory *newFactory,
IAttributeElementChoiceList *newChoiceList )
{
Assert( attributeName );
Assert( newFactory || newChoiceList );
if ( !newFactory )
{
return;
}
Entry_t e;
e.factory = newFactory;
e.choices = newChoiceList;
m_Overloads.Insert( attributeName, e );
}
int CFactoryOverloads::Count()
{
return m_Overloads.Count();
}
char const *CFactoryOverloads::Name( int index )
{
return m_Overloads.GetElementName( index );
}
IAttributeWidgetFactory *CFactoryOverloads::Factory( int index )
{
return m_Overloads[ index ].factory;
}
IAttributeElementChoiceList *CFactoryOverloads::ChoiceList( int index )
{
return m_Overloads[ index ].choices;
}

View File

@@ -0,0 +1,49 @@
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef FACTORYOVERLOADS_H
#define FACTORYOVERLOADS_H
#ifdef _WIN32
#pragma once
#endif
#include "UtlDict.h"
class IAttributeWidgetFactory;
class IAttributeElementChoiceList;
class CFactoryOverloads : public IFactoryOverloads
{
public:
virtual void AddOverload
(
char const *attributeName,
IAttributeWidgetFactory *newFactory,
IAttributeElementChoiceList *newChoiceList
);
int Count();
char const *Name( int index );
IAttributeWidgetFactory *Factory( int index );
IAttributeElementChoiceList *ChoiceList( int index );
private:
struct Entry_t
{
Entry_t() :
factory( 0 ),
choices( 0 )
{
}
IAttributeWidgetFactory *factory;
IAttributeElementChoiceList *choices;
};
CUtlDict< Entry_t, int > m_Overloads;
};
#endif // FACTORYOVERLOADS_H

View File

@@ -0,0 +1,616 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/filelistmanager.h"
#include "vgui_controls/FileOpenDialog.h"
#include "vgui_controls/menu.h"
#include "vgui_controls/messagebox.h"
#include "datamodel/idatamodel.h"
#include "datamodel/dmelement.h"
#include "datamodel/dmattribute.h"
#include "datamodel/dmattributevar.h"
#include "vgui/ISurface.h"
#include <vgui/IInput.h>
#include "vgui/mousecode.h"
#include "tier1/strtools.h"
#include "tier1/KeyValues.h"
#include "tier2/tier2.h"
#include "p4lib/ip4.h"
#include "filesystem.h"
#include "dme_controls/INotifyUI.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
template < int C >
int ListPanelStringSortFunc( vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2 );
struct ColumnInfo_t
{
char const *columnName;
char const *columnText;
int startingWidth;
int flags;
vgui::SortFunc *pfnSort;
vgui::Label::Alignment alignment;
};
enum ColumnIndex_t
{
CI_FILENAME,
CI_PATH,
CI_LOADED,
CI_NUMELEMENTS,
CI_CHANGED,
CI_INPERFORCE,
CI_OPENFOREDIT,
};
const int baseflags = vgui::ListPanel::COLUMN_UNHIDABLE;
const int fixedflags = vgui::ListPanel::COLUMN_UNHIDABLE | vgui::ListPanel::COLUMN_FIXEDSIZE;
static ColumnInfo_t g_ColInfo[] =
{
{ "filename", "#BxFileManager_Filename", 150, baseflags, ListPanelStringSortFunc< CI_FILENAME >, vgui::Label::a_west },
{ "path", "#BxFileManager_Path", 240, baseflags, ListPanelStringSortFunc< CI_PATH >, vgui::Label::a_west },
{ "loaded", "#BxFileManager_Loaded", 40, fixedflags, ListPanelStringSortFunc< CI_LOADED >, vgui::Label::a_center },
{ "numelements", "#BxFileManager_NumElements", 60, fixedflags, ListPanelStringSortFunc< CI_NUMELEMENTS >, vgui::Label::a_east },
{ "changed", "#BxFileManager_Changed", 50, fixedflags, ListPanelStringSortFunc< CI_CHANGED >, vgui::Label::a_center },
{ "in_perforce", "#BxFileManager_P4Exists", 35, fixedflags, ListPanelStringSortFunc< CI_INPERFORCE >, vgui::Label::a_center },
{ "open_for_edit", "#BxFileManager_P4Edit", 40, fixedflags, ListPanelStringSortFunc< CI_OPENFOREDIT >, vgui::Label::a_center },
};
const char *GetKey( ColumnIndex_t ci )
{
return g_ColInfo[ ci ].columnName;
}
template < int C >
int ListPanelStringSortFunc( vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2 )
{
NOTE_UNUSED( pPanel );
const char *pKey = GetKey( ( ColumnIndex_t )C );
const char *string1 = item1.kv->GetString( pKey );
const char *string2 = item2.kv->GetString( pKey );
return Q_stricmp( string1, string2 );
}
void AddColumn( CFileListManager *pFileManager, ColumnIndex_t ci )
{
pFileManager->AddColumnHeader( ci, g_ColInfo[ ci ].columnName, g_ColInfo[ ci ].columnText, g_ColInfo[ ci ].startingWidth, g_ColInfo[ ci ].flags );
pFileManager->SetSortFunc( ci, g_ColInfo[ ci ].pfnSort );
pFileManager->SetColumnTextAlignment( ci, g_ColInfo[ ci ].alignment );
}
CFileListManager::CFileListManager( vgui::Panel *parent ) : BaseClass( parent, "FileListManager" )
{
SetMultiselectEnabled( true );
SetVisible( true );
m_bRefreshRequired = false;
SetSize( 800, 200 );
SetPos( 100, 100 );
AddColumn( this, CI_FILENAME );
AddColumn( this, CI_PATH );
AddColumn( this, CI_LOADED );
AddColumn( this, CI_NUMELEMENTS );
AddColumn( this, CI_CHANGED );
AddColumn( this, CI_INPERFORCE );
AddColumn( this, CI_OPENFOREDIT );
SetSortColumn( 0 );
Refresh();
SetScheme( vgui::scheme()->LoadSchemeFromFile( "Resource/BoxRocket.res", "BoxRocket" ) );
// LoadControlSettings( "resource/BxFileListManager.res" );
}
int CFileListManager::AddItem( DmFileId_t fileid, const char *pFilename, const char *pPath, bool bLoaded, int nElements, bool bChanged, bool bInPerforce, bool bOpenForEdit )
{
KeyValues *kv = new KeyValues( "", GetKey( CI_FILENAME ), pFilename, GetKey( CI_PATH ), pPath );
kv->SetInt ( GetKey( CI_NUMELEMENTS ), nElements );
kv->SetString( GetKey( CI_LOADED ), bLoaded ? "Y" : "N" );
kv->SetString( GetKey( CI_CHANGED ), bChanged ? "Y" : "N" );
kv->SetString( GetKey( CI_INPERFORCE ), bInPerforce ? "Y" : "N" );
kv->SetString( GetKey( CI_OPENFOREDIT ), bOpenForEdit ? "Y" : "N" );
int itemID = BaseClass::AddItem( kv, fileid, false, false );
kv->deleteThis();
return itemID;
}
void CFileListManager::SetLoaded( DmFileId_t fileid, bool bLoaded )
{
CNotifyScopeGuard notify( "CFileListManager::SetLoaded", NOTIFY_SOURCE_FILE_LIST_MANAGER, NOTIFY_SETDIRTYFLAG );
if ( bLoaded )
{
const char *pFilename = g_pDataModel->GetFileName( fileid );
Assert( pFilename );
if ( !pFilename )
return;
CDisableUndoScopeGuard guard;
CDmElement *pRoot = NULL;
g_pDataModel->RestoreFromFile( pFilename, NULL, NULL, &pRoot, CR_DELETE_NEW );
}
else
{
CDisableUndoScopeGuard guard;
g_pDataModel->UnloadFile( fileid );
}
}
void CFileListManager::OnMousePressed( vgui::MouseCode code )
{
// determine where we were pressed
int x, y, row, column;
vgui::input()->GetCursorPos( x, y );
GetCellAtPos( x, y, row, column );
if ( code == MOUSE_LEFT )
{
bool bIsFakeToggleButton = column == CI_LOADED;
if ( bIsFakeToggleButton && row >= 0 && row < GetItemCount() )
{
int itemID = GetItemIDFromRow( row );
KeyValues *kv = GetItem( itemID );
const char *pStr = kv->GetString( GetKey( ( ColumnIndex_t )column ), "" );
Assert( *pStr == 'Y' || *pStr == 'N' );
bool bSet = *pStr == 'N'; // bSet is the NEW state, not the old one
kv->SetString( GetKey( ( ColumnIndex_t )column ), bSet ? "Y" : "N" );
SetLoaded( ( DmFileId_t )GetItemUserData( itemID ), bSet );
// get the key focus
RequestFocus();
return;
}
}
else if ( code == MOUSE_RIGHT )
{
int itemID = -1;
if ( row >= 0 && row < GetItemCount() )
{
itemID = GetItemIDFromRow( row );
if ( !IsItemSelected( itemID ) )
{
SetSingleSelectedItem( itemID );
}
}
KeyValues *kv = new KeyValues( "OpenContextMenu", "itemID", itemID );
OnOpenContextMenu( kv );
kv->deleteThis();
return;
}
BaseClass::OnMousePressed( code );
}
int AddMenuItemHelper( vgui::Menu *pMenu, const char *pItemName, const char *pKVName, vgui::Panel *pTarget, bool bEnabled )
{
int id = pMenu->AddMenuItem( pItemName, new KeyValues( pKVName ), pTarget );
pMenu->SetItemEnabled( id, bEnabled );
return id;
}
void CFileListManager::OnOpenContextMenu( KeyValues *pParams )
{
if ( m_hContextMenu.Get() )
{
delete m_hContextMenu.Get();
m_hContextMenu = NULL;
}
m_hContextMenu = new vgui::Menu( this, "ContextMenu" );
int itemID = pParams->GetInt( "itemID", -1 );
if ( itemID < 0 )
{
AddMenuItemHelper( m_hContextMenu, "Open File...", "open", this, true ); // Is this how we should load other files???
}
else
{
bool bP4Connected = p4->IsConnectedToServer();
int nSelected = GetSelectedItemsCount();
int nLoaded = 0;
int nChanged = 0;
int nOnDisk = 0;
int nInPerforce = 0;
int nOpenForEdit = 0;
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
if ( g_pDataModel->IsFileLoaded( fileid ) )
{
++nLoaded;
++nChanged; // TODO - find out for real
}
const char *pFilename = g_pDataModel->GetFileName( fileid );
if ( g_pFullFileSystem->FileExists( pFilename ) )
{
++nOnDisk;
}
if ( bP4Connected )
{
if ( p4->IsFileInPerforce( pFilename ) )
{
++nInPerforce;
if ( p4->GetFileState( pFilename ) != P4FILE_UNOPENED )
{
++nOpenForEdit;
}
}
}
}
AddMenuItemHelper( m_hContextMenu, "Load", "load", this, nLoaded < nSelected && nOnDisk > 0 );
AddMenuItemHelper( m_hContextMenu, "Unload", "unload", this, nLoaded > 0 );
AddMenuItemHelper( m_hContextMenu, "Save", "save", this, nChanged > 0 && nOnDisk == nSelected );
AddMenuItemHelper( m_hContextMenu, "Save As...", "saveas", this, nLoaded == 1 && nSelected == 1 );
AddMenuItemHelper( m_hContextMenu, "Add To Perforce", "p4add", this, nInPerforce < nSelected && nOnDisk > 0 );
AddMenuItemHelper( m_hContextMenu, "Open For Edit", "p4edit", this, nOpenForEdit < nSelected && nOnDisk > 0 );
}
vgui::Menu::PlaceContextMenu( this, m_hContextMenu.Get() );
}
void CFileListManager::OnLoadFiles( KeyValues *pParams )
{
CNotifyScopeGuard notify( "CFileListManager::OnLoadFiles", NOTIFY_SOURCE_FILE_LIST_MANAGER, NOTIFY_SETDIRTYFLAG );
int nSelected = GetSelectedItemsCount();
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
if ( !g_pDataModel->IsFileLoaded( fileid ) )
{
SetLoaded( fileid, true );
}
}
Refresh();
}
void CFileListManager::OnUnloadFiles( KeyValues *pParams )
{
CNotifyScopeGuard notify( "CFileListManager::OnUnloadFiles", NOTIFY_SOURCE_FILE_LIST_MANAGER, NOTIFY_SETDIRTYFLAG );
int nSelected = GetSelectedItemsCount();
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
if ( g_pDataModel->IsFileLoaded( fileid ) )
{
SetLoaded( fileid, false );
}
}
Refresh();
}
void CFileListManager::OnSaveFiles( KeyValues *pParams )
{
int nSelected = GetSelectedItemsCount();
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
if ( !g_pDataModel->IsFileLoaded( fileid ) )
continue;
const char *pFilename = g_pDataModel->GetFileName( fileid );
Assert( pFilename );
if ( !pFilename )
continue;
CDmElement *pRoot = GetElement< CDmElement >( g_pDataModel->GetFileRoot( fileid ) );
Assert( pRoot );
if ( !pRoot )
continue;
const char *pFileFormat = g_pDataModel->GetFileFormat( fileid );
const char *pEncoding = g_pDataModel->GetDefaultEncoding( pFileFormat );
g_pDataModel->SaveToFile( pFilename, NULL, pEncoding, pFileFormat, pRoot );
}
Refresh();
}
void CFileListManager::OnOpenFile( KeyValues *pParams )
{
KeyValues *pContextKeyValues = new KeyValues( "OnOpen" );
vgui::FileOpenDialog *pFileOpenDialog = new vgui::FileOpenDialog( this, "Save .dmx File As", false, pContextKeyValues );
pFileOpenDialog->AddFilter( "*.dmx", "DmElements File (*.dmx)", true );
pFileOpenDialog->AddActionSignalTarget( this );
pFileOpenDialog->DoModal( false );
}
void CFileListManager::OnSaveFileAs( KeyValues *pParams )
{
int nSelected = GetSelectedItemsCount();
Assert( nSelected == 1 );
if ( nSelected != 1 )
return;
KeyValues *pContextKeyValues = new KeyValues( "OnSaveAs" );
pContextKeyValues->SetInt( "itemId", GetSelectedItem( 0 ) );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( GetSelectedItem( 0 ) );
const char *pFileFormat = g_pDataModel->GetFileFormat( fileid );
vgui::FileOpenDialog *pFileOpenDialog = new vgui::FileOpenDialog( this, "Save .dmx File As", false, pContextKeyValues );
// if this control is moved to vgui_controls, change the default format to "dmx", the generic dmx format
pFileOpenDialog->AddFilter( "*.dmx", "Generic MovieObjects File (*.dmx)", false, "movieobjects" );
if ( V_strcmp( pFileFormat, "movieobjects" ) != 0 )
{
char description[ 256 ];
V_snprintf( description, sizeof( description ), "%s (*.dmx)", g_pDataModel->GetFormatDescription( pFileFormat ) );
pFileOpenDialog->AddFilter( "*.dmx", description, true, pFileFormat );
}
pFileOpenDialog->AddActionSignalTarget( this );
pFileOpenDialog->DoModal( false );
}
void CFileListManager::OnFileSelected( KeyValues *pParams )
{
const char *pFullPath = pParams->GetString( "fullpath" );
if ( !pFullPath || !pFullPath[ 0 ] )
return;
KeyValues *pSaveAsKey = pParams->FindKey( "OnSaveAs" );
if ( pSaveAsKey )
{
int itemId = pSaveAsKey->GetInt( "itemId", -1 );
Assert( itemId != -1 );
if ( itemId == -1 )
return;
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
Assert( fileid != DMFILEID_INVALID );
if ( fileid == DMFILEID_INVALID )
return;
CDmElement *pRoot = GetElement< CDmElement >( g_pDataModel->GetFileRoot( fileid ) );
Assert( pRoot );
if ( !pRoot )
return;
const char *pFormat = pParams->GetString( "filterinfo" );
Assert( pFormat );
if ( !pFormat )
return;
g_pDataModel->SetFileName( fileid, pFullPath );
g_pDataModel->SaveToFile( pFullPath, NULL, g_pDataModel->GetDefaultEncoding( pFormat ), pFormat, pRoot );
Refresh();
return;
}
KeyValues *pOpenKey = pParams->FindKey( "OnOpen" );
if ( pOpenKey )
{
CDmElement *pRoot = NULL;
g_pDataModel->RestoreFromFile( pFullPath, NULL, NULL, &pRoot );
Refresh();
return;
}
}
void CFileListManager::OnAddToPerforce( KeyValues *pParams )
{
int nFileCount = 0;
int nSelected = GetSelectedItemsCount();
const char **ppFileNames = ( const char** )_alloca( nSelected * sizeof( char* ) );
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
const char *pFilename = g_pDataModel->GetFileName( fileid );
Assert( pFilename );
if ( !pFilename )
continue;
++nFileCount;
ppFileNames[ i ] = pFilename;
}
bool bSuccess = p4->OpenFilesForAdd( nFileCount, ppFileNames );
if ( !bSuccess )
{
vgui::MessageBox *pError = new vgui::MessageBox( "Perforce Error!", p4->GetLastError(), GetParent() );
pError->SetSmallCaption( true );
pError->DoModal();
}
Refresh();
}
void CFileListManager::OnOpenForEdit( KeyValues *pParams )
{
int nFileCount = 0;
int nSelected = GetSelectedItemsCount();
const char **ppFileNames = ( const char** )_alloca( nSelected * sizeof( char* ) );
for ( int i = 0; i < nSelected; ++i )
{
int itemId = GetSelectedItem( i );
DmFileId_t fileid = ( DmFileId_t )GetItemUserData( itemId );
const char *pFilename = g_pDataModel->GetFileName( fileid );
Assert( pFilename );
if ( !pFilename )
continue;
++nFileCount;
ppFileNames[ i ] = pFilename;
}
bool bSuccess = p4->OpenFilesForEdit( nFileCount, ppFileNames );
if ( !bSuccess )
{
vgui::MessageBox *pError = new vgui::MessageBox( "Perforce Error!", p4->GetLastError(), GetParent() );
pError->SetSmallCaption( true );
pError->DoModal();
}
Refresh();
}
void CFileListManager::OnDataChanged( KeyValues *pParams )
{
int nNotifyFlags = pParams->GetInt( "notifyFlags" );
if ( ( nNotifyFlags & NOTIFY_CHANGE_TOPOLOGICAL ) == 0 )
return;
int nNotifySource = pParams->GetInt( "source" );
if ( nNotifySource == NOTIFY_SOURCE_FILE_LIST_MANAGER )
return;
if ( !IsVisible() )
{
m_bRefreshRequired = true;
return;
}
int nCount = GetItemCount();
int nFiles = g_pDataModel->NumFileIds();
bool bPerformFullRefresh = ( nCount != nFiles );
if ( !bPerformFullRefresh )
{
const char *pNameKey = GetKey( CI_FILENAME );
for ( int i = 0; i < nCount; ++i )
{
DmFileId_t fileid = g_pDataModel->GetFileId( i );
const char *pFileName = g_pDataModel->GetFileName( fileid );
if ( !pFileName || !*pFileName )
{
bPerformFullRefresh = true;
break;
}
pFileName = V_UnqualifiedFileName( pFileName );
KeyValues *pKeyValues = GetItem( i );
bPerformFullRefresh = ( fileid != (DmFileId_t)GetItemUserData(i) ) || Q_stricmp( pFileName, pKeyValues->GetString( pNameKey ) );
if ( bPerformFullRefresh )
break;
pKeyValues->SetInt ( GetKey( CI_NUMELEMENTS ), g_pDataModel->NumElementsInFile( fileid ) );
pKeyValues->SetString( GetKey( CI_LOADED ), g_pDataModel->IsFileLoaded( fileid ) ? "Y" : "N" );
pKeyValues->SetString( GetKey( CI_CHANGED ), false ? "Y" : "N" );
ApplyItemChanges( i );
}
}
if ( bPerformFullRefresh )
{
Refresh();
return;
}
}
void CFileListManager::Refresh()
{
m_bRefreshRequired = false;
RemoveAll();
const bool bP4Connected = p4 ? p4->IsConnectedToServer() : false;
int nFiles = g_pDataModel->NumFileIds();
for ( int i = 0; i < nFiles; ++i )
{
DmFileId_t fileid = g_pDataModel->GetFileId( i );
const char *pFileName = g_pDataModel->GetFileName( fileid );
if ( !pFileName || !*pFileName )
continue; // skip DMFILEID_INVALID and the default fileid ""
bool bLoaded = g_pDataModel->IsFileLoaded( fileid );
int nElements = g_pDataModel->NumElementsInFile( fileid );
bool bChanged = false; // TODO - find out for real
bool bInPerforce = bP4Connected && p4->IsFileInPerforce( pFileName );
bool bOpenForEdit = bInPerforce && p4->GetFileState( pFileName ) != P4FILE_UNOPENED;
char path[ 256 ];
V_ExtractFilePath( pFileName, path, sizeof( path ) );
AddItem( fileid, V_UnqualifiedFileName( pFileName ), path, bLoaded, nElements, bChanged, bInPerforce, bOpenForEdit );
}
}
void CFileListManager::OnThink( )
{
BaseClass::OnThink();
if ( m_bRefreshRequired && IsVisible() )
{
Refresh();
}
}
void CFileListManager::OnCommand( const char *cmd )
{
// if ( !Q_stricmp( cmd, "foo" ) ) ...
BaseClass::OnCommand( cmd );
}
//-----------------------------------------------------------------------------
//
// CFileManagerFrame methods
//
//-----------------------------------------------------------------------------
CFileManagerFrame::CFileManagerFrame( vgui::Panel *parent ) : BaseClass( parent, "FileManagerFrame" )
{
SetTitle( "#BxFileManagerFrame", true );
SetSizeable( true );
SetCloseButtonVisible( false );
SetMinimumSize( 200, 200 );
SetVisible( true );
SetSize( 800, 200 );
SetPos( 100, 100 );
m_pFileListManager = new CFileListManager( this );
Refresh();
SetScheme( vgui::scheme()->LoadSchemeFromFile( "Resource/BoxRocket.res", "BoxRocket" ) );
}
void CFileManagerFrame::Refresh()
{
m_pFileListManager->Refresh();
}
void CFileManagerFrame::OnCommand( const char *cmd )
{
BaseClass::OnCommand( cmd );
m_pFileListManager->OnCommand( cmd );
}
void CFileManagerFrame::PerformLayout()
{
BaseClass::PerformLayout();
int iWidth, iHeight;
GetSize( iWidth, iHeight );
m_pFileListManager->SetPos( 0, GetCaptionHeight() );
m_pFileListManager->SetSize( iWidth, iHeight - GetCaptionHeight() );
}

View File

@@ -0,0 +1,334 @@
// ----------------------------------------- //
// File generated by VPC //
// ----------------------------------------- //
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\2DSlider.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\2DSlider.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\2DSlider.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AssetBuilder.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AssetBuilder.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AssetBuilder.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeassetpickerpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeassetpickerpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeassetpickerpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBasePickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBasePickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBasePickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBoolChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBoolChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeBoolChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributebooleanpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributebooleanpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributebooleanpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeColorPickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeColorPickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeColorPickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributedetailtypepickerpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributedetailtypepickerpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributedetailtypepickerpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeElementPickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeFilePickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeFilePickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeFilePickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeIntChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeIntChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeIntChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeInterpolatorChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeInterpolatorChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeInterpolatorChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeMDLPickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeMDLPickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeMDLPickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSequencePickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSequencePickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSequencePickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeshaderpickerpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeshaderpickerpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeshaderpickerpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesheetsequencepickerpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesheetsequencepickerpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesheetsequencepickerpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSoundPickerPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSoundPickerPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeSoundPickerPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeStringChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeStringChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeStringChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesurfacepropertypickerpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesurfacepropertypickerpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributesurfacepropertypickerpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextEntry.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextEntry.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextEntry.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeTextPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeWidgetFactory.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeWidgetFactory.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\AttributeWidgetFactory.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeDoubleChoicePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeDoubleChoicePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributeDoubleChoicePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAttributePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ChannelGraphPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ChannelGraphPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ChannelGraphPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Debug output file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Release output file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecombinationsystemeditorpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecombinationsystemeditorpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecombinationsystemeditorpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecontrols.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecontrols.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmecontrols.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedageditpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedageditpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedageditpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedagrenderpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedagrenderpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmedagrenderpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmelogeditpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmelogeditpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmelogeditpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmemdlpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmemdlpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmemdlpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepicker.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepicker.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepicker.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepresetgroupeditorpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepresetgroupeditorpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\dmepresetgroupeditorpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceDCCFilePanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceDCCFilePanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceDCCFilePanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceSkinPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceSkinPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\DmeSourceSkinPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ElementPropertiesTree.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ElementPropertiesTree.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\ElementPropertiesTree.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\FileListManager.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\FileListManager.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\FileListManager.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\filtercombobox.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\filtercombobox.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\filtercombobox.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempropertiespanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempropertiespanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\particlesystempropertiespanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\sheeteditorpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\sheeteditorpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\sheeteditorpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundpicker.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundpicker.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundpicker.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundrecordpanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundrecordpanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\soundrecordpanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeslider.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeslider.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\attributeslider.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditor.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditor.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditor.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditorController.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditorController.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimationSetEditorController.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetAttributeSliderPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetAttributeSliderPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetAttributeSliderPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetControlGroupPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetControlGroupPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetControlGroupPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetPresetFaderPanel.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetPresetFaderPanel.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\BaseAnimSetPresetFaderPanel.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\public\phonemeconverter.cpp
Debug output file: F:\csgo_64\cstrike15_src\public\phonemeconverter.cpp
Release output file: F:\csgo_64\cstrike15_src\public\phonemeconverter.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\presetpicker.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\presetpicker.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\dme_controls\presetpicker.cpp
Containing unity file:
PCH file:

View File

@@ -0,0 +1,101 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeAssetPickerPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/AssetPicker.h"
#include "matsys_controls/VtfPicker.h"
#include "matsys_controls/TGAPicker.h"
#include "matsys_controls/VMTPicker.h"
#include "tier1/keyvalues.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Assets
//-----------------------------------------------------------------------------
IMPLEMENT_ATTRIBUTE_ASSET_PICKER( CAttributeBspPickerPanel, "Select .BSP file", "BSP Files", "bsp", "maps", "bspName" );
IMPLEMENT_ATTRIBUTE_ASSET_PREVIEW_PICKER( CAttributeVmtPickerPanel, CVMTPickerFrame, "Select .VMT file" );
IMPLEMENT_ATTRIBUTE_ASSET_PREVIEW_PICKER( CAttributeVtfPickerPanel, CVTFPickerFrame, "Select .VTF file" );
IMPLEMENT_ATTRIBUTE_ASSET_PREVIEW_PICKER( CAttributeTgaPickerPanel, CTGAPickerFrame, "Select .TGA file" );
void CAttributeVmtPickerPanel::OnAssetSelected( KeyValues *kv )
{
BaseClass::OnAssetSelected(kv);
int nSheetSequenceCount = kv->GetInt( "sheet_sequence_count" );
int nSheetSequenceNum = kv->GetInt( "sheet_sequence_number" );
int nSecondSheetSequenceNum = kv->GetInt( "sheet_sequence_secondary_number" );
if ( nSheetSequenceCount > 0 )
{
CUndoScopeGuard guard( 0, NOTIFY_SETDIRTYFLAG, GetNotify(), "Auto-Set Sequence from VMT dialog" );
// selected a VMT that uses sheet information
CDmElement* pElement = GetPanelElement();
CDmAttribute* pSeqNumberAttr = pElement->GetAttribute("sequence_number");
if ( pSeqNumberAttr )
{
pSeqNumberAttr->SetValue(nSheetSequenceNum);
}
CDmAttribute* pSecondSeqNumberAttr = pElement->GetAttribute("sequence_number 1");
if ( pSecondSeqNumberAttr )
{
pSecondSeqNumberAttr->SetValue(nSecondSheetSequenceNum);
}
}
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeAssetPickerPanel::CAttributeAssetPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeAssetPickerPanel::~CAttributeAssetPickerPanel()
{
}
//-----------------------------------------------------------------------------
// Called when it's time to show the BSP picker
//-----------------------------------------------------------------------------
void CAttributeAssetPickerPanel::ShowPickerDialog()
{
CBaseAssetPickerFrame *pAssetPickerDialog = CreateAssetPickerFrame( );
pAssetPickerDialog->AddActionSignalTarget( this );
pAssetPickerDialog->DoModal( );
}
//-----------------------------------------------------------------------------
// Called by the asset picker dialog if a asset was selected
//-----------------------------------------------------------------------------
void CAttributeAssetPickerPanel::OnAssetSelected( KeyValues *pKeyValues )
{
// Get the asset name back
const char *pAssetName = pKeyValues->GetString( "asset", NULL );
if ( !pAssetName || !pAssetName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pAssetName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,73 @@
//============ Copyright (c) Valve Corporation, All rights reserved. ============
#include "dme_controls/attributebooleanpanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "tier1/KeyValues.h"
#include "datamodel/dmelement.h"
#include "movieobjects/dmeeditortypedictionary.h"
#include "movieobjects/dmechannel.h"
#include "dme_controls/inotifyui.h"
#include "vgui_controls/CheckButton.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
CAttributeBooleanPanel::CAttributeBooleanPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
m_pValueButton = new vgui::CheckButton( this, "", "" );
m_pValueButton->AddActionSignalTarget( this );
}
//-----------------------------------------------------------------------------
void CAttributeBooleanPanel::ApplySchemeSettings(IScheme *pScheme)
{
// Need to override the scheme settings for this button
BaseClass::ApplySchemeSettings( pScheme );
m_pValueButton->SetBorder(NULL);
m_pValueButton->SetPaintBorderEnabled( false );
// Hack to get rid of the checkbox offset of &!^@#% 6
// m_pValueButton->SetImage( vgui::scheme()->GetImage( "tools/ifm/icon_properties_linkarrow" , false), 0);
m_pValueButton->SetImageAtIndex( 0, m_pValueButton->GetImageAtIndex( 0 ), 0 );
}
void CAttributeBooleanPanel::OnCheckButtonChecked( int state )
{
bool attributeValue = GetAttributeValue< bool>();
bool buttonValue = (state == 1);
if( buttonValue != attributeValue )
{
SetAttributeValue( state );
Refresh();
}
}
void CAttributeBooleanPanel::Refresh()
{
BaseClass::Refresh();
bool myValue = GetAttributeValue< bool>();
if( myValue != m_pValueButton->IsSelected() )
{
m_pValueButton->SetSelected( myValue );
}
}
void CAttributeBooleanPanel::PerformLayout()
{
BaseClass::PerformLayout();
int viewWidth, viewHeight;
GetSize( viewWidth, viewHeight );
m_pValueButton->SetBounds( (FirstColumnWidth - ColumnBorderWidth - 16) * 0.5 , ( viewHeight - 16 )* 0.5 , 16, 16 );
}

View File

@@ -0,0 +1,88 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeDetailTypePickerPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "tier1/keyvalues.h"
#include "filesystem.h"
using namespace vgui;
const char *DETAILTYPE_FILE = "detail.vbsp";
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeDetailTypePickerPanel::CAttributeDetailTypePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeDetailTypePickerPanel::~CAttributeDetailTypePickerPanel()
{
}
//-----------------------------------------------------------------------------
// Reads the detail types
//-----------------------------------------------------------------------------
void CAttributeDetailTypePickerPanel::AddDetailTypesToList( PickerList_t &list )
{
KeyValues *pDetailTypes = new KeyValues( DETAILTYPE_FILE );
if ( pDetailTypes->LoadFromFile( g_pFullFileSystem, DETAILTYPE_FILE, "GAME" ) )
{
for ( KeyValues *sub = pDetailTypes->GetFirstTrueSubKey(); sub != NULL; sub = sub->GetNextTrueSubKey() )
{
int i = list.AddToTail( );
list[i].m_pChoiceString = sub->GetName();
list[i].m_pChoiceValue = sub->GetName();
}
}
else
{
Warning( "Unable to load detail prop file '%s'\n", DETAILTYPE_FILE );
}
pDetailTypes->deleteThis();
}
//-----------------------------------------------------------------------------
// Called when it's time to show the picker
//-----------------------------------------------------------------------------
void CAttributeDetailTypePickerPanel::ShowPickerDialog()
{
CPickerFrame *pDetailTypePickerDialog = new CPickerFrame( this, "Select Detail Type", "Detail Type", "detailTypeName" );
PickerList_t detailTypeList;
AddDetailTypesToList( detailTypeList );
pDetailTypePickerDialog->AddActionSignalTarget( this );
pDetailTypePickerDialog->DoModal( detailTypeList );
}
//-----------------------------------------------------------------------------
// Called by the picker dialog if a asset was selected
//-----------------------------------------------------------------------------
void CAttributeDetailTypePickerPanel::OnPicked( KeyValues *pKeyValues )
{
// Get the detail type name back
const char *pDetailTypeName = pKeyValues->GetString( "choice", NULL );
if ( !pDetailTypeName || !pDetailTypeName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pDetailTypeName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,77 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeShaderPickerPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/Picker.h"
#include "tier1/keyvalues.h"
#include "matsys_controls/matsyscontrols.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/ishader.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeShaderPickerPanel::CAttributeShaderPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeShaderPickerPanel::~CAttributeShaderPickerPanel()
{
}
//-----------------------------------------------------------------------------
// Called when it's time to show the picker
//-----------------------------------------------------------------------------
void CAttributeShaderPickerPanel::ShowPickerDialog()
{
CPickerFrame *pShaderPickerDialog = new CPickerFrame( this, "Select Shader", "Shader", "shaderName" );
int nCount = vgui::MaterialSystem()->ShaderCount();
IShader** ppShaderList = (IShader**)_alloca( nCount * sizeof(IShader) );
vgui::MaterialSystem()->GetShaders( 0, nCount, ppShaderList );
PickerList_t shaderList( 0, nCount );
for ( int i = 0; i < nCount; ++i )
{
if ( ( ppShaderList[i]->GetFlags() & SHADER_NOT_EDITABLE ) == 0 )
{
int j = shaderList.AddToTail( );
shaderList[j].m_pChoiceString = ppShaderList[i]->GetName();
shaderList[j].m_pChoiceValue = ppShaderList[i]->GetName();
}
}
pShaderPickerDialog->AddActionSignalTarget( this );
pShaderPickerDialog->DoModal( shaderList );
}
//-----------------------------------------------------------------------------
// Called by the picker dialog if a asset was selected
//-----------------------------------------------------------------------------
void CAttributeShaderPickerPanel::OnPicked( KeyValues *pKeyValues )
{
// Get the asset name back
const char *pShaderName = pKeyValues->GetString( "choice", NULL );
if ( !pShaderName || !pShaderName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pShaderName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,140 @@
//======= Copyright (c) 1996-2009, Valve Corporation, All rights reserved. ======
//
// CAttributeSheetSequencePickerPanel - Panel for editing int attributes that select a sprite sheet sequence
//
//===============================================================================
#include "dme_controls/attributesheetsequencepickerpanel.h"
#include "FileSystem.h"
#include "vgui_controls/MenuButton.h"
#include "vgui_controls/FileOpenDialog.h"
#include "dme_controls/AttributeTextEntry.h"
#include "matsys_controls/sheetsequencepanel.h"
#include "movieobjects/dmeparticlesystemdefinition.h"
#include "tier1/keyvalues.h"
#include "dme_controls/AttributeWidgetFactory.h"
#include "movieobjects/dmeeditortypedictionary.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// CNotifyMenuButton - MenuButton with a notify before the menu is shown
//
//-----------------------------------------------------------------------------
class CNotifyMenuButton: public vgui::MenuButton
{
DECLARE_CLASS_SIMPLE( CNotifyMenuButton, vgui::MenuButton );
public:
CNotifyMenuButton(CAttributeSheetSequencePickerPanel *parent, const char *panelName, const char *text);
virtual void OnShowMenu(Menu *menu);
private:
CAttributeSheetSequencePickerPanel* m_pParent;
};
CNotifyMenuButton::CNotifyMenuButton(CAttributeSheetSequencePickerPanel *parent, const char *panelName, const char *text):
BaseClass(parent,panelName,text)
{
m_pParent = parent;
}
void CNotifyMenuButton::OnShowMenu(Menu *menu)
{
if ( m_pParent )
{
m_pParent->UpdateSheetPanel();
}
BaseClass::OnShowMenu(menu);
}
//-----------------------------------------------------------------------------
//
// CAttributeSheetSequencePickerPanel
//
//-----------------------------------------------------------------------------
CAttributeSheetSequencePickerPanel::CAttributeSheetSequencePickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
if ( info.m_pEditorInfo )
{
m_bIsSecondView = !V_stricmp( info.m_pEditorInfo->GetWidgetName(), "sheetsequencepicker_second" );
}
else
{
m_bIsSecondView = false;
}
m_pSheetPanel = new CSheetSequencePanel(this, "sheetsequencepanel");
m_pSheetPanel->AddActionSignalTarget( this );
m_pSequenceSelection = new CNotifyMenuButton( this, "SequenceSelection", "seq" );
m_pSequenceSelection->SetMenu( m_pSheetPanel );
m_pSheetPanel->AddActionSignalTarget( this );
UpdateSheetPanel();
}
void CAttributeSheetSequencePickerPanel::UpdateSheetPanel()
{
CDmElement* pElement = GetPanelElement();
CDmAttribute* pMaterialAttr = pElement->GetAttribute("material");
if ( m_bIsSecondView )
{
m_pSheetPanel->SetSecondSequenceView( true );
m_pSequenceSelection->SetText( "sq2" );
}
if ( pMaterialAttr == NULL )
{
pElement = FindReferringElement< CDmeParticleSystemDefinition >( pElement, "initializers" );
if ( pElement )
{
pMaterialAttr = pElement->GetAttribute("material");
}
}
if ( pMaterialAttr )
{
m_pSheetPanel->SetFromMaterialName( pMaterialAttr->GetValueString() );
}
}
CAttributeSheetSequencePickerPanel::~CAttributeSheetSequencePickerPanel()
{
}
void CAttributeSheetSequencePickerPanel::OnSheetSequenceSelected( int nSequenceNumber )
{
CUndoScopeGuard guard( 0, NOTIFY_SETDIRTYFLAG, GetNotify(), "Select Sheet Sequence" );
SetAttributeValue(nSequenceNumber);
}
// MOC_TODO: factor this somewhere else - shared with other attribute controls
void CAttributeSheetSequencePickerPanel::PerformLayout()
{
BaseClass::PerformLayout();
int x, y, w, h;
m_pType->GetBounds( x, y, w, h );
int inset = 25;
m_pType->SetWide( w - inset );
x += w;
x -= inset;
h -= 2;
m_pSequenceSelection->SetBounds( x, y, inset, h );
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "dme_controls/AttributeSurfacePropertyPickerPanel.h"
#include "dme_controls/AttributeTextEntry.h"
#include "tier1/keyvalues.h"
#include "filesystem.h"
using namespace vgui;
const char *SURFACEPROP_MANIFEST_FILE = "scripts/surfaceproperties_manifest.txt";
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CAttributeSurfacePropertyPickerPanel::CAttributeSurfacePropertyPickerPanel( vgui::Panel *parent, const AttributeWidgetInfo_t &info ) :
BaseClass( parent, info )
{
}
CAttributeSurfacePropertyPickerPanel::~CAttributeSurfacePropertyPickerPanel()
{
}
//-----------------------------------------------------------------------------
// Reads the surface properties
//-----------------------------------------------------------------------------
void CAttributeSurfacePropertyPickerPanel::AddSurfacePropertiesToList( PickerList_t &list )
{
KeyValues *manifest = new KeyValues( SURFACEPROP_MANIFEST_FILE );
if ( manifest->LoadFromFile( g_pFullFileSystem, SURFACEPROP_MANIFEST_FILE, "GAME" ) )
{
for ( KeyValues *sub = manifest->GetFirstSubKey(); sub != NULL; sub = sub->GetNextKey() )
{
if ( Q_stricmp( sub->GetName(), "file" ) )
continue;
KeyValues *file = new KeyValues( SURFACEPROP_MANIFEST_FILE );
if ( file->LoadFromFile( g_pFullFileSystem, sub->GetString(), "GAME" ) )
{
for ( KeyValues *pTrav = file; pTrav; pTrav = pTrav->GetNextKey() )
{
int i = list.AddToTail();
list[i].m_pChoiceString = pTrav->GetName();
list[i].m_pChoiceValue = pTrav->GetName();
}
}
else
{
Warning( "Unable to load surface properties file '%s'\n", sub->GetString() );
}
file->deleteThis();
}
}
else
{
Warning( "Unable to load manifest file '%s'\n", SURFACEPROP_MANIFEST_FILE );
}
manifest->deleteThis();
}
//-----------------------------------------------------------------------------
// Called when it's time to show the picker
//-----------------------------------------------------------------------------
void CAttributeSurfacePropertyPickerPanel::ShowPickerDialog()
{
CPickerFrame *pSurfacePropPickerDialog = new CPickerFrame( this, "Select Surface Property", "Surface Property", "surfacePropertyName" );
PickerList_t surfacePropList;
AddSurfacePropertiesToList( surfacePropList );
pSurfacePropPickerDialog->AddActionSignalTarget( this );
pSurfacePropPickerDialog->DoModal( surfacePropList );
}
//-----------------------------------------------------------------------------
// Called by the picker dialog if a asset was selected
//-----------------------------------------------------------------------------
void CAttributeSurfacePropertyPickerPanel::OnPicked( KeyValues *pKeyValues )
{
// Get the asset name back
const char *pSurfacePropertyName = pKeyValues->GetString( "choice", NULL );
if ( !pSurfacePropertyName || !pSurfacePropertyName[ 0 ] )
return;
// Apply to text panel
m_pData->SetText( pSurfacePropertyName );
SetDirty(true);
if ( IsAutoApply() )
{
Apply();
}
}

View File

@@ -0,0 +1,142 @@
//-----------------------------------------------------------------------------
// DME_CONTROLS.VPC
//
// Project Script
//-----------------------------------------------------------------------------
$Macro SRCDIR "..\.."
$Include "$SRCDIR\vpc_scripts\source_lib_base.vpc"
$Configuration
{
$Compiler
{
$PreprocessorDefinitions "$BASE;DMECONTROLS_LIB"
$PrecompiledHeaderFile "Debug/dme_controls.pch"
}
}
$Project "Dme_controls"
{
$Folder "Header Files"
{
$File "$SRCDIR\public\dme_controls\AssetBuilder.h"
$File "$SRCDIR\public\dme_controls\attributeassetpickerpanel.h"
$File "$SRCDIR\public\dme_controls\AttributeBasePickerPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeBoolChoicePanel.h"
$File "$SRCDIR\public\dme_controls\attributebooleanpanel.h"
$File "$SRCDIR\public\dme_controls\AttributeColorPickerPanel.h"
$File "$SRCDIR\public\dme_controls\attributedetailtypepickerpanel.h"
$File "$SRCDIR\public\dme_controls\AttributeElementPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeElementPickerPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeFilePickerPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeIntChoicePanel.h"
$File "$SRCDIR\public\dme_controls\AttributeInterpolatorChoicePanel.h"
$File "$SRCDIR\public\dme_controls\AttributeMDLPickerPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeSequencePickerPanel.h"
$File "$SRCDIR\public\dme_controls\attributeshaderpickerpanel.h"
$File "$SRCDIR\public\dme_controls\attributesheetsequencepickerpanel.h"
$File "$SRCDIR\public\dme_controls\AttributeSoundPickerPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeStringChoicePanel.h"
$File "$SRCDIR\public\dme_controls\attributesurfacepropertypickerpanel.h"
$File "$SRCDIR\public\dme_controls\AttributeTextEntry.h"
$File "$SRCDIR\public\dme_controls\AttributeTextPanel.h"
$File "$SRCDIR\public\dme_controls\AttributeWidgetFactory.h"
$File "$SRCDIR\public\dme_controls\BaseAttributeChoicePanel.h"
$File "$SRCDIR\public\dme_controls\BaseAttributeDoubleChoicePanel.h"
$File "$SRCDIR\public\dme_controls\BaseAttributePanel.h"
$File "$SRCDIR\public\dme_controls\ChannelGraphPanel.h"
$File "$SRCDIR\public\dme_controls\dmecombinationsystemeditorpanel.h"
$File "$SRCDIR\public\dme_controls\dmecontrols.h"
$File "$SRCDIR\public\dme_controls\dmecontrols_utils.h"
$File "$SRCDIR\public\dme_controls\dmedageditpanel.h"
$File "$SRCDIR\public\dme_controls\dmedagrenderpanel.h"
$File "$SRCDIR\public\dme_controls\dmemdlpanel.h"
$File "$SRCDIR\public\dme_controls\dmepanel.h"
$File "$SRCDIR\public\dme_controls\dmepicker.h"
$File "$SRCDIR\public\dme_controls\dmepresetgroupeditorpanel.h"
$File "$SRCDIR\public\dme_controls\DmeSourceDCCFilePanel.h"
$File "$SRCDIR\public\dme_controls\DmeSourceSkinPanel.h"
$File "$SRCDIR\public\dme_controls\ElementPropertiesTree.h"
$File "$SRCDIR\public\dme_controls\FileListManager.h"
$File "$SRCDIR\public\dme_controls\filtercombobox.h"
$File "$SRCDIR\public\dme_controls\inotifyui.h"
$File "$SRCDIR\public\dme_controls\particlesystempanel.h"
$File "$SRCDIR\public\dme_controls\particlesystempropertiespanel.h"
$File "$SRCDIR\public\dme_controls\sheeteditorpanel.h"
$File "$SRCDIR\public\dme_controls\soundpicker.h"
$File "$SRCDIR\public\dme_controls\soundrecordpanel.h"
$File "$SRCDIR\public\dme_controls\2DSlider.h"
}
$Folder "Source Files"
{
$File "AssetBuilder.cpp"
$File "attributeassetpickerpanel.cpp"
$File "AttributeBasePickerPanel.cpp"
$File "AttributeBoolChoicePanel.cpp"
$File "attributebooleanpanel.cpp"
$File "AttributeColorPickerPanel.cpp"
$File "attributedetailtypepickerpanel.cpp"
$File "AttributeElementPanel.cpp"
$File "AttributeElementPickerPanel.cpp"
$File "AttributeFilePickerPanel.cpp"
$File "AttributeIntChoicePanel.cpp"
$File "AttributeInterpolatorChoicePanel.cpp"
$File "AttributeMDLPickerPanel.cpp"
$File "AttributeSequencePickerPanel.cpp"
$File "attributeshaderpickerpanel.cpp"
$File "attributesheetsequencepickerpanel.cpp"
$File "AttributeSoundPickerPanel.cpp"
$File "AttributeStringChoicePanel.cpp"
$File "attributesurfacepropertypickerpanel.cpp"
$File "AttributeTextEntry.cpp"
$File "AttributeTextPanel.cpp"
$File "AttributeWidgetFactory.cpp"
$File "BaseAttributeChoicePanel.cpp"
$File "BaseAttributeDoubleChoicePanel.cpp"
$File "BaseAttributePanel.cpp"
$File "ChannelGraphPanel.cpp"
$File "dmecombinationsystemeditorpanel.cpp"
$File "dmecontrols.cpp"
$File "dmedageditpanel.cpp"
$File "dmedagrenderpanel.cpp"
$File "dmelogeditpanel.cpp"
$File "dmemdlpanel.cpp"
$File "dmepanel.cpp"
$File "dmepicker.cpp"
$File "dmepresetgroupeditorpanel.cpp"
$File "DmeSourceDCCFilePanel.cpp"
$File "DmeSourceSkinPanel.cpp"
$File "ElementPropertiesTree.cpp"
$File "FileListManager.cpp"
$File "filtercombobox.cpp"
$File "particlesystempanel.cpp"
$File "particlesystempropertiespanel.cpp"
$File "sheeteditorpanel.cpp"
$File "soundpicker.cpp"
$File "soundrecordpanel.cpp"
$File "2DSlider.cpp"
$Folder "Animation Set Editor"
{
$File "$SRCDIR\public\dme_controls\attributeslider.h"
$File "attributeslider.cpp"
$File "BaseAnimationSetEditorController.cpp"
$File "$SRCDIR\public\dme_controls\BaseAnimationSetEditorController.h"
$File "BaseAnimationSetEditor.cpp"
$File "$SRCDIR\public\dme_controls\BaseAnimationSetEditor.h"
$File "BaseAnimSetAttributeSliderPanel.cpp"
$File "$SRCDIR\public\dme_controls\BaseAnimSetAttributeSliderPanel.h"
$File "BaseAnimSetControlGroupPanel.cpp"
$File "$SRCDIR\public\dme_controls\BaseAnimSetControlGroupPanel.h"
$File "BaseAnimSetPresetFaderPanel.cpp"
$File "$SRCDIR\public\dme_controls\BaseAnimSetPresetFaderPanel.h"
$File "presetpicker.cpp"
$File "$SRCDIR\public\dme_controls\presetpicker.h"
$File "$SRCDIR\public\dme_controls\RecordingState.h"
$File "$SRCDIR\public\phonemeconverter.cpp"
}
}
}

View File

@@ -0,0 +1,13 @@
"vpc_cache"
{
"CacheVersion" "1"
"win32"
{
"CRCFile" "dme_controls.vcxproj.vpc_crc"
"OutputFiles"
{
"0" "dme_controls.vcxproj"
"1" "dme_controls.vcxproj.filters"
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,103 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "dme_controls/dmecontrols.h"
#include "soundemittersystem/isoundemittersystembase.h"
#include "matsys_controls/matsyscontrols.h"
#include "toolframework/ienginetool.h"
#include "vphysics_interface.h"
#include "dme_controls/inotifyui.h"
#include "tier3/tier3.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
namespace vgui
{
ISoundEmitterSystemBase *g_pSoundEmitterSystem = NULL;
ISoundEmitterSystemBase *SoundEmitterSystem()
{
return g_pSoundEmitterSystem;
}
IEngineTool *enginetools = NULL;
IEngineTool *EngineTool()
{
return enginetools;
}
IPhysicsCollision *g_pPhysicsCollision = NULL;
IPhysicsCollision *PhysicsCollision()
{
return g_pPhysicsCollision;
}
class CDefaultElementPropertiesChoices : public CBaseElementPropertiesChoices
{
public:
};
static CDefaultElementPropertiesChoices s_DefaultChoices;
IElementPropertiesChoices *g_pElementPropertiesChoices = &s_DefaultChoices;
IElementPropertiesChoices *ElementPropertiesChoices()
{
return g_pElementPropertiesChoices;
}
void SetElementPropertiesChoices( IElementPropertiesChoices *pElementPropertiesChoices )
{
g_pElementPropertiesChoices = pElementPropertiesChoices ? pElementPropertiesChoices : &s_DefaultChoices;
}
//-----------------------------------------------------------------------------
// Purpose: finds a particular interface in the factory set
//-----------------------------------------------------------------------------
static void *InitializeInterface( char const *interfaceName, CreateInterfaceFn *factoryList, int numFactories )
{
void *retval;
for ( int i = 0; i < numFactories; i++ )
{
CreateInterfaceFn factory = factoryList[ i ];
if ( !factory )
continue;
retval = factory( interfaceName, NULL );
if ( retval )
return retval;
}
// No provider for requested interface!!!
// Assert( !"No provider for requested interface!!!" );
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: Initializes the controls
//-----------------------------------------------------------------------------
bool VGui_InitDmeInterfacesList( const char *moduleName, CreateInterfaceFn *factoryList, int numFactories )
{
if ( !vgui::VGui_InitMatSysInterfacesList( moduleName, factoryList, numFactories ) )
return false;
g_pSoundEmitterSystem = (ISoundEmitterSystemBase*)InitializeInterface( SOUNDEMITTERSYSTEM_INTERFACE_VERSION, factoryList, numFactories );
enginetools = (IEngineTool*)InitializeInterface( VENGINETOOL_INTERFACE_VERSION, factoryList, numFactories );
g_pPhysicsCollision = (IPhysicsCollision*)InitializeInterface( VPHYSICS_COLLISION_INTERFACE_VERSION, factoryList, numFactories );
// Can function without either of these
return true;
}
} // namespace vgui

View File

@@ -0,0 +1,984 @@
//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "vstdlib/random.h"
#include "dme_controls/dmedageditpanel.h"
#include "dme_controls/dmedagrenderpanel.h"
#include "dme_controls/dmepanel.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/Splitter.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/PropertyPage.h"
#include "vgui_controls/Label.h"
#include "vgui_controls/ScrollBar.h"
#include "vgui_controls/Slider.h"
#include "vgui_controls/ScrollableEditablePanel.h"
#include "vgui_controls/ListPanel.h"
#include "vgui_controls/Image.h"
#include "vgui_controls/TextImage.h"
#include "vgui/isurface.h"
#include "vgui/ischeme.h"
#include "vgui/iinput.h"
#include "vgui/ivgui.h"
#include "vgui/cursor.h"
#include "movieobjects/dmemakefile.h"
#include "movieobjects/dmemdlmakefile.h"
#include "movieobjects/dmedccmakefile.h"
#include "movieobjects/dmedag.h"
#include "movieobjects/dmeclip.h"
#include "movieobjects/dmeanimationlist.h"
#include "movieobjects/dmecombinationoperator.h"
#include "movieobjects/dmeanimationset.h"
#include "movieobjects/dmeflexrules.h"
#include "tier1/keyvalues.h"
#include "materialsystem/imesh.h"
#include "dme_controls/BaseAnimationSetEditor.h"
#include "dme_controls/BaseAnimationSetEditorController.h"
#include "dme_controls/BaseAnimSetAttributeSliderPanel.h"
//-----------------------------------------------------------------------------
//
// Hook into the dme panel editor system
//
//-----------------------------------------------------------------------------
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeDag, "DmeDagPreview2", "DmeDag Previewer 2", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeSourceSkin, "DmeSourceSkinPreview2", "MDL Skin Previewer 2", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeSourceAnimation, "DmeSourceAnimationPreview2", "MDL Animation Previewer 2", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeDCCMakefile, "DmeMakeFileOutputPreview2", "DCC MakeFile Output Previewer 2", false );
//-----------------------------------------------------------------------------
// Slider panel
//-----------------------------------------------------------------------------
class CDmeAnimationListPanel : public vgui::EditablePanel
{
DECLARE_CLASS_SIMPLE( CDmeAnimationListPanel, vgui::EditablePanel );
public:
// constructor, destructor
CDmeAnimationListPanel( vgui::Panel *pParent, const char *pName );
virtual ~CDmeAnimationListPanel();
void SetAnimationList( CDmeAnimationList *pList );
void RefreshAnimationList();
const char *GetSelectedAnimation() const;
private:
// Called when the selection changes moves
MESSAGE_FUNC( OnItemSelected, "ItemSelected" );
MESSAGE_FUNC( OnItemDeselected, "ItemDeselected" );
vgui::ListPanel *m_pAnimationList;
CDmeHandle< CDmeAnimationList > m_hAnimationList;
};
static int __cdecl AnimationNameSortFunc( vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString("name");
const char *string2 = item2.kv->GetString("name");
return Q_stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CDmeAnimationListPanel::CDmeAnimationListPanel( vgui::Panel *pParent, const char *pName ) :
BaseClass( pParent, pName )
{
m_pAnimationList = new vgui::ListPanel( this, "AnimationList" );
m_pAnimationList->AddColumnHeader( 0, "name", "name", 100, 0 );
m_pAnimationList->AddActionSignalTarget( this );
m_pAnimationList->SetSortFunc( 0, AnimationNameSortFunc );
m_pAnimationList->SetSortColumn( 0 );
m_pAnimationList->SetEmptyListText("No animations");
m_pAnimationList->SetMultiselectEnabled( false );
LoadControlSettingsAndUserConfig( "resource/dmeanimationlistpanel.res" );
}
CDmeAnimationListPanel::~CDmeAnimationListPanel()
{
}
//-----------------------------------------------------------------------------
// Sets the combination operator
//-----------------------------------------------------------------------------
void CDmeAnimationListPanel::SetAnimationList( CDmeAnimationList *pList )
{
if ( pList != m_hAnimationList.Get() )
{
m_hAnimationList = pList;
RefreshAnimationList();
}
}
//-----------------------------------------------------------------------------
// Builds the list of animations
//-----------------------------------------------------------------------------
void CDmeAnimationListPanel::RefreshAnimationList()
{
m_pAnimationList->RemoveAll();
if ( !m_hAnimationList.Get() )
return;
int nCount = m_hAnimationList->GetAnimationCount();
for ( int i = 0; i < nCount; ++i )
{
CDmeChannelsClip *pAnimation = m_hAnimationList->GetAnimation( i );
KeyValues *pItemKeys = new KeyValues( "node", "name", pAnimation->GetName() );
m_pAnimationList->AddItem( pItemKeys, 0, false, false );
}
m_pAnimationList->SortList();
}
//-----------------------------------------------------------------------------
// Returns the selected animation
//-----------------------------------------------------------------------------
const char *CDmeAnimationListPanel::GetSelectedAnimation() const
{
if ( m_pAnimationList->GetSelectedItemsCount() == 0 )
return "";
int nIndex = m_pAnimationList->GetSelectedItem( 0 );
KeyValues *pItemKeyValues = m_pAnimationList->GetItem( nIndex );
return pItemKeyValues->GetString( "name" );
}
//-----------------------------------------------------------------------------
// Called when an animation is selected or deselected
//-----------------------------------------------------------------------------
void CDmeAnimationListPanel::OnItemSelected( )
{
const char *pAnimationName = GetSelectedAnimation();
PostActionSignal( new KeyValues( "AnimationSelected", "animationName", pAnimationName ) );
}
void CDmeAnimationListPanel::OnItemDeselected( )
{
PostActionSignal( new KeyValues( "AnimationDeselected" ) );
}
class CCombinationOperatorControl : public CBaseAnimationSetControl
{
public:
CCombinationOperatorControl() {}
virtual void ChangeAnimationSetClip( CDmeFilmClip *pFilmClip )
{
RebuildControlList( m_FullControlList, pFilmClip );
CBaseAnimationSetControl::ChangeAnimationSetClip( pFilmClip );
}
virtual void OnControlsAddedOrRemoved()
{
RemoveNullControls( m_FullControlList );
AddMissingControls( m_FullControlList, m_hFilmClip );
CBaseAnimationSetControl::OnControlsAddedOrRemoved();
}
protected:
virtual SelectionInfo_t *FindSelectionInfoForControl( const CDmElement *pControl )
{
return ::FindSelectionInfoForControl( m_FullControlList, pControl );
}
CUtlVector< SelectionInfo_t* > m_FullControlList;
};
class CDmeCombinationOperatorPanel : public CBaseAnimationSetEditor
{
DECLARE_CLASS_SIMPLE( CDmeCombinationOperatorPanel, CBaseAnimationSetEditor );
public:
CDmeCombinationOperatorPanel( vgui::Panel *parent, const char *panelName, CBaseAnimationSetControl *pAnimationSetController );
virtual ~CDmeCombinationOperatorPanel();
virtual void OnTick();
void SetCombinationOperator( CDmeCombinationOperator *pOp );
void RefreshCombinationOperator();
private:
void CreateFakeAnimationSet( );
void DestroyFakeAnimationSet( );
// Adds new controls to the animation set
void AddNewAnimationSetControls();
// Removes a controls from all presets
void RemoveAnimationControlFromPresets( const char *pControlName );
// Removes controls from the animation set that aren't used
void RemoveUnusedAnimationSetControls();
// Modify controls in the presets which have had stereo settings changed
void ModifyExistingAnimationSetControls();
// Modify controls in the presets which have had stereo settings changed
void ModifyExistingAnimationSetPresets( CDmElement *pControlElement );
// Modify controls which have had stereo settings changed
void ModifyExistingAnimationSetControl( CDmElement *pControlElement );
void RefreshAnimationSet();
// Sort control names to match the combination controls
void SortAnimationSetControls();
CDmeHandle< CDmeCombinationOperator > m_hCombinationOperator;
CUtlVector< IDmeOperator * > m_operatorList;
};
//-----------------------------------------------------------------------------
// Constructor/destructor
//-----------------------------------------------------------------------------
CDmeCombinationOperatorPanel::CDmeCombinationOperatorPanel( vgui::Panel *parent, const char *panelName, CBaseAnimationSetControl *pAnimationSetController ) :
BaseClass( parent, panelName, pAnimationSetController )
{
CreateFakeAnimationSet();
vgui::ivgui()->AddTickSignal( GetVPanel(), 0 );
}
CDmeCombinationOperatorPanel::~CDmeCombinationOperatorPanel()
{
DestroyFakeAnimationSet();
}
//-----------------------------------------------------------------------------
// Create, destroy fake animation sets
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::CreateFakeAnimationSet()
{
CDmeFilmClip *pFilmClip = CreateElement< CDmeFilmClip >( "fakeFilmClip", DMFILEID_INVALID );
CDmeAnimationSet *pAnimSet = CreateElement< CDmeAnimationSet >( "fakeAnimSet", DMFILEID_INVALID );
pAnimSet->SetValue( "gameModel", DMELEMENT_HANDLE_INVALID );
pFilmClip->GetAnimationSets().AddToTail( pAnimSet );
g_pDataModel->DontAutoDelete( pFilmClip->GetHandle() );
ChangeAnimationSetClip( pFilmClip );
}
void CDmeCombinationOperatorPanel::DestroyFakeAnimationSet( )
{
DestroyElement( m_pController->GetAnimationSetClip(), TD_DEEP );
}
//-----------------------------------------------------------------------------
// Sets combination ops + animation sets
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::SetCombinationOperator( CDmeCombinationOperator *pOp )
{
// The Animation Set Editor Doesn't Handle Passing The Same Animation Set With
// Different Data In It Very Well
DestroyFakeAnimationSet();
CreateFakeAnimationSet();
m_operatorList.RemoveAll();
if ( pOp != m_hCombinationOperator.Get() )
{
m_hCombinationOperator = pOp;
m_operatorList.AddToTail( m_hCombinationOperator );
for ( int i = 0; i < pOp->GetOperationTargetCount(); ++i )
{
CDmeFlexRules *pDmeFlexRules = CastElement< CDmeFlexRules >( pOp->GetOperationTarget( i ) );
if ( !pDmeFlexRules )
continue;
m_operatorList.AddToTail( pDmeFlexRules );
for ( int j = 0; j < pDmeFlexRules->GetRuleCount(); ++j )
{
CDmeFlexRuleBase *pDmeFlexRule = pDmeFlexRules->GetRule( j );
if ( !pDmeFlexRule )
continue;
m_operatorList.AddToTail( pDmeFlexRule );
}
}
RefreshCombinationOperator();
}
}
//-----------------------------------------------------------------------------
// Removes a controls from all presets
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::RemoveAnimationControlFromPresets( const char *pControlName )
{
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimationSet = traversal.Next();
Assert( !traversal.IsValid() );
CDmrElementArray< CDmePresetGroup > presetGroupList = pAnimationSet->GetPresetGroups();
int nPresetGroupCount = presetGroupList.Count();
for ( int i = 0; i < nPresetGroupCount; ++i )
{
CDmePresetGroup *pPresetGroup = presetGroupList[ i ];
CDmrElementArray< CDmePreset > presetList = pPresetGroup->GetPresets();
int nPresetCount = presetList.Count();
for ( int j = 0; j < nPresetCount; ++j )
{
CDmePreset *pPreset = presetList[ j ];
CDmrElementArray<> controlValues = pPreset->GetControlValues();
int nControlCount = controlValues.Count();
for ( int k = 0; k < nControlCount; ++k )
{
CDmElement *v = controlValues[ k ];
if ( !Q_stricmp( v->GetName(), pControlName ) )
{
controlValues.FastRemove( k );
break;
}
}
}
}
}
//-----------------------------------------------------------------------------
// Removes controls from the animation set that aren't used
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::RemoveUnusedAnimationSetControls()
{
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimationSet = traversal.Next();
Assert( !traversal.IsValid() );
CDmrElementArray< > controls = pAnimationSet->GetControls();
// Remove all controls in the animation set and in presets that don't exist in the combination system
int nAnimSetCount = controls.Count();
for ( int i = nAnimSetCount; --i >= 0; )
{
CDmElement *pControlElement = controls[i];
if ( !pControlElement )
continue;
// Don't do any of this work for transforms
if ( IsTransformControl( pControlElement ) )
continue;
const char *pControlName = pControlElement->GetName();
// Look for a match
if ( FindComboOpControlIndexForAnimSetControl( m_hCombinationOperator, pControlName ) >= 0 )
continue;
// No match, blow the control away.
RemoveAnimationControlFromPresets( pControlName );
pAnimationSet->RemoveControlFromGroups( pControlName );
controls.FastRemove( i );
}
}
//-----------------------------------------------------------------------------
// Modify controls in the presets which have had stereo settings changed
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::ModifyExistingAnimationSetControl( CDmElement *pControlElement )
{
const char *pControlName = pControlElement->GetName();
// Look for a match
bool bIsMultiControl;
ControlIndex_t nControlIndex = FindComboOpControlIndexForAnimSetControl( m_hCombinationOperator, pControlName, &bIsMultiControl );
Assert( nControlIndex >= 0 );
float flDefaultValue = m_hCombinationOperator->GetControlDefaultValue( nControlIndex );
if ( bIsMultiControl )
{
// multi control can't (currently) be stereo, and so it either exists or it doesn't...
pControlElement->SetValue< float >( "value", m_hCombinationOperator->GetMultiControlLevel( nControlIndex ) );
pControlElement->SetValue( "defaultValue", 0.5f );
}
else
{
bool bIsStereoControl = m_hCombinationOperator->IsStereoControl( nControlIndex );
bool bIsAnimControlStereo = IsStereoControl( pControlElement );
if ( bIsAnimControlStereo != bIsStereoControl )
{
if ( !bIsStereoControl )
{
float flValue = m_hCombinationOperator->GetControlValue( nControlIndex );
pControlElement->SetValue< float >( "value", flValue );
pControlElement->RemoveAttribute( "leftValue" );
pControlElement->RemoveAttribute( "rightValue" );
}
else
{
const Vector2D &value = m_hCombinationOperator->GetStereoControlValue( nControlIndex );
pControlElement->SetValue< float >( "leftValue", value.x );
pControlElement->SetValue< float >( "rightValue", value.y );
pControlElement->RemoveAttribute( "value" );
}
}
pControlElement->SetValue( "defaultValue", flDefaultValue );
}
}
//-----------------------------------------------------------------------------
// Modify controls in the presets which have had stereo settings changed
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::ModifyExistingAnimationSetPresets( CDmElement *pControlElement )
{
const char *pControlName = pControlElement->GetName();
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimationSet = traversal.Next();
Assert( !traversal.IsValid() );
const CDmrElementArray< CDmePresetGroup > &presetGroupList = pAnimationSet->GetPresetGroups();
int nPresetGroupCount = presetGroupList.Count();
for ( int g = 0; g < nPresetGroupCount; ++g )
{
CDmePresetGroup *pPresetGroup = presetGroupList[ g ];
const CDmrElementArray< CDmePreset > &presetList = pPresetGroup->GetPresets();
int nPresetCount = presetList.Count();
for ( int i = 0; i < nPresetCount; ++i )
{
CDmePreset *pPreset = presetList[ i ];
Assert( !pPreset->IsAnimated() ); // deal with this after GDC
if ( pPreset->IsAnimated() )
continue;
const CDmrElementArray< CDmElement > &controlValues = pPreset->GetControlValues( );
int nControlCount = controlValues.Count();
for ( int j = 0; j < nControlCount; ++j )
{
CDmElement *v = controlValues[ j ];
if ( Q_stricmp( v->GetName(), pControlName ) )
continue;
bool bIsAnimControlStereo = IsStereoControl( pControlElement );
if ( bIsAnimControlStereo )
{
float flValue = v->GetValue< float >( "value" );
v->RemoveAttribute( "value" );
v->InitValue( "leftValue", flValue );
v->InitValue( "rightValue", flValue );
}
else
{
float flLeftValue = v->GetValue< float >( "leftValue" );
float flRightValue = v->GetValue< float >( "rightValue" );
v->RemoveAttribute( "leftValue" );
v->RemoveAttribute( "rightValue" );
v->InitValue( "value", MAX( flLeftValue, flRightValue ) ); // TODO - should this be max or average?
}
}
}
}
}
//-----------------------------------------------------------------------------
// Modify controls which have had stereo settings changed
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::ModifyExistingAnimationSetControls()
{
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimationSet = traversal.Next();
Assert( !traversal.IsValid() );
const CDmrElementArray< CDmElement > &controls = pAnimationSet->GetControls();
// Update the main controls; update defaults and add or remove combo + multi data
int nAnimSetCount = controls.Count();
for ( int i = nAnimSetCount; --i >= 0; )
{
CDmElement *pControlElement = controls[i];
if ( !pControlElement )
continue;
// Don't do any of this work for transforms
if ( IsTransformControl( pControlElement ) )
continue;
ModifyExistingAnimationSetControl( pControlElement );
ModifyExistingAnimationSetPresets( pControlElement );
}
}
//-----------------------------------------------------------------------------
// Adds new controls to the animation set
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::AddNewAnimationSetControls()
{
if ( !m_hCombinationOperator.Get() )
return;
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimationSet = traversal.Next();
Assert( !traversal.IsValid() );
CDmaElementArray< > &controls = pAnimationSet->GetControls();
// Remove all controls in the animation set and in presets that don't exist in the combination system
int nFirstControl = controls.Count();
int nCombinationControlCount = m_hCombinationOperator->GetControlCount();
int iCurrentAnimSetControl = 0;
for ( int i = 0; i < nCombinationControlCount; ++i, ++iCurrentAnimSetControl )
{
const char *pControlName = m_hCombinationOperator->GetControlName( i );
if ( !pAnimationSet->FindControl( pControlName ) )
{
bool bIsStereoControl = m_hCombinationOperator->IsStereoControl( i );
float flDefaultValue = m_hCombinationOperator->GetControlDefaultValue( i );
// Add the control to the controls group
CDmElement *pControl = CreateElement< CDmElement >( pControlName, pAnimationSet->GetFileId() );
Assert( pControl );
controls.InsertBefore( iCurrentAnimSetControl, pControl );
if ( bIsStereoControl )
{
const Vector2D &value = m_hCombinationOperator->GetStereoControlValue(i);
pControl->SetValue( "leftValue", value.x );
pControl->SetValue( "rightValue", value.y );
}
else
{
pControl->SetValue( "value", m_hCombinationOperator->GetControlValue(i) );
}
pControl->SetValue( "defaultValue", flDefaultValue );
}
bool bIsMultiControl = m_hCombinationOperator->IsMultiControl( i );
if ( bIsMultiControl )
{
++iCurrentAnimSetControl;
char pMultiControlName[ 256 ];
V_snprintf( pMultiControlName, sizeof( pMultiControlName ), MULTI_CONTROL_FORMAT_STRING, pControlName );
if ( !pAnimationSet->FindControl( pMultiControlName ) )
{
CDmElement *pMultiControl = CreateElement< CDmElement >( pMultiControlName, pAnimationSet->GetFileId() );
Assert( pMultiControl );
controls.InsertBefore( iCurrentAnimSetControl, pMultiControl );
pMultiControl->SetValue( "value", m_hCombinationOperator->GetMultiControlLevel( i ) );
pMultiControl->SetValue( "defaultValue", 0.5f );
}
}
}
int nLastControl = controls.Count();
if ( nLastControl == nFirstControl )
return;
// Add new controls to the root group
CDmElement *pGroup = pAnimationSet->FindOrAddControlGroup( NULL, "Root" );
// Fill in members
CDmrElementArray<> groups( pGroup, "controls" );
for ( int i = nFirstControl; i < nLastControl; ++i )
{
groups.AddToTail( controls[ i ] );
}
}
//-----------------------------------------------------------------------------
// Sort control names to match the combination controls
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::SortAnimationSetControls()
{
// TODO - we should be storing which animationset an item is associated with
CAnimSetGroupAnimSetTraversal traversal( m_pController->GetAnimationSetClip() );
CDmeAnimationSet *pAnimSet = traversal.Next();
Assert( !traversal.IsValid() );
// TODO: Figure out why this isn't called on load
pAnimSet->OnElementUnserialized();
CDmaElementArray<> &controls = pAnimSet->GetControls();
int nControlCount = controls.Count();
if ( nControlCount == 0 )
return;
int nCombinationControlCount = m_hCombinationOperator->GetControlCount();
DmElementHandle_t *pElements = (DmElementHandle_t*)_alloca( nControlCount * sizeof(DmElementHandle_t) );
int iCurrentControlIndex = 0;
for ( int i = 0; i < nCombinationControlCount; ++i )
{
const char *pControlName = m_hCombinationOperator->GetControlName( i );
CDmElement *pControl = pAnimSet->FindControl( pControlName );
pElements[iCurrentControlIndex++] = pControl->GetHandle();
if ( m_hCombinationOperator->IsMultiControl( i ) )
{
char pMultiControlName[ 256 ];
V_snprintf( pMultiControlName, sizeof( pMultiControlName ), MULTI_CONTROL_FORMAT_STRING, pControlName );
CDmElement *pMultiControl = pAnimSet->FindControl( pMultiControlName );
pElements[iCurrentControlIndex++] = pMultiControl->GetHandle();
}
}
Assert( nControlCount == iCurrentControlIndex );
controls.SetMultiple( 0, nControlCount, pElements );
}
//-----------------------------------------------------------------------------
// Called when the animation set has to be made to match the combination operator
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::RefreshAnimationSet()
{
if ( !m_pController->GetAnimationSetClip() )
return;
CDisableUndoScopeGuard sg;
// Remove all controls in the animation set and in presets that don't exist in the combination system
RemoveUnusedAnimationSetControls();
// Modify controls in the presets which have had stereo settings changed
ModifyExistingAnimationSetControls();
// Add all controls not in the animation set but which do exist in the combination system
AddNewAnimationSetControls();
// Sort control names to match the combination controls
SortAnimationSetControls();
}
void CDmeCombinationOperatorPanel::RefreshCombinationOperator()
{
RefreshAnimationSet();
ChangeAnimationSetClip( m_pController->GetAnimationSetClip() );
}
//-----------------------------------------------------------------------------
// Simulate
//-----------------------------------------------------------------------------
void CDmeCombinationOperatorPanel::OnTick()
{
BaseClass::OnTick();
if ( m_hCombinationOperator )
{
{
CDisableUndoScopeGuard sg;
int nCombinationControlCount = m_hCombinationOperator->GetControlCount();
int iCurrentControlIndex = 0;
for ( int i = 0; i < nCombinationControlCount; ++i )
{
AttributeValue_t value;
if ( GetAttributeSlider()->GetSliderValues( &value, iCurrentControlIndex++ ) )
{
if ( m_hCombinationOperator->IsStereoControl( i ) )
{
m_hCombinationOperator->SetControlValue( i, value.m_pValue[ANIM_CONTROL_VALUE_LEFT], value.m_pValue[ANIM_CONTROL_VALUE_RIGHT] );
}
else
{
m_hCombinationOperator->SetControlValue( i, value.m_pValue[ANIM_CONTROL_VALUE] );
}
}
if ( m_hCombinationOperator->IsMultiControl( i ) )
{
AttributeValue_t multiValue;
if ( GetAttributeSlider()->GetSliderValues( &multiValue, iCurrentControlIndex++ ) )
{
m_hCombinationOperator->SetMultiControlLevel( i, multiValue.m_pValue[ANIM_CONTROL_VALUE] );
}
}
}
}
if ( m_operatorList.Count() )
{
CDisableUndoScopeGuard guard;
g_pDmElementFramework->SetOperators( m_operatorList );
g_pDmElementFramework->Operate( true );
}
else
{
// FIXME: Shouldn't this happen at the application level?
// run the machinery - apply, resolve, dependencies, operate, resolve
CUtlVector< IDmeOperator* > operators;
operators.AddToTail( m_hCombinationOperator );
CDisableUndoScopeGuard guard;
g_pDmElementFramework->SetOperators( operators );
g_pDmElementFramework->Operate( true );
}
}
// allow elements and attributes to be edited again
g_pDmElementFramework->BeginEdit();
}
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CDmeDagEditPanel::CDmeDagEditPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
m_pPropertiesSplitter = new vgui::Splitter( this, "PropertiesSplitter", vgui::SPLITTER_MODE_VERTICAL, 1 );
vgui::Panel *pSplitterLeftSide = m_pPropertiesSplitter->GetChild( 0 );
vgui::Panel *pSplitterRightSide = m_pPropertiesSplitter->GetChild( 1 );
m_pDagRenderPanel = new CDmeDagRenderPanel( pSplitterRightSide, "DagRenderPanel" );
m_pEditorSheet = new vgui::PropertySheet( pSplitterLeftSide, "EditorSheet" );
m_pEditorSheet->AddActionSignalTarget( this );
m_pAnimationPage = new vgui::PropertyPage( m_pEditorSheet, "AnimationPage" );
m_pCombinationPage = new vgui::PropertyPage( m_pEditorSheet, "AnimationSetEditor" );
m_pVertexAnimationPage = new vgui::PropertyPage( m_pEditorSheet, "VertexAnimationPage" );
CCombinationOperatorControl *pAnimationSetController = new CCombinationOperatorControl();
m_pCombinationPanel = new CDmeCombinationOperatorPanel( m_pCombinationPage, "AnimationSetEditorPanel", pAnimationSetController );
m_pCombinationPanel->CreateToolsSubPanels();
m_pAnimationListPanel = new CDmeAnimationListPanel( m_pAnimationPage, "AnimationListPanel" );
m_pAnimationListPanel->AddActionSignalTarget( this );
m_pVertexAnimationListPanel = new CDmeAnimationListPanel( m_pVertexAnimationPage, "VertexAnimationListPanel" );
m_pVertexAnimationListPanel->AddActionSignalTarget( this );
m_pCombinationPage->LoadControlSettingsAndUserConfig( "resource/dmedageditpanel_animationseteditorpage.res" );
m_pAnimationPage->LoadControlSettingsAndUserConfig( "resource/dmedageditpanel_animationpage.res" );
m_pVertexAnimationPage->LoadControlSettingsAndUserConfig( "resource/dmedageditpanel_vertexanimationpage.res" );
// Load layout settings; has to happen before pinning occurs in code
LoadControlSettingsAndUserConfig( "resource/dmedageditpanel.res" );
// NOTE: Page adding happens *after* LoadControlSettingsAndUserConfig
// because the layout of the sheet is correct at this point.
m_pEditorSheet->AddPage( m_pAnimationPage, "Animation" );
m_pEditorSheet->AddPage( m_pCombinationPage, "Combination" );
m_pEditorSheet->AddPage( m_pVertexAnimationPage, "Vertex Animation" );
m_pEditorSheet->SetActivePage( m_pCombinationPage );
}
CDmeDagEditPanel::~CDmeDagEditPanel()
{
}
//-----------------------------------------------------------------------------
// Set the scene
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::SetDmeElement( CDmeDag *pScene )
{
m_pDagRenderPanel->SetDmeElement( pScene );
}
//-----------------------------------------------------------------------------
// Sets up the various panels in the dag editor
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::SetMakefileRootElement( CDmElement *pRoot )
{
CDmeAnimationList *pAnimationList = pRoot->GetValueElement< CDmeAnimationList >( "animationList" );
SetAnimationList( pAnimationList );
CDmeAnimationList *pVertexAnimationList = pRoot->GetValueElement< CDmeAnimationList >( "vertexAnimationList" );
SetVertexAnimationList( pVertexAnimationList );
CDmeCombinationOperator *pComboOp = pRoot->GetValueElement< CDmeCombinationOperator >( "combinationOperator" );
SetCombinationOperator( pComboOp );
}
//-----------------------------------------------------------------------------
// Other methods which hook into DmePanel
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::SetDmeElement( CDmeSourceSkin *pSkin )
{
m_pDagRenderPanel->SetDmeElement( pSkin );
// First, try to grab the dependent makefile
CDmeMakefile *pSourceMakefile = pSkin->GetDependentMakefile();
if ( !pSourceMakefile )
return;
// Next, try to grab the output of that makefile
CDmElement *pOutput = pSourceMakefile->GetOutputElement( true );
if ( !pOutput )
return;
SetMakefileRootElement( pOutput );
}
void CDmeDagEditPanel::SetDmeElement( CDmeSourceAnimation *pAnimation )
{
m_pDagRenderPanel->SetDmeElement( pAnimation );
// First, try to grab the dependent makefile
CDmeMakefile *pSourceMakefile = pAnimation->GetDependentMakefile();
if ( !pSourceMakefile )
return;
// Next, try to grab the output of that makefile
CDmElement *pOutput = pSourceMakefile->GetOutputElement( true );
if ( !pOutput )
return;
SetMakefileRootElement( pOutput );
// if ( pAnimationList->FindAnimation( pAnimation->m_SourceAnimationName ) < 0 )
// return;
}
void CDmeDagEditPanel::SetDmeElement( CDmeDCCMakefile *pDCCMakefile )
{
m_pDagRenderPanel->SetDmeElement( pDCCMakefile );
// First, try to grab the dependent makefile
CDmElement *pOutput = pDCCMakefile->GetOutputElement( true );
if ( !pOutput )
return;
SetMakefileRootElement( pOutput );
}
CDmeDag *CDmeDagEditPanel::GetDmeElement()
{
return m_pDagRenderPanel->GetDmeElement();
}
//-----------------------------------------------------------------------------
// paint it!
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::Paint()
{
BaseClass::Paint();
}
//-----------------------------------------------------------------------------
// Sets animation
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::SetAnimationList( CDmeAnimationList *pAnimationList )
{
m_pDagRenderPanel->SetAnimationList( pAnimationList );
m_pDagRenderPanel->SelectAnimation( "" );
m_pAnimationListPanel->SetAnimationList( pAnimationList );
}
void CDmeDagEditPanel::SetVertexAnimationList( CDmeAnimationList *pAnimationList )
{
m_pDagRenderPanel->SetVertexAnimationList( pAnimationList );
m_pDagRenderPanel->SelectVertexAnimation( "" );
m_pVertexAnimationListPanel->SetAnimationList( pAnimationList );
}
void CDmeDagEditPanel::SetCombinationOperator( CDmeCombinationOperator *pComboOp )
{
m_pCombinationPanel->SetCombinationOperator( pComboOp );
}
void CDmeDagEditPanel::RefreshCombinationOperator()
{
m_pCombinationPanel->RefreshCombinationOperator();
}
//-----------------------------------------------------------------------------
// Called when the page changes
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::OnPageChanged( )
{
if ( m_pEditorSheet->GetActivePage() == m_pCombinationPage )
{
m_pDagRenderPanel->SelectAnimation( "" );
m_pDagRenderPanel->SelectVertexAnimation( "" );
return;
}
if ( m_pEditorSheet->GetActivePage() == m_pAnimationPage )
{
m_pDagRenderPanel->SelectAnimation( m_pAnimationListPanel->GetSelectedAnimation() );
m_pDagRenderPanel->SelectVertexAnimation( "" );
return;
}
if ( m_pEditorSheet->GetActivePage() == m_pVertexAnimationPage )
{
m_pDagRenderPanel->SelectAnimation( "" );
m_pDagRenderPanel->SelectVertexAnimation( m_pVertexAnimationListPanel->GetSelectedAnimation() );
return;
}
}
//-----------------------------------------------------------------------------
// Called when new animations are selected
//-----------------------------------------------------------------------------
void CDmeDagEditPanel::OnAnimationSelected( KeyValues *pKeyValues )
{
vgui::Panel *pPanel = (vgui::Panel *)pKeyValues->GetPtr( "panel", NULL );
const char *pAnimationName = pKeyValues->GetString( "animationName", "" );
if ( pPanel == m_pAnimationListPanel )
{
m_pDagRenderPanel->SelectAnimation( pAnimationName );
return;
}
if ( pPanel == m_pVertexAnimationListPanel )
{
m_pDagRenderPanel->SelectVertexAnimation( pAnimationName );
return;
}
}
void CDmeDagEditPanel::OnAnimationDeselected( KeyValues *pKeyValues )
{
vgui::Panel *pPanel = (vgui::Panel *)pKeyValues->GetPtr( "panel", NULL );
if ( pPanel == m_pAnimationListPanel )
{
m_pDagRenderPanel->SelectAnimation( "" );
return;
}
if ( pPanel == m_pVertexAnimationListPanel )
{
m_pDagRenderPanel->SelectVertexAnimation( "" );
return;
}
}

View File

@@ -0,0 +1,919 @@
//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#include "dme_controls/dmedagrenderpanel.h"
#include "movieobjects/dmedag.h"
#include "movieobjects/dmemodel.h"
#include "movieobjects/dmeanimationlist.h"
#include "movieobjects/dmeclip.h"
#include "movieobjects/dmechannel.h"
#include "movieobjects/dmemdlmakefile.h"
#include "movieobjects/dmedccmakefile.h"
#include "movieobjects/dmemesh.h"
#include "movieobjects/dmedrawsettings.h"
#include "dme_controls/dmepanel.h"
#include "tier1/KeyValues.h"
#include "vguimatsurface/IMatSystemSurface.h"
#include "tier3/tier3.h"
#include "materialsystem/imaterialsystemhardwareconfig.h"
#include "materialsystem/imesh.h"
#include "vgui_controls/Menu.h"
#include "vgui_controls/MenuBar.h"
#include "vgui_controls/MenuButton.h"
//-----------------------------------------------------------------------------
//
// Hook into the dme panel editor system
//
//-----------------------------------------------------------------------------
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeDag, "DmeDagRenderer", "DmeDag Preview Renderer", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeSourceSkin, "DmeSourceSkinPreview", "MDL Skin Previewer", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeSourceAnimation, "DmeSourceAnimationPreview", "MDL Animation Previewer", false );
IMPLEMENT_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeDCCMakefile, "DmeMakeFileOutputPreview", "DCC MakeFile Output Preview", false );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CDmeDagRenderPanel::CDmeDagRenderPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
CDisableUndoScopeGuard sg;
m_bDrawJointNames = false;
m_bDrawJoints = false;
m_bDrawGrid = true;
m_bDrawAxis = true;
m_bModelInEngineCoordinates = false;
m_bModelZUp = false;
// Deal with the default cubemap
ITexture *pCubemapTexture = g_pMaterialSystem->FindTexture( "editor/cubemap", NULL, true );
m_DefaultEnvCubemap.Init( pCubemapTexture );
pCubemapTexture = g_pMaterialSystem->FindTexture( "editor/cubemap.hdr", NULL, true );
m_DefaultHDREnvCubemap.Init( pCubemapTexture );
if ( g_pMaterialSystem )
{
KeyValues *pVMTKeyValues = new KeyValues( "wireframe" );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
pVMTKeyValues->SetInt( "$ignorez", 1 );
m_axisMaterial.Init( "__DmeDagRenderPanelAxis", pVMTKeyValues );
}
m_pDrawSettings = CreateElement< CDmeDrawSettings >( "drawSettings", g_pDataModel->FindOrCreateFileId( "DagRenderPanelDrawSettings" ) );
m_hDrawSettings = m_pDrawSettings;
m_pMenuBar = new vgui::MenuBar( this, "Dag Render Panel Menu Bar" );
m_pShadingMenu = new vgui::Menu( NULL, "Shading Menu" );
m_nMenuSmoothShade = m_pShadingMenu->AddCheckableMenuItem( "&Smooth Shade", new KeyValues( "SmoothShade" ), this );
m_nMenuFlatShade = m_pShadingMenu->AddCheckableMenuItem( "&Flat Shade", new KeyValues( "FlatShade" ), this );
m_nMenuWireframe = m_pShadingMenu->AddCheckableMenuItem( "&Wireframe", new KeyValues( "Wireframe" ), this );
m_pShadingMenu->AddSeparator();
m_nMenuBoundingBox = m_pShadingMenu->AddCheckableMenuItem( "&Bounding Box", new KeyValues( "BoundingBox" ), this );
m_pShadingMenu->AddSeparator(); // Bug is visibility
m_nMenuNormals = m_pShadingMenu->AddCheckableMenuItem( "&Normals", new KeyValues( "Normals" ), this );
m_nMenuWireframeOnShaded = m_pShadingMenu->AddCheckableMenuItem( "WireFrame &On Shaded", new KeyValues( "WireframeOnShaded" ), this );
m_nMenuBackfaceCulling = m_pShadingMenu->AddCheckableMenuItem( "&Backface Culling", new KeyValues( "BackfaceCulling" ), this );
m_nMenuXRay = m_pShadingMenu->AddCheckableMenuItem( "&X-Ray", new KeyValues( "XRay" ), this );
m_nMenuGrayShade = m_pShadingMenu->AddCheckableMenuItem( "&Gray Shade", new KeyValues( "GrayShade" ), this );
// For now...
m_pShadingMenu->SetItemVisible( m_nMenuFlatShade, false );
m_pShadingMenu->SetItemEnabled( m_nMenuFlatShade, false );
m_pShadingMenu->SetItemVisible( m_nMenuBoundingBox, false );
m_pShadingMenu->SetItemEnabled( m_nMenuBoundingBox, false );
m_pShadingMenu->SetItemVisible( m_nMenuBackfaceCulling, false );
m_pShadingMenu->SetItemEnabled( m_nMenuBackfaceCulling, false );
m_pShadingMenu->SetItemVisible( m_nMenuXRay, false );
m_pShadingMenu->SetItemEnabled( m_nMenuXRay, false );
m_pMenuBar->AddMenu( "&Shading", m_pShadingMenu );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CDmeDagRenderPanel::~CDmeDagRenderPanel()
{
if ( g_pMaterialSystem )
{
m_axisMaterial.Shutdown();
}
}
//-----------------------------------------------------------------------------
// Scheme settings
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetBorder( pScheme->GetBorder( "MenuBorder") );
m_hFont = pScheme->GetFont( "DmePropertyVerySmall", IsProportional() );
}
//-----------------------------------------------------------------------------
// Set the scene
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::SetDmeElement( CDmeDag *pScene )
{
m_hDag = pScene;
ComputeDefaultTangentData( m_hDag, false );
CDmeModel *pDmeModel = CastElement< CDmeModel >( m_hDag );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
}
//-----------------------------------------------------------------------------
// Other methods which hook into DmePanel
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::SetDmeElement( CDmeSourceSkin *pSkin )
{
// First, try to grab the dependent makefile
CDmeMakefile *pSourceMakefile = pSkin->GetDependentMakefile();
if ( !pSourceMakefile )
{
m_hDag = NULL;
return;
}
// Next, try to grab the output of that makefile
CDmElement *pOutput = pSourceMakefile->GetOutputElement( true );
if ( !pOutput )
{
m_hDag = NULL;
return;
}
// Finally, grab the 'skin' attribute of that makefile
m_hDag = pOutput->GetValueElement< CDmeDag >( "model" );
ComputeDefaultTangentData( m_hDag, false );
DrawJoints( false );
DrawJointNames( false );
CDmeModel *pDmeModel = CastElement< CDmeModel >( m_hDag );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
else
{
pDmeModel = CastElement< CDmeModel >( pOutput );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
}
}
void CDmeDagRenderPanel::SetDmeElement( CDmeSourceAnimation *pAnimation )
{
// First, try to grab the dependent makefile
CDmeMakefile *pSourceMakefile = pAnimation->GetDependentMakefile();
if ( !pSourceMakefile )
{
m_hDag = NULL;
return;
}
// Next, try to grab the output of that makefile
CDmElement *pOutput = pSourceMakefile->GetOutputElement( true );
if ( !pOutput )
{
m_hDag = NULL;
return;
}
// Finally, grab the 'model' or 'skeleton' attribute of that makefile
CDmeDag *pDag = pOutput->GetValueElement< CDmeDag >( "model" );
if ( !pDag )
{
pDag = pOutput->GetValueElement< CDmeDag >( "skeleton" );
}
if ( !pDag )
return;
CDmeAnimationList *pAnimationList = pOutput->GetValueElement< CDmeAnimationList >( "animationList" );
if ( !pAnimationList )
return;
if ( pAnimationList->FindAnimation( pAnimation->m_SourceAnimationName ) < 0 )
return;
m_hDag = pDag;
ComputeDefaultTangentData( m_hDag, false );
m_hAnimationList = pAnimationList;
SelectAnimation( pAnimation->m_SourceAnimationName );
DrawJoints( true );
DrawJointNames( true );
CDmeModel *pDmeModel = CastElement< CDmeModel >( m_hDag );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
else
{
pDmeModel = CastElement< CDmeModel >( pOutput );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
}
}
void CDmeDagRenderPanel::SetDmeElement( CDmeDCCMakefile *pDCCMakefile )
{
// First, try to grab the dependent makefile
CDmElement *pOutputElement = pDCCMakefile->GetOutputElement( true );
if ( !pOutputElement )
{
m_hDag = NULL;
return;
}
// Finally, grab the 'model' or 'skeleton' attribute of that makefile
CDmeDag *pDag = pOutputElement->GetValueElement< CDmeDag >( "model" );
if ( !pDag )
{
pDag = pOutputElement->GetValueElement< CDmeDag >( "skeleton" );
}
if ( !pDag )
return;
CDmeAnimationList *pAnimationList = pOutputElement->GetValueElement< CDmeAnimationList >( "animationList" );
m_hDag = pDag;
ComputeDefaultTangentData( m_hDag, false );
m_hAnimationList = pAnimationList;
SelectAnimation( 0 );
DrawJoints( pAnimationList != NULL );
DrawJointNames( pAnimationList != NULL );
CDmeModel *pDmeModel = CastElement< CDmeModel >( m_hDag );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
else
{
pDmeModel = CastElement< CDmeModel >( pOutputElement );
if ( pDmeModel )
{
ModelZUp( pDmeModel->IsZUp() );
}
}
}
CDmeDag *CDmeDagRenderPanel::GetDmeElement()
{
return m_hDag;
}
//-----------------------------------------------------------------------------
// Draw joint names
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawJointNames( CDmeDag *pRoot, CDmeDag *pDag, const matrix3x4_t& parentToWorld )
{
int nJointIndex = -1;
CDmeModel *pRootModel = CastElement<CDmeModel>( pRoot );
if ( pRootModel )
{
nJointIndex = pRootModel->GetJointIndex( pDag );
if ( nJointIndex < 0 && pRootModel != pDag )
return;
}
matrix3x4_t jointToParent, jointToWorld;
pDag->GetTransform()->GetTransform( jointToParent );
ConcatTransforms( parentToWorld, jointToParent, jointToWorld );
CDmeJoint *pJoint = CastElement< CDmeJoint >( pDag );
if ( pJoint )
{
Vector vecJointOrigin;
MatrixGetColumn( jointToWorld, 3, vecJointOrigin );
Vector2D vecPanelPos;
ComputePanelPosition( vecJointOrigin, &vecPanelPos );
char pJointName[512];
if ( nJointIndex >= 0 )
{
Q_snprintf( pJointName, sizeof(pJointName), "%d : %s", nJointIndex, pJoint->GetName() );
}
else
{
Q_snprintf( pJointName, sizeof(pJointName), "%s", pJoint->GetName() );
}
g_pMatSystemSurface->DrawColoredText( m_hFont, vecPanelPos.x + 5, vecPanelPos.y, 255, 255, 255, 255, pJointName );
}
int nCount = pDag->GetChildCount();
for ( int i = 0; i < nCount; ++i )
{
CDmeDag *pChild = pDag->GetChild(i);
if ( !pChild )
continue;
DrawJointNames( pRoot, pChild, jointToWorld );
}
}
//-----------------------------------------------------------------------------
// Draw highlight points
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawHighlightPoints()
{
if ( !m_pDrawSettings )
return;
const float flPointRadius = m_pDrawSettings->m_flHighlightSize;
Vector2D vecPanelPos;
g_pMatSystemSurface->DrawSetColor( m_pDrawSettings->m_cHighlightColor );
const CUtlVector< Vector > &highLightPoints = m_pDrawSettings->GetHighlightPoints();
const int nPointCount = highLightPoints.Count();
for ( int i = 0; i < nPointCount; ++i )
{
ComputePanelPosition( highLightPoints[i], &vecPanelPos );
g_pMatSystemSurface->DrawFilledRect( vecPanelPos.x - flPointRadius, vecPanelPos.y - flPointRadius, vecPanelPos.x + flPointRadius, vecPanelPos.y + flPointRadius );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnSmoothShade()
{
if ( m_pShadingMenu->IsChecked( m_nMenuSmoothShade ) )
{
m_pDrawSettings->SetDrawType( CDmeDrawSettings::DRAW_SMOOTH );
}
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnFlatShade()
{
if ( m_pShadingMenu->IsChecked( m_nMenuFlatShade ) )
{
m_pDrawSettings->SetDrawType( CDmeDrawSettings::DRAW_FLAT );
}
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnWireframe()
{
if ( m_pShadingMenu->IsChecked( m_nMenuWireframe ) )
{
m_pDrawSettings->SetDrawType( CDmeDrawSettings::DRAW_WIREFRAME );
}
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnBoundingBox()
{
if ( m_pShadingMenu->IsChecked( m_nMenuBoundingBox ) )
{
m_pDrawSettings->SetDrawType( CDmeDrawSettings::DRAW_BOUNDINGBOX );
}
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnNormals()
{
m_pDrawSettings->SetNormals( m_pShadingMenu->IsChecked( m_nMenuNormals ) );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnWireframeOnShaded()
{
m_pDrawSettings->SetWireframeOnShaded( m_pShadingMenu->IsChecked( m_nMenuWireframeOnShaded ) );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnBackfaceCulling()
{
m_pDrawSettings->SetBackfaceCulling( m_pShadingMenu->IsChecked( m_nMenuBackfaceCulling ) );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnXRay()
{
m_pDrawSettings->SetXRay( m_pShadingMenu->IsChecked( m_nMenuXRay ) );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnGrayShade()
{
m_pDrawSettings->SetGrayShade( m_pShadingMenu->IsChecked( m_nMenuGrayShade ) );
UpdateMenu();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnFrame()
{
if ( !m_hDag )
return;
float flRadius;
Vector vecCenter, vecWorldCenter;
m_hDag->GetBoundingSphere( vecCenter, flRadius );
matrix3x4_t dmeToEngine;
if ( !m_bModelInEngineCoordinates )
{
CDmeDag::DmeToEngineMatrix( dmeToEngine, m_bModelZUp );
}
VectorTransform( vecCenter, dmeToEngine, vecWorldCenter );
LookAt( vecWorldCenter, flRadius );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::PerformLayout()
{
BaseClass::PerformLayout();
if ( m_pMenuBar->IsVisible() )
{
int iWidth;
int iHeight;
GetSize( iWidth, iHeight );
int iMenuWidth; // Unused
int iMenuHeight;
m_pMenuBar->GetSize( iMenuWidth, iMenuHeight );
m_pMenuBar->SetSize( iWidth, iMenuHeight );
}
}
//-----------------------------------------------------------------------------
// paint it!
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::Paint()
{
if ( m_hCurrentAnimation.Get() )
{
DmeTime_t currentTime( Plat_FloatTime() - m_flStartTime );
if ( m_hCurrentAnimation->GetDuration() != DMETIME_ZERO )
{
currentTime = currentTime % m_hCurrentAnimation->GetDuration();
}
else
{
currentTime = DMETIME_ZERO;
}
currentTime += m_hCurrentAnimation->GetStartTime();
DmeTime_t mediaTime = m_hCurrentAnimation->ToChildMediaTime( currentTime, true );
int nChannelCount = m_hCurrentAnimation->m_Channels.Count();
for ( int i = 0; i < nChannelCount; ++i )
{
m_hCurrentAnimation->m_Channels[i]->SetCurrentTime( mediaTime );
}
}
if ( m_hCurrentVertexAnimation.Get() )
{
DmeTime_t currentTime( Plat_FloatTime() - m_flStartTime );
currentTime = currentTime % m_hCurrentVertexAnimation->GetDuration();
currentTime += m_hCurrentVertexAnimation->GetStartTime();
DmeTime_t mediaTime = m_hCurrentVertexAnimation->ToChildMediaTime( currentTime, true );
int nChannelCount = m_hCurrentVertexAnimation->m_Channels.Count();
for ( int i = 0; i < nChannelCount; ++i )
{
m_hCurrentVertexAnimation->m_Channels[i]->SetCurrentTime( mediaTime );
}
}
// FIXME: Shouldn't this happen at the application level?
// run the machinery - apply, resolve, dependencies, operate, resolve
{
CDisableUndoScopeGuard guard;
g_pDmElementFramework->SetOperators( m_operators );
g_pDmElementFramework->Operate( true );
}
// allow elements and attributes to be edited again
g_pDmElementFramework->BeginEdit();
BaseClass::Paint();
// Overlay the joint names
if ( m_bDrawJointNames && m_hDag )
{
matrix3x4_t modelToWorld;
if ( !m_bModelInEngineCoordinates )
{
CDmeDag::DmeToEngineMatrix( modelToWorld, m_bModelZUp );
}
DrawJointNames( m_hDag, m_hDag, modelToWorld );
}
DrawHighlightPoints();
}
//-----------------------------------------------------------------------------
// Indicate we should draw joint names
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawJointNames( bool bDrawJointNames )
{
m_bDrawJointNames = bDrawJointNames;
}
//-----------------------------------------------------------------------------
// Indicate we should draw joints
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawJoints( bool bDrawJoint )
{
m_bDrawJoints = bDrawJoint;
}
//-----------------------------------------------------------------------------
// Indicate we should draw the grid
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawGrid( bool bDrawGrid )
{
m_bDrawGrid = bDrawGrid;
}
//-----------------------------------------------------------------------------
// Indicate we should draw the coordinate axis
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::DrawAxis( bool bDrawAxis )
{
m_bDrawAxis = bDrawAxis;
}
//-----------------------------------------------------------------------------
// Indicate whether the model is in engine coordinates already
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::ModelInEngineCoordinates( bool bDrawInEngineCoordinates )
{
m_bModelInEngineCoordinates = bDrawInEngineCoordinates;
}
//-----------------------------------------------------------------------------
// Indicate whether the model is Z Up
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::ModelZUp( bool bDrawZUp )
{
m_bModelZUp = bDrawZUp;
}
//-----------------------------------------------------------------------------
// paint it!
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnPaint3D()
{
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
ITexture *pLocalCube = pRenderContext->GetLocalCubemap();
if ( g_pMaterialSystemHardwareConfig->GetHDRType() == HDR_TYPE_NONE )
{
pRenderContext->BindLocalCubemap( m_DefaultEnvCubemap );
}
else
{
pRenderContext->BindLocalCubemap( m_DefaultHDREnvCubemap );
}
if ( m_bDrawGrid )
{
BaseClass::DrawGrid();
}
if ( m_bDrawJoints )
{
CDmeJoint::DrawJointHierarchy( true );
}
pRenderContext->CullMode( MATERIAL_CULLMODE_CW );
CDmeDag::DrawUsingEngineCoordinates( !m_bModelInEngineCoordinates );
CDmeDag::DrawZUp( m_bModelZUp );
m_pDrawSettings->DrawDag( m_hDag );
CDmeDag::DrawUsingEngineCoordinates( false );
CDmeDag::DrawZUp( false );
if ( m_bDrawAxis )
{
DrawAxis();
}
pRenderContext->Flush();
pRenderContext->BindLocalCubemap( pLocalCube );
}
//-----------------------------------------------------------------------------
// For rendering joints
//-----------------------------------------------------------------------------
#define AXIS_SIZE 10.0f
void CDmeDagRenderPanel::DrawAxis( )
{
if ( !g_pMaterialSystem )
return;
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->Bind( m_axisMaterial );
IMesh *pMesh = pRenderContext->GetDynamicMesh( );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_LINES, 3 );
meshBuilder.Position3f( 0.0f, 0.0f, 0.0f );
meshBuilder.Color4ub( 255, 0, 0, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.Position3f( AXIS_SIZE, 0.0f, 0.0f );
meshBuilder.Color4ub( 255, 0, 0, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.Position3f( 0.0f, 0.0f, 0.0f );
meshBuilder.Color4ub( 0, 255, 0, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.Position3f( 0.0f, AXIS_SIZE, 0.0f );
meshBuilder.Color4ub( 0, 255, 0, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.Position3f( 0.0f, 0.0f, 0.0f );
meshBuilder.Color4ub( 0, 0, 255, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.Position3f( 0.0f, 0.0f, AXIS_SIZE );
meshBuilder.Color4ub( 0, 0, 255, 255 );
meshBuilder.AdvanceVertexF< VTX_HAVEPOS | VTX_HAVECOLOR, 0 >();
meshBuilder.End();
pMesh->Draw();
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->LoadIdentity();
}
//-----------------------------------------------------------------------------
// input
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnMouseDoublePressed( vgui::MouseCode code )
{
OnFrame();
BaseClass::OnMouseDoublePressed( code );
}
//-----------------------------------------------------------------------------
// TODO: Have a whole groovy keybinding thingy like SFM
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::OnKeyCodePressed( vgui::KeyCode code )
{
BaseClass::OnKeyCodePressed( code );
if ( code == KEY_F )
{
OnFrame();
}
}
//-----------------------------------------------------------------------------
// Rebuilds the list of operators
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::RebuildOperatorList( )
{
m_operators.RemoveAll();
if ( m_hCurrentAnimation.Get() )
{
int nChannelCount = m_hCurrentAnimation->m_Channels.Count();
for ( int i = 0; i < nChannelCount; ++i )
{
m_hCurrentAnimation->m_Channels[i]->SetMode( CM_PLAY );
m_operators.AddToTail( m_hCurrentAnimation->m_Channels[i] );
}
}
if ( m_hCurrentVertexAnimation.Get() )
{
int nChannelCount = m_hCurrentVertexAnimation->m_Channels.Count();
for ( int i = 0; i < nChannelCount; ++i )
{
m_hCurrentVertexAnimation->m_Channels[i]->SetMode( CM_PLAY );
m_operators.AddToTail( m_hCurrentVertexAnimation->m_Channels[i] );
}
}
m_flStartTime = Plat_FloatTime();
}
//-----------------------------------------------------------------------------
// Select animation by index
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::SelectAnimation( int nIndex )
{
m_hCurrentAnimation = NULL;
if ( m_hAnimationList.Get() && ( nIndex >= 0 ) )
{
// FIXME: How is this actually going to work?
m_hCurrentAnimation = m_hAnimationList->GetAnimation( nIndex );
}
RebuildOperatorList();
}
void CDmeDagRenderPanel::SelectVertexAnimation( int nIndex )
{
m_hCurrentVertexAnimation = NULL;
if ( m_hVertexAnimationList.Get() && ( nIndex >= 0 ) )
{
// FIXME: How is this actually going to work?
m_hCurrentVertexAnimation = m_hVertexAnimationList->GetAnimation( nIndex );
}
RebuildOperatorList();
}
//-----------------------------------------------------------------------------
// Select animation by name
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::SelectAnimation( const char *pAnimName )
{
if ( !pAnimName[0] )
{
SelectAnimation( -1 );
return;
}
if ( m_hAnimationList )
{
int nIndex = m_hAnimationList->FindAnimation( pAnimName );
if ( nIndex >= 0 )
{
SelectAnimation( nIndex );
}
}
}
void CDmeDagRenderPanel::SelectVertexAnimation( const char *pAnimName )
{
if ( !pAnimName[0] )
{
SelectVertexAnimation( -1 );
return;
}
if ( m_hVertexAnimationList )
{
int nIndex = m_hVertexAnimationList->FindAnimation( pAnimName );
if ( nIndex >= 0 )
{
SelectVertexAnimation( nIndex );
}
}
}
//-----------------------------------------------------------------------------
// Sets animation
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::SetAnimationList( CDmeAnimationList *pAnimationList )
{
m_hAnimationList = pAnimationList;
int nCount = pAnimationList ? pAnimationList->GetAnimationCount() : 0;
if ( nCount == 0 )
{
m_hCurrentAnimation = NULL;
return;
}
SelectAnimation( 0 );
}
void CDmeDagRenderPanel::SetVertexAnimationList( CDmeAnimationList *pAnimationList )
{
m_hVertexAnimationList = pAnimationList;
int nCount = pAnimationList ? pAnimationList->GetAnimationCount() : 0;
if ( nCount == 0 )
{
m_hCurrentVertexAnimation = NULL;
return;
}
SelectVertexAnimation( 0 );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDmeDagRenderPanel::UpdateMenu()
{
switch ( m_pDrawSettings->GetDrawType() )
{
case CDmeDrawSettings::DRAW_FLAT:
m_pShadingMenu->SetMenuItemChecked( m_nMenuSmoothShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuFlatShade, true );
m_pShadingMenu->SetMenuItemChecked( m_nMenuWireframe, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuBoundingBox, false );
break;
case CDmeDrawSettings::DRAW_WIREFRAME:
m_pShadingMenu->SetMenuItemChecked( m_nMenuSmoothShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuFlatShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuWireframe, true );
m_pShadingMenu->SetMenuItemChecked( m_nMenuBoundingBox, false );
break;
case CDmeDrawSettings::DRAW_BOUNDINGBOX:
m_pShadingMenu->SetMenuItemChecked( m_nMenuSmoothShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuFlatShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuWireframe, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuBoundingBox, true );
break;
default:
m_pShadingMenu->SetMenuItemChecked( m_nMenuSmoothShade, true );
m_pShadingMenu->SetMenuItemChecked( m_nMenuFlatShade, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuWireframe, false );
m_pShadingMenu->SetMenuItemChecked( m_nMenuBoundingBox, false );
break;
}
m_pShadingMenu->SetMenuItemChecked( m_nMenuNormals, m_pDrawSettings->GetNormals() );
m_pShadingMenu->SetMenuItemChecked( m_nMenuWireframeOnShaded, m_pDrawSettings->GetWireframeOnShaded() );
m_pShadingMenu->SetMenuItemChecked( m_nMenuBackfaceCulling, m_pDrawSettings->GetBackfaceCulling() );
m_pShadingMenu->SetMenuItemChecked( m_nMenuXRay, m_pDrawSettings->GetXRay() );
m_pShadingMenu->SetMenuItemChecked( m_nMenuGrayShade, m_pDrawSettings->GetGrayShade() );
}

View File

@@ -0,0 +1,542 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
//===========================================================================//
#include "dme_controls/dmelogeditpanel.h"
#include "movieobjects/dmelog.h"
#include "vgui_controls/button.h"
#include "vgui_controls/combobox.h"
#include "tier1/keyvalues.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CDmeLogEditPanel::CDmeLogEditPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
SetVisible( false );
m_flMinVertical = 0;
m_flMaxVertical = 256;
}
CDmeLogEditPanel::~CDmeLogEditPanel()
{
}
//-----------------------------------------------------------------------------
// Converts normalized values to int time
//-----------------------------------------------------------------------------
DmeTime_t CDmeLogEditPanel::NormalizedToTime( float flIn )
{
return m_minTime + NormalizedToDuration( flIn );
}
DmeTime_t CDmeLogEditPanel::NormalizedToDuration( float flDuration )
{
flDuration = clamp( flDuration, 0.0f, 1.0f );
return flDuration * ( m_maxTime - m_minTime );
}
float CDmeLogEditPanel::TimeToNormalized( DmeTime_t time )
{
if ( m_maxTime == m_minTime )
return 0.0f;
return GetFractionOfTimeBetween( time, m_minTime, m_maxTime, true );
}
float CDmeLogEditPanel::NormalizedToValue( float flValue )
{
return Lerp( flValue, m_flMinVertical, m_flMaxVertical );
}
float CDmeLogEditPanel::ValueToNormalized( float flNormalized )
{
if ( m_flMaxVertical == m_flMinVertical )
return 0.0f;
return (flNormalized - m_flMinVertical) / ( m_flMaxVertical - m_flMinVertical );
}
//-----------------------------------------------------------------------------
// Control points + values...
//-----------------------------------------------------------------------------
int CDmeLogEditPanel::FindOrAddControlPoint( float flIn, float flTolerance, float flOut )
{
Assert( m_hLog.Get() );
DmeTime_t time = NormalizedToTime( flIn );
DmeTime_t tolerance = ( flTolerance >= 0 ) ? NormalizedToDuration( flTolerance ) : DmeTime_t( 0 );
float flValue = NormalizedToValue( flOut );
int nKeyIndex = -1;
Assert( m_hLog.Get() );
switch( m_hLog->GetDataType() )
{
case AT_BOOL:
nKeyIndex = CastElement<CDmeBoolLog >( m_hLog )->FindOrAddKey( time, tolerance, (bool)(flValue >= 0.5f) );
break;
case AT_INT:
nKeyIndex = CastElement<CDmeIntLog >( m_hLog )->FindOrAddKey( time, tolerance, (int)(flValue + 0.5f) );
break;
case AT_FLOAT:
nKeyIndex = CastElement<CDmeFloatLog >( m_hLog )->FindOrAddKey( time, tolerance, flValue );
break;
case AT_COLOR:
{
Color c = CastElement<CDmeColorLog >( m_hLog )->GetValue( time );
int nComp = (int)( flValue + 0.5f );
nComp = clamp( nComp, 0, 255 );
for ( int i = 0; i < 4; ++i )
{
if ( m_LogFieldMask & (1 << i) )
{
c[i] = (unsigned char)nComp;
}
}
nKeyIndex = CastElement<CDmeColorLog >( m_hLog )->FindOrAddKey( time, tolerance, c );
}
break;
case AT_VECTOR2:
nKeyIndex = FindOrAddKey< Vector2D >( time, tolerance, 2, flValue );
break;
case AT_VECTOR3:
nKeyIndex = FindOrAddKey< Vector >( time, tolerance, 3, flValue );
break;
case AT_VECTOR4:
nKeyIndex = FindOrAddKey< Vector4D >( time, tolerance, 4, flValue );
break;
case AT_QANGLE:
nKeyIndex = FindOrAddKey< QAngle >( time, tolerance, 3, flValue );
break;
case AT_QUATERNION:
nKeyIndex = FindOrAddKey< Quaternion >( time, tolerance, 4, flValue );
break;
}
return nKeyIndex;
}
//-----------------------------------------------------------------------------
// Finds a control point within tolerance
//-----------------------------------------------------------------------------
int CDmeLogEditPanel::FindControlPoint( float flIn, float flTolerance )
{
Assert( m_hLog.Get() );
DmeTime_t time = NormalizedToTime( flIn );
DmeTime_t tolerance = NormalizedToDuration( flTolerance );
return m_hLog->FindKeyWithinTolerance( time, tolerance );
}
//-----------------------------------------------------------------------------
// Modifies an existing control point
//-----------------------------------------------------------------------------
int CDmeLogEditPanel::ModifyControlPoint( int nPoint, float flIn, float flOut )
{
Assert( m_hLog.Get() );
DmeTime_t time = NormalizedToTime( flIn );
DmeTime_t initialTime = m_hLog->GetKeyTime( nPoint );
float flValue = NormalizedToValue( flOut );
int nKeyIndex = -1;
Assert( m_hLog.Get() );
switch( m_hLog->GetDataType() )
{
case AT_BOOL:
RemoveControlPoint( nPoint );
nKeyIndex = CastElement<CDmeBoolLog >( m_hLog )->FindOrAddKey( time, DmeTime_t( 0 ), (bool)(flValue >= 0.5f) );
break;
case AT_INT:
RemoveControlPoint( nPoint );
nKeyIndex = CastElement<CDmeIntLog >( m_hLog )->FindOrAddKey( time, DmeTime_t( 0 ), (int)(flValue + 0.5f) );
break;
case AT_FLOAT:
RemoveControlPoint( nPoint );
nKeyIndex = CastElement<CDmeFloatLog >( m_hLog )->FindOrAddKey( time, DmeTime_t( 0 ), flValue );
break;
case AT_COLOR:
{
Color c = CastElement<CDmeColorLog >( m_hLog )->GetValue( initialTime );
int nComp = (int)( flValue + 0.5f );
nComp = clamp( nComp, 0, 255 );
for ( int i = 0; i < 4; ++i )
{
if ( m_LogFieldMask & (1 << i) )
{
c[i] = (unsigned char)nComp;
}
}
RemoveControlPoint( nPoint );
nKeyIndex = CastElement<CDmeColorLog >( m_hLog )->FindOrAddKey( time, DmeTime_t( 0 ), c );
}
break;
case AT_VECTOR2:
nKeyIndex = ModifyKey< Vector2D >( nPoint, initialTime, time, 2, flValue );
break;
case AT_VECTOR3:
nKeyIndex = ModifyKey< Vector >( nPoint, initialTime, time, 3, flValue );
break;
case AT_VECTOR4:
nKeyIndex = ModifyKey< Vector4D >( nPoint, initialTime, time, 4, flValue );
break;
case AT_QANGLE:
nKeyIndex = ModifyKey< QAngle >( nPoint, initialTime, time, 3, flValue );
break;
case AT_QUATERNION:
nKeyIndex = ModifyKey< Quaternion >( nPoint, initialTime, time, 4, flValue );
break;
}
return nKeyIndex;
}
//-----------------------------------------------------------------------------
// Removes a single control point
//-----------------------------------------------------------------------------
void CDmeLogEditPanel::RemoveControlPoint( int nPoint )
{
Assert( m_hLog.Get() );
m_hLog->RemoveKey( nPoint );
}
//-----------------------------------------------------------------------------
// Gets the interpolated value of the log based on normalized time
//-----------------------------------------------------------------------------
float CDmeLogEditPanel::GetValue( float flIn )
{
DmeTime_t time = NormalizedToTime( flIn );
float flValue = 0.0f;
Assert( m_hLog.Get() );
switch( m_hLog->GetDataType() )
{
case AT_BOOL:
flValue = CastElement<CDmeBoolLog >( m_hLog )->GetValue( time );
break;
case AT_INT:
flValue = CastElement<CDmeIntLog >( m_hLog )->GetValue( time );
break;
case AT_FLOAT:
flValue = CastElement<CDmeFloatLog >( m_hLog )->GetValue( time );
break;
case AT_COLOR:
{
Color c = CastElement<CDmeColorLog >( m_hLog )->GetValue( time );
flValue = c[m_nFieldIndex];
}
break;
case AT_VECTOR2:
flValue = CastElement<CDmeVector2Log >( m_hLog )->GetValue( time )[m_nFieldIndex];
break;
case AT_VECTOR3:
flValue = CastElement<CDmeVector3Log >( m_hLog )->GetValue( time )[m_nFieldIndex];
break;
case AT_VECTOR4:
flValue = CastElement<CDmeVector2Log >( m_hLog )->GetValue( time )[m_nFieldIndex];
break;
case AT_QANGLE:
flValue = CastElement<CDmeQAngleLog >( m_hLog )->GetValue( time )[m_nFieldIndex];
break;
case AT_QUATERNION:
flValue = CastElement<CDmeQuaternionLog >( m_hLog )->GetValue( time )[m_nFieldIndex];
break;
}
return ValueToNormalized( flValue );
}
int CDmeLogEditPanel::ControlPointCount()
{
Assert( m_hLog.Get() );
return m_hLog->GetKeyCount( );
}
//-----------------------------------------------------------------------------
// Gets a particular control point's value
//-----------------------------------------------------------------------------
void CDmeLogEditPanel::GetControlPoint( int nPoint, float *pIn, float *pOut )
{
Assert( m_hLog.Get() );
DmeTime_t time = m_hLog->GetKeyTime( nPoint );
*pIn = TimeToNormalized( time );
float flValue = 0.0f;
Assert( m_hLog.Get() );
switch( m_hLog->GetDataType() )
{
case AT_BOOL:
flValue = CastElement<CDmeBoolLog >( m_hLog )->GetKeyValue( nPoint );
break;
case AT_INT:
flValue = CastElement<CDmeIntLog >( m_hLog )->GetKeyValue( nPoint );
break;
case AT_FLOAT:
flValue = CastElement<CDmeFloatLog >( m_hLog )->GetKeyValue( nPoint );
break;
case AT_COLOR:
{
Color c = CastElement<CDmeColorLog >( m_hLog )->GetKeyValue( nPoint );
flValue = c[m_nFieldIndex];
}
break;
case AT_VECTOR2:
flValue = CastElement<CDmeVector2Log >( m_hLog )->GetKeyValue( nPoint )[m_nFieldIndex];
break;
case AT_VECTOR3:
flValue = CastElement<CDmeVector3Log >( m_hLog )->GetKeyValue( nPoint )[m_nFieldIndex];
break;
case AT_VECTOR4:
flValue = CastElement<CDmeVector2Log >( m_hLog )->GetKeyValue( nPoint )[m_nFieldIndex];
break;
case AT_QANGLE:
flValue = CastElement<CDmeQAngleLog >( m_hLog )->GetKeyValue( nPoint )[m_nFieldIndex];
break;
case AT_QUATERNION:
flValue = CastElement<CDmeQuaternionLog >( m_hLog )->GetKeyValue( nPoint )[m_nFieldIndex];
break;
}
*pOut = ValueToNormalized( flValue );
}
//-----------------------------------------------------------------------------
// Sets the log to edit
//-----------------------------------------------------------------------------
void CDmeLogEditPanel::SetDmeLog( CDmeLog *pLog )
{
bool bValid = pLog && ( pLog->GetDataType() == AT_INT || pLog->GetDataType() == AT_FLOAT || pLog->GetDataType() == AT_COLOR );
if ( bValid )
{
m_hLog = pLog;
}
else
{
m_minTime.SetSeconds( 0.0f );
m_maxTime.SetSeconds( 0.0f );
}
SetVisible( bValid );
}
void CDmeLogEditPanel::SetMask( int nMask )
{
m_LogFieldMask = nMask;
m_nFieldIndex = 0;
for ( int i = 0; i < 4; ++i )
{
if ( m_LogFieldMask & (1 << i) )
{
m_nFieldIndex = i;
break;
}
}
}
//-----------------------------------------------------------------------------
// Sets the time range on the view in ms
//-----------------------------------------------------------------------------
void CDmeLogEditPanel::SetTimeRange( DmeTime_t startTime, DmeTime_t endTime )
{
m_minTime = startTime;
m_maxTime = endTime;
}
//-----------------------------------------------------------------------------
// Sets the vertical range on the view
//-----------------------------------------------------------------------------
void CDmeLogEditPanel::SetVerticalRange( float flMin, float flMax )
{
m_flMinVertical = flMin;
m_flMaxVertical = flMax;
}
//-----------------------------------------------------------------------------
//
// Purpose: Modal picker frame
//
//-----------------------------------------------------------------------------
CDmeLogEditFrame::CDmeLogEditFrame( vgui::Panel *pParent, const char *pTitle ) :
BaseClass( pParent, "DmeLogEditFrame" )
{
m_pContextKeyValues = NULL;
SetDeleteSelfOnClose( true );
m_pCurveEditor = new CDmeLogEditPanel( this, "DmeLogEditPanel" );
m_pOkButton = new Button( this, "OkButton", "#GameUI_OK", this, "Ok" );
m_pCancelButton = new Button( this, "CancelButton", "#GameUI_Cancel", this, "Cancel" );
m_pFilter = new ComboBox( this, "LogFilter", 5, false );
SetBlockDragChaining( true );
LoadControlSettingsAndUserConfig( "resource/dmelogeditframe.res" );
SetTitle( pTitle, false );
}
CDmeLogEditFrame::~CDmeLogEditFrame()
{
CleanUpMessage();
}
//-----------------------------------------------------------------------------
// Deletes the message
//-----------------------------------------------------------------------------
void CDmeLogEditFrame::CleanUpMessage()
{
if ( m_pContextKeyValues )
{
m_pContextKeyValues->deleteThis();
m_pContextKeyValues = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when the combo box changes
//-----------------------------------------------------------------------------
void CDmeLogEditFrame::OnTextChanged( )
{
KeyValues *pKeyValues = m_pFilter->GetActiveItemUserData();
int nMask = pKeyValues->GetInt( "Value", CDmeLogEditPanel::FIELD_ALL );
m_pCurveEditor->SetMask( nMask );
}
//-----------------------------------------------------------------------------
// Purpose: Activate the dialog
//-----------------------------------------------------------------------------
void CDmeLogEditFrame::DoModal( CDmeLog *pLog, DmeTime_t startTime, DmeTime_t endTime, KeyValues *pKeyValues )
{
CleanUpMessage();
m_pContextKeyValues = pKeyValues;
m_pCurveEditor->SetDmeLog( pLog );
m_pCurveEditor->SetTimeRange( startTime, endTime );
m_pFilter->SetVisible( true );
m_pFilter->RemoveAll();
switch( pLog->GetDataType() )
{
case AT_BOOL:
case AT_INT:
case AT_FLOAT:
m_pFilter->SetVisible( false );
break;
case AT_COLOR:
m_pFilter->AddItem( "RGB Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_R | CDmeLogEditPanel::FIELD_G | CDmeLogEditPanel::FIELD_B ) );
m_pFilter->AddItem( "Red Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_R ) );
m_pFilter->AddItem( "Green Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_G ) );
m_pFilter->AddItem( "Blue Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_B ) );
m_pFilter->AddItem( "Alpha Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_A ) );
break;
case AT_VECTOR2:
m_pFilter->AddItem( "X Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_X ) );
m_pFilter->AddItem( "Y Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_Y ) );
break;
case AT_VECTOR3:
case AT_QANGLE:
m_pFilter->AddItem( "X Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_X ) );
m_pFilter->AddItem( "Y Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_Y ) );
m_pFilter->AddItem( "Z Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_Z ) );
break;
case AT_VECTOR4:
case AT_QUATERNION:
m_pFilter->AddItem( "X Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_X ) );
m_pFilter->AddItem( "Y Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_Y ) );
m_pFilter->AddItem( "Z Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_Z ) );
m_pFilter->AddItem( "W Channel", new KeyValues( "Mask", "Value", CDmeLogEditPanel::FIELD_W ) );
break;
}
if ( m_pFilter->IsVisible() )
{
// Will cause the mask to be set
m_pFilter->ActivateItemByRow( 0 );
}
else
{
m_pCurveEditor->SetMask( CDmeLogEditPanel::FIELD_ALL );
}
BaseClass::DoModal();
}
//-----------------------------------------------------------------------------
// On command
//-----------------------------------------------------------------------------
void CDmeLogEditFrame::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "Ok" ) )
{
KeyValues *pActionKeys = new KeyValues( "LogEdited" );
if ( m_pContextKeyValues )
{
pActionKeys->AddSubKey( m_pContextKeyValues );
// This prevents them from being deleted later
m_pContextKeyValues = NULL;
}
PostActionSignal( pActionKeys );
CloseModal();
return;
}
if ( !Q_stricmp( pCommand, "Cancel" ) )
{
CloseModal();
return;
}
BaseClass::OnCommand( pCommand );
}

View File

@@ -0,0 +1,47 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/dmemdlpanel.h"
#include "dme_controls/dmecontrols.h"
#include "dme_controls/dmepanel.h"
#include "movieobjects/dmemdl.h"
#include "movieobjects/dmemdlmakefile.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
IMPLEMENT_DMEPANEL_FACTORY( CDmeMDLPanel, DmeMDLMakefile, "DmeMakeFileOutputPreview", "MDL MakeFile Output Preview", false );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CDmeMDLPanel::CDmeMDLPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
}
CDmeMDLPanel::~CDmeMDLPanel()
{
}
//-----------------------------------------------------------------------------
// DMEPanel..
//-----------------------------------------------------------------------------
void CDmeMDLPanel::SetDmeElement( CDmeMDLMakefile *pMDLMakefile )
{
if ( pMDLMakefile != NULL )
{
CDmeMDL *pMDL = CastElement< CDmeMDL >( pMDLMakefile->GetOutputElement( true ) );
if ( pMDL )
{
SetMDL( pMDL->GetMDL() );
}
}
}

View File

@@ -0,0 +1,656 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/dmepanel.h"
#include "tier1/keyvalues.h"
#include "dme_controls/dmecontrols.h"
#include "vgui_controls/combobox.h"
#include "datamodel/dmelement.h"
#include "dme_controls/dmecontrols_utils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// All DmePanels used by the system must be listed here to link them in
//-----------------------------------------------------------------------------
USING_DMEPANEL_FACTORY( CDmeElementPanel, DmElement );
USING_DMEPANEL_FACTORY( CDmeSourceSkinPanel, DmeSourceSkin );
USING_DMEPANEL_FACTORY( CAssetBuilder, DmeMakefile );
USING_DMEPANEL_FACTORY( CDmeSourceDCCFilePanel, DmeSourceDCCFile );
USING_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeDag );
USING_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeSourceAnimation );
USING_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeSourceSkin );
USING_DMEPANEL_FACTORY( CDmeDagRenderPanel, DmeDCCMakefile );
USING_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeDag );
USING_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeSourceAnimation );
USING_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeSourceSkin );
USING_DMEPANEL_FACTORY( CDmeDagEditPanel, DmeDCCMakefile );
USING_DMEPANEL_FACTORY( CDmeMDLPanel, DmeMDLMakefile );
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CDmePanel::CDmePanel( vgui::Panel *pParent, const char *pPanelName, bool bComboBoxVisible ) :
BaseClass( pParent, pPanelName )
{
m_pEditorNames = new vgui::ComboBox( this, "EditorDisplayNames", 6, false );
if ( bComboBoxVisible )
{
m_pEditorNames->AddActionSignalTarget( this );
}
else
{
m_pEditorNames->SetVisible( false );
}
m_pDmeEditorPanel = NULL;
m_hElement = NULL;
SetDropEnabled( true );
}
CDmePanel::~CDmePanel()
{
DeleteCachedPanels();
}
//-----------------------------------------------------------------------------
// Scheme
//-----------------------------------------------------------------------------
void CDmePanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
m_pEditorNames->SetFont( pScheme->GetFont( "DefaultVerySmall" ) );
}
//-----------------------------------------------------------------------------
// Layout
//-----------------------------------------------------------------------------
void CDmePanel::PerformLayout()
{
BaseClass::PerformLayout();
int w, h;
GetSize( w, h );
if ( m_pEditorNames->IsVisible() )
{
m_pEditorNames->SetBounds( 1, 1, w-2, 20 );
if ( m_pDmeEditorPanel )
{
m_pDmeEditorPanel->SetBounds( 0, 24, w, h-24 );
}
}
else
{
if ( m_pDmeEditorPanel )
{
m_pDmeEditorPanel->SetBounds( 0, 0, w, h );
}
}
}
//-----------------------------------------------------------------------------
// Drag/drop
//-----------------------------------------------------------------------------
bool CDmePanel::IsDroppable( CUtlVector< KeyValues * >& msglist )
{
if ( msglist.Count() != 1 )
return false;
KeyValues *data = msglist[ 0 ];
CDmElement *ptr = GetElementKeyValue<CDmElement>( data, "dmeelement" );
if ( !ptr )
return false;
if ( ptr == m_hElement.Get() )
return false;
return true;
}
void CDmePanel::OnPanelDropped( CUtlVector< KeyValues * >& msglist )
{
if ( msglist.Count() != 1 )
return;
KeyValues *data = msglist[ 0 ];
CDmElement *ptr = GetElementKeyValue<CDmElement>( data, "dmeelement" );
if ( !ptr )
return;
// Already browsing
if ( ptr == m_hElement.Get() )
return;
SetDmeElement( ptr );
}
//-----------------------------------------------------------------------------
// Sets the default editor type
//-----------------------------------------------------------------------------
void CDmePanel::SetDefaultEditorType( const char *pEditorType )
{
m_DefaultEditorType = pEditorType;
}
//-----------------------------------------------------------------------------
// Populate editor name combo box
//-----------------------------------------------------------------------------
void CDmePanel::PopulateEditorNames( const char *pPanelName )
{
m_pEditorNames->RemoveAll();
m_pEditorNames->SetText( "" );
if ( !m_pEditorNames->IsVisible() )
{
SetEditor( pPanelName );
return;
}
if ( !m_hElement.Get() )
{
OnTextChanged();
return;
}
const char *pPreferredEditor = NULL;
if ( m_LastUsedEditorType.Defined( m_hElement->GetTypeString() ) )
{
pPreferredEditor = m_LastUsedEditorType[ m_hElement->GetTypeString() ].Get();
}
else
{
pPreferredEditor = m_DefaultEditorType;
}
int nBestInheritanceDepth = -1;
int nActiveItemID = -1;
bool bFoundPanelName = false;
DmeFactoryHandle_t h = DmePanelFirstFactory( m_hElement.Get() );
for ( ; h != DMEFACTORY_HANDLE_INVALID; h = DmePanelNextFactory( h, m_hElement.Get() ) )
{
const char *pDisplayName = DmePanelFactoryDisplayName( h );
const char *pEditorName = DmePanelFactoryName( h );
KeyValues *pKeyValues = new KeyValues( "entry", "editorName", pEditorName );
int nItemID = m_pEditorNames->AddItem( pDisplayName, pKeyValues );
if ( pPanelName && !Q_stricmp( pPanelName, pEditorName ) )
{
nBestInheritanceDepth = 0;
nActiveItemID = nItemID;
bFoundPanelName = true;
continue;
}
if ( pPreferredEditor && !bFoundPanelName && !Q_stricmp( pPreferredEditor, pEditorName ) )
{
nBestInheritanceDepth = 0;
nActiveItemID = nItemID;
continue;
}
// Don't select this as the default if it's not a default factory
if ( !DmePanelFactoryIsDefault(h) )
continue;
// Choose this factory if it's more derived than the previous best
const char *pElementType = DmePanelFactoryElementType( h );
int nInheritanceDepth = m_hElement->GetInheritanceDepth( pElementType );
Assert( nInheritanceDepth >= 0 );
if ( nBestInheritanceDepth >= 0 && ( nInheritanceDepth >= nBestInheritanceDepth ) )
continue;
nBestInheritanceDepth = nInheritanceDepth;
nActiveItemID = nItemID;
}
if ( m_pEditorNames->GetItemCount() == 0 )
{
// ItemCount == 0;
m_pEditorNames->SetText( "" );
m_CurrentEditorName = NULL;
OnTextChanged();
return;
}
if ( nActiveItemID >= 0 )
{
m_pEditorNames->ActivateItem( nActiveItemID );
}
else
{
m_pEditorNames->ActivateItemByRow( 0 );
}
}
//-----------------------------------------------------------------------------
// Called when the dme element was changed
//-----------------------------------------------------------------------------
void CDmePanel::OnDmeElementChanged()
{
PostActionSignal( new KeyValues( "DmeElementChanged" ) );
}
//-----------------------------------------------------------------------------
// Context menu support
//-----------------------------------------------------------------------------
void CDmePanel::OnOpenContextMenu( KeyValues *params )
{
// Forward the context menu message to the DME panel
KeyValues *pMsg = params->MakeCopy();
if ( m_pDmeEditorPanel )
{
PostMessage( m_pDmeEditorPanel->GetVPanel(), pMsg );
}
}
//-----------------------------------------------------------------------------
// Copy/paste support
//-----------------------------------------------------------------------------
void CDmePanel::PostMessageToDmePanel( const char *pMessage )
{
if ( m_pDmeEditorPanel )
{
PostMessage( m_pDmeEditorPanel->GetVPanel(), new KeyValues( pMessage ) );
}
}
void CDmePanel::OnCut()
{
PostMessageToDmePanel( "OnCut" );
}
void CDmePanel::OnCopy()
{
PostMessageToDmePanel( "OnCopy" );
}
void CDmePanel::OnPaste()
{
PostMessageToDmePanel( "OnPaste" );
}
void CDmePanel::OnPasteInsert()
{
PostMessageToDmePanel( "OnPasteInsert" );
}
void CDmePanel::OnPasteReference()
{
PostMessageToDmePanel( "OnPasteReference" );
}
void CDmePanel::OnEditDelete()
{
PostMessageToDmePanel( "OnEditDelete" );
}
//-----------------------------------------------------------------------------
// Called when a child of the dme panel switches the thing it's looking at
//-----------------------------------------------------------------------------
void CDmePanel::OnViewedElementChanged( KeyValues *kv )
{
// This is kind of tricky. It's called by the element properties tree
// when doing the back/forward searching. Just calling the normal SetDmeElement
// doesn't work because it reorders the history. What we want is to
// populate the combo box without causing the OnTextChanged message to get sent.
// FIXME: Perhaps it would be better to extract the back/forward/search
// out of the element properties tree and put it into the dme panel?
CDmElement *pElement = GetElementKeyValue<CDmElement>( kv, "dmeelement" );
if ( pElement == m_hElement )
return;
// If the current editor isn't supported by this new element, then just reset. Too bad.
bool bFound = false;
if ( m_CurrentEditorName.Length() && pElement )
{
DmeFactoryHandle_t h = DmePanelFirstFactory( pElement );
for ( ; h != DMEFACTORY_HANDLE_INVALID; h = DmePanelNextFactory( h, pElement ) )
{
const char *pEditorName = DmePanelFactoryName( h );
if ( !Q_stricmp( m_CurrentEditorName, pEditorName ) )
{
bFound = true;
break;
}
}
}
if ( !bFound )
{
SetDmeElement( pElement );
return;
}
// Remove obsolete items
int nCount = m_pEditorNames->GetItemCount();
while ( --nCount >= 0 )
{
int nItemID = m_pEditorNames->GetItemIDFromRow( nCount );
KeyValues *kv = m_pEditorNames->GetItemUserData( nItemID );
if ( Q_stricmp( m_CurrentEditorName, kv->GetString( "editorName" ) ) )
{
m_pEditorNames->DeleteItem( nItemID );
}
}
// Just want to populate the combo box with new items
DmeFactoryHandle_t h = DmePanelFirstFactory( pElement );
for ( ; h != DMEFACTORY_HANDLE_INVALID; h = DmePanelNextFactory( h, pElement ) )
{
const char *pEditorName = DmePanelFactoryName( h );
if ( Q_stricmp( pEditorName, m_CurrentEditorName ) )
{
const char *pDisplayName = DmePanelFactoryDisplayName( h );
KeyValues *pKeyValues = new KeyValues( "entry", "editorName", pEditorName );
m_pEditorNames->AddItem( pDisplayName, pKeyValues );
}
}
m_hElement = pElement;
}
//-----------------------------------------------------------------------------
// Delete cached panels
//-----------------------------------------------------------------------------
void CDmePanel::DeleteCachedPanels()
{
int nCount = m_EditorPanelCache.GetNumStrings();
for ( int i = 0; i < nCount; ++i )
{
int nEditorCount = m_EditorPanelCache[ i ].Count();
for ( int j = 0; j < nEditorCount; ++j )
{
m_EditorPanelCache[ i ][ j ].m_pEditorPanel->MarkForDeletion();
}
}
m_EditorPanelCache.Clear();
}
//-----------------------------------------------------------------------------
// Refreshes the current panel owing to external change
// Values only means no topological change
//-----------------------------------------------------------------------------
void CDmePanel::Refresh( bool bValuesOnly )
{
if ( m_pDmeEditorPanel )
{
KeyValues *pKeyValues = new KeyValues( "ElementChangedExternally", "valuesOnly", bValuesOnly );
PostMessage( m_pDmeEditorPanel, pKeyValues );
}
}
//-----------------------------------------------------------------------------
// Deactivates the current editor
//-----------------------------------------------------------------------------
void CDmePanel::DeactivateCurrentEditor()
{
if ( m_pDmeEditorPanel )
{
m_pDmeEditorPanel->SetParent( (vgui::Panel*)NULL );
m_pDmeEditorPanel = NULL;
m_CurrentEditorName = NULL;
}
}
//-----------------------------------------------------------------------------
// Switch to a new editor
//-----------------------------------------------------------------------------
void CDmePanel::SetEditor( const char *pEditorName )
{
if ( pEditorName && !Q_stricmp( m_CurrentEditorName, pEditorName ) )
return;
DeactivateCurrentEditor();
if ( !m_hElement.Get() || !pEditorName )
return;
if ( m_EditorPanelCache.Defined( pEditorName ) )
{
CUtlVector< EditorPanelMap_t > &entries = m_EditorPanelCache[ pEditorName ];
int nCount = entries.Count();
for ( int i = 0; i < nCount; ++i )
{
EditorPanelMap_t &entry = entries[i];
if ( !m_hElement->IsA( entry.m_pFactory->m_pElementType ) )
continue;
m_pDmeEditorPanel = entry.m_pEditorPanel;
m_pDmeEditorPanel->SetParent( this );
entry.m_pFactory->SetDmeElement( m_pDmeEditorPanel, m_hElement );
break;
}
}
if ( !m_pDmeEditorPanel )
{
EditorPanelMap_t entry;
if ( CreateDmePanel( this, "DmePanelEditor", m_hElement, pEditorName, &entry ) )
{
m_EditorPanelCache[ pEditorName ].AddToTail( entry );
m_pDmeEditorPanel = entry.m_pEditorPanel;
}
}
if ( m_pDmeEditorPanel )
{
// Store the last selected type of editor
m_LastUsedEditorType[ m_hElement->GetTypeString() ] = pEditorName;
m_CurrentEditorName = pEditorName;
m_pDmeEditorPanel->AddActionSignalTarget( this );
}
InvalidateLayout();
}
//-----------------------------------------------------------------------------
// Called when a new element in the combo box has been selected
//-----------------------------------------------------------------------------
void CDmePanel::OnTextChanged()
{
KeyValues *kv = m_pEditorNames->GetActiveItemUserData();
const char *pEditorName = kv ? kv->GetString( "editorName", NULL ) : NULL;
SetEditor( pEditorName );
}
//-----------------------------------------------------------------------------
// Setting a new element
//-----------------------------------------------------------------------------
void CDmePanel::SetDmeElement( CDmElement *pDmeElement, bool bForce, const char *pPanelName )
{
if ( ( m_hElement == pDmeElement ) && !bForce )
{
if ( !pPanelName || !Q_stricmp( pPanelName, m_CurrentEditorName.Get() ) )
return;
}
m_hElement = pDmeElement;
m_CurrentEditorName = NULL;
// Populate the editor type list
PopulateEditorNames( pPanelName );
}
//-----------------------------------------------------------------------------
// Statics for the panel factory
//-----------------------------------------------------------------------------
CBaseDmePanelFactory* CBaseDmePanelFactory::s_pFirstDmePanelFactory;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CBaseDmePanelFactory::CBaseDmePanelFactory( const char *pElementType, const char *pEditorName,
const char *pEditorDisplayName, bool bIsDefault, bool bIsOverride )
{
// Prior to linking this in, look to see if this has been overridden
CBaseDmePanelFactory *pPrevFactory = NULL;
for( CBaseDmePanelFactory* pFactory = s_pFirstDmePanelFactory; pFactory;
pPrevFactory = pFactory, pFactory = pFactory->m_pNext )
{
if ( !Q_stricmp( pFactory->m_pElementType, pElementType ) &&
!Q_stricmp( pFactory->m_pEditorDisplayName, pEditorDisplayName ) )
{
// Collision found! If this is not an override, then we've been overridden
if ( !bIsOverride )
{
AssertMsg( pFactory->m_bIsOverride, ( "Two DmePanel factories have the same name (\"%s\") + type (\"%s\")!\n", pElementType, pEditorName ) );
return;
}
// If this *is* an override, replace the previous version
AssertMsg( !pFactory->m_bIsOverride, ( "Two DmePanel factories have the same name (\"%s\") + type (\"%s\")!\n", pElementType, pEditorName ) );
if ( pPrevFactory )
{
pPrevFactory->m_pNext = pFactory->m_pNext;
}
else
{
s_pFirstDmePanelFactory = pFactory->m_pNext;
}
break;
}
}
m_pNext = s_pFirstDmePanelFactory;
s_pFirstDmePanelFactory = this;
m_pElementType = pElementType;
m_pEditorName = pEditorName;
m_pEditorDisplayName = pEditorDisplayName;
m_bIsDefault = bIsDefault;
m_bIsOverride = bIsOverride;
}
//-----------------------------------------------------------------------------
// Dme Panel factory iteration methods
//-----------------------------------------------------------------------------
DmeFactoryHandle_t DmePanelFirstFactory( CDmElement *pElement )
{
CBaseDmePanelFactory *pFactory = CBaseDmePanelFactory::s_pFirstDmePanelFactory;
for ( ; pFactory; pFactory = pFactory->m_pNext )
{
if ( !pElement || pElement->IsA( pFactory->m_pElementType ) )
return (DmeFactoryHandle_t)pFactory;
}
return DMEFACTORY_HANDLE_INVALID;
}
DmeFactoryHandle_t DmePanelNextFactory( DmeFactoryHandle_t h, CDmElement *pElement )
{
CBaseDmePanelFactory *pFactory = (CBaseDmePanelFactory*)h;
if ( !pFactory )
return DMEFACTORY_HANDLE_INVALID;
for ( pFactory = pFactory->m_pNext; pFactory; pFactory = pFactory->m_pNext )
{
if ( !pElement || pElement->IsA( pFactory->m_pElementType ) )
return (DmeFactoryHandle_t)pFactory;
}
return DMEFACTORY_HANDLE_INVALID;
}
//-----------------------------------------------------------------------------
// Dme Panel factory info methods
//-----------------------------------------------------------------------------
const char *DmePanelFactoryName( DmeFactoryHandle_t h )
{
CBaseDmePanelFactory *pFactory = (CBaseDmePanelFactory*)h;
return pFactory ? pFactory->m_pEditorName : NULL;
}
const char *DmePanelFactoryDisplayName( DmeFactoryHandle_t h )
{
CBaseDmePanelFactory *pFactory = (CBaseDmePanelFactory*)h;
return pFactory ? pFactory->m_pEditorDisplayName : NULL;
}
const char *DmePanelFactoryElementType( DmeFactoryHandle_t h )
{
CBaseDmePanelFactory *pFactory = (CBaseDmePanelFactory*)h;
return pFactory ? pFactory->m_pElementType : NULL;
}
bool DmePanelFactoryIsDefault( DmeFactoryHandle_t h )
{
CBaseDmePanelFactory *pFactory = (CBaseDmePanelFactory*)h;
return pFactory ? pFactory->m_bIsDefault : false;
}
//-----------------------------------------------------------------------------
// Dme Panel factory methods
//-----------------------------------------------------------------------------
bool CDmePanel::CreateDmePanel( vgui::Panel *pParent, const char *pPanelName, CDmElement *pElement, const char *pEditorName, EditorPanelMap_t *pMap )
{
int nBestInheritanceDepth = -1;
CBaseDmePanelFactory *pBestFactory = NULL;
CBaseDmePanelFactory *pFactory = CBaseDmePanelFactory::s_pFirstDmePanelFactory;
for ( ; pFactory; pFactory = pFactory->m_pNext )
{
if ( !pElement->IsA( pFactory->m_pElementType ) )
continue;
if ( pEditorName )
{
if ( !Q_stricmp( pEditorName, pFactory->m_pEditorName ) )
{
pBestFactory = pFactory;
break;
}
continue;
}
// No editor name specified? Only use default factories
if ( !pFactory->m_bIsDefault )
continue;
// Choose this factory if it's more derived than the previous best
int nInheritanceDepth = pElement->GetInheritanceDepth( pFactory->m_pElementType );
Assert( nInheritanceDepth >= 0 );
if ( nBestInheritanceDepth >= 0 && ( nInheritanceDepth > nBestInheritanceDepth ) )
continue;
nBestInheritanceDepth = nInheritanceDepth;
pBestFactory = pFactory;
}
if ( pBestFactory )
{
pMap->m_pFactory = pBestFactory;
pMap->m_pEditorPanel = pBestFactory->CreateDmePanel( pParent, pPanelName, pElement );
return true;
}
return false;
}

View File

@@ -0,0 +1,280 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/DmePicker.h"
#include "tier1/keyvalues.h"
#include "vgui_controls/TextEntry.h"
#include "vgui_controls/ListPanel.h"
#include "vgui_controls/Button.h"
#include "datamodel/dmelement.h"
#include "vgui/isurface.h"
#include "vgui/iinput.h"
#include "dme_controls/dmecontrols_utils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Dme Picker
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Sort by MDL name
//-----------------------------------------------------------------------------
static int __cdecl DmeBrowserSortFunc( vgui::ListPanel *pPanel, const ListPanelItem &item1, const ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString("dme");
const char *string2 = item2.kv->GetString("dme");
return stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CDmePicker::CDmePicker( vgui::Panel *pParent ) : BaseClass( pParent, "DmePicker" )
{
// FIXME: Make this an image browser
m_pDmeBrowser = new vgui::ListPanel( this, "DmeBrowser" );
m_pDmeBrowser->AddColumnHeader( 0, "dme", "Dme Elements", 52, 0 );
m_pDmeBrowser->SetSelectIndividualCells( true );
m_pDmeBrowser->SetEmptyListText( "No Dme Elements" );
m_pDmeBrowser->SetDragEnabled( true );
m_pDmeBrowser->AddActionSignalTarget( this );
m_pDmeBrowser->SetSortFunc( 0, DmeBrowserSortFunc );
m_pDmeBrowser->SetSortColumn( 0 );
// filter selection
m_pFilterList = new TextEntry( this, "FilterList" );
m_pFilterList->AddActionSignalTarget( this );
m_pFilterList->RequestFocus();
LoadControlSettingsAndUserConfig( "resource/dmepicker.res" );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CDmePicker::~CDmePicker()
{
}
//-----------------------------------------------------------------------------
// Purpose: called to open
//-----------------------------------------------------------------------------
void CDmePicker::Activate( const CUtlVector< DmePickerInfo_t >&vec )
{
m_pDmeBrowser->RemoveAll();
int nCount = vec.Count();
for ( int i = 0; i < nCount; ++i )
{
CDmElement *pElement = GetElement<CDmElement>( vec[i].m_hElement );
const char *pElementName = pElement ? pElement->GetName() : "<null element>";
const char *pItemName = vec[i].m_pChoiceString ? vec[i].m_pChoiceString : pElementName;
KeyValues *kv = new KeyValues( "node", "dme", pItemName );
kv->SetInt( "dmeHandle", vec[i].m_hElement );
int nItemID = m_pDmeBrowser->AddItem( kv, 0, false, false );
KeyValues *pDrag = new KeyValues( "drag", "text", pElementName );
pDrag->SetString( "texttype", "dmeName" );
pDrag->SetInt( "dmeelement", vec[i].m_hElement );
m_pDmeBrowser->SetItemDragData( nItemID, pDrag );
}
RefreshDmeList();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CDmePicker::OnKeyCodeTyped( KeyCode code )
{
if (( code == KEY_UP ) || ( code == KEY_DOWN ) || ( code == KEY_PAGEUP ) || ( code == KEY_PAGEDOWN ))
{
KeyValues *pMsg = new KeyValues("KeyCodeTyped", "code", code);
vgui::ipanel()->SendMessage( m_pDmeBrowser->GetVPanel(), pMsg, GetVPanel());
pMsg->deleteThis();
}
else
{
BaseClass::OnKeyCodeTyped( code );
}
}
//-----------------------------------------------------------------------------
// Purpose: refreshes the file list
//-----------------------------------------------------------------------------
void CDmePicker::RefreshDmeList()
{
// Check the filter matches
int nMatchingElements = 0;
int nTotalCount = 0;
for ( int nItemID = m_pDmeBrowser->FirstItem(); nItemID != m_pDmeBrowser->InvalidItemID(); nItemID = m_pDmeBrowser->NextItem( nItemID ) )
{
KeyValues *kv = m_pDmeBrowser->GetItem( nItemID );
const char *pElementName = kv->GetString( "dme" );
bool bIsVisible = !m_Filter.Length() || Q_stristr( pElementName, m_Filter.Get() );
m_pDmeBrowser->SetItemVisible( nItemID, bIsVisible );
if ( bIsVisible )
{
++nMatchingElements;
}
++nTotalCount;
}
m_pDmeBrowser->SortList();
char pColumnTitle[512];
Q_snprintf( pColumnTitle, sizeof(pColumnTitle), "%s (%d/%d)",
"Dme Elements", nMatchingElements, nTotalCount );
m_pDmeBrowser->SetColumnHeaderText( 0, pColumnTitle );
if ( ( m_pDmeBrowser->GetItemCount() > 0 ) && ( m_pDmeBrowser->GetSelectedItemsCount() == 0 ) )
{
int nItemID = m_pDmeBrowser->GetItemIDFromRow( 0 );
m_pDmeBrowser->SetSelectedCell( nItemID, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose: refreshes dialog on text changing
//-----------------------------------------------------------------------------
void CDmePicker::OnTextChanged( )
{
int nLength = m_pFilterList->GetTextLength();
m_Filter.SetLength( nLength );
if ( nLength > 0 )
{
m_pFilterList->GetText( m_Filter.Get(), nLength+1 );
}
RefreshDmeList();
}
//-----------------------------------------------------------------------------
// Returns the selceted model name
//-----------------------------------------------------------------------------
CDmElement *CDmePicker::GetSelectedDme( )
{
if ( m_pDmeBrowser->GetSelectedItemsCount() == 0 )
return NULL;
int nIndex = m_pDmeBrowser->GetSelectedItem( 0 );
KeyValues *pItemKeyValues = m_pDmeBrowser->GetItem( nIndex );
return GetElementKeyValue< CDmElement >( pItemKeyValues, "dmeHandle" );
}
//-----------------------------------------------------------------------------
//
// Purpose: Modal picker frame
//
//-----------------------------------------------------------------------------
CDmePickerFrame::CDmePickerFrame( vgui::Panel *pParent, const char *pTitle ) :
BaseClass( pParent, "DmePickerFrame" )
{
m_pContextKeyValues = NULL;
SetDeleteSelfOnClose( true );
m_pPicker = new CDmePicker( this );
m_pPicker->AddActionSignalTarget( this );
m_pOpenButton = new Button( this, "OpenButton", "#FileOpenDialog_Open", this, "Open" );
m_pCancelButton = new Button( this, "CancelButton", "#FileOpenDialog_Cancel", this, "Cancel" );
SetBlockDragChaining( true );
LoadControlSettingsAndUserConfig( "resource/dmepickerframe.res" );
SetTitle( pTitle, false );
}
CDmePickerFrame::~CDmePickerFrame()
{
CleanUpMessage();
}
//-----------------------------------------------------------------------------
// Deletes the message
//-----------------------------------------------------------------------------
void CDmePickerFrame::CleanUpMessage()
{
if ( m_pContextKeyValues )
{
m_pContextKeyValues->deleteThis();
m_pContextKeyValues = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: Activate the dialog
//-----------------------------------------------------------------------------
void CDmePickerFrame::DoModal( const CUtlVector< DmePickerInfo_t >& vec, KeyValues *pKeyValues )
{
CleanUpMessage();
m_pContextKeyValues = pKeyValues;
m_pPicker->Activate( vec );
m_pOpenButton->SetEnabled( vec.Count() != 0 );
BaseClass::DoModal();
}
//-----------------------------------------------------------------------------
// On command
//-----------------------------------------------------------------------------
void CDmePickerFrame::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "Open" ) )
{
CDmElement *pElement = m_pPicker->GetSelectedDme( );
KeyValues *pActionKeys = new KeyValues( "DmeSelected" );
SetElementKeyValue( pActionKeys, "dme", pElement );
if ( m_pContextKeyValues )
{
pActionKeys->AddSubKey( m_pContextKeyValues );
// This prevents them from being deleted later
m_pContextKeyValues = NULL;
}
PostActionSignal( pActionKeys );
CloseModal();
return;
}
if ( !Q_stricmp( pCommand, "Cancel" ) )
{
KeyValues *pActionKeys = new KeyValues( "DmeSelectionCancelled" );
if ( m_pContextKeyValues )
{
pActionKeys->AddSubKey( m_pContextKeyValues );
// This prevents them from being deleted later
m_pContextKeyValues = NULL;
}
PostActionSignal( pActionKeys );
CloseModal();
return;
}
BaseClass::OnCommand( pCommand );
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,53 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/filtercombobox.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CFilterComboBox::CFilterComboBox( Panel *parent, const char *panelName, int numLines, bool allowEdit ) :
BaseClass( parent, panelName, numLines, allowEdit )
{
}
//-----------------------------------------------------------------------------
// Purpose: panel lost focus message
//-----------------------------------------------------------------------------
void CFilterComboBox::OnKillFocus()
{
int nLength = GetTextLength();
char *pFilterText = (char*)_alloca( (nLength+1) * sizeof(char) );
GetText( pFilterText, nLength+1 );
// Remove the existing version in the list
char pItemText[512];
int nItemCount = GetItemCount();
int i;
for ( i = 0; i < nItemCount; ++i )
{
GetItemText( i, pItemText, sizeof(pItemText) );
if ( !Q_stricmp( pFilterText, pItemText ) )
break;
}
if ( i != nItemCount )
{
// Remove the existing copy
DeleteItem( i );
}
AddItem( pFilterText, NULL );
BaseClass::OnKillFocus( );
}

View File

@@ -0,0 +1,495 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/mdlpanel.h"
#include "materialsystem/imaterialsystem.h"
#include <materialsystem/IMaterialSystemHardwareConfig.h>
#include "materialsystem/imesh.h"
#include "vgui/ivgui.h"
#include "tier1/keyvalues.h"
#include "movieobjects/dmemdl.h"
#include "movieobjects/dmetransform.h"
#include "movieobjects/dmedag.h"
#include "movieobjects/dmemdlmakefile.h"
#include "vgui_controls/frame.h"
#include "convar.h"
#include "tier0/dbg.h"
#include "istudiorender.h"
#include "matsys_controls/matsyscontrols.h"
#include "vcollide.h"
#include "vcollide_parse.h"
#include "bone_setup.h"
#include "vphysics_interface.h"
#include "dme_controls/dmecontrols.h"
#include "dme_controls/dmepanel.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
IMPLEMENT_DMEPANEL_FACTORY( CMDLPanel, DmeMDLMakefile, "DmeMakeFileOutputPreview", "MDL MakeFile Output Preview", false );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CMDLPanel::CMDLPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
CDmeMDL *pMDL = CreateElement< CDmeMDL >( "mdl", DMFILEID_INVALID );
m_hMDL = pMDL;
m_hMDL->DrawInEngine( true );
UseEngineCoordinateSystem( true );
m_pDag = CreateElement< CDmeDag >( "dag", DMFILEID_INVALID );
m_pDag->SetShape( pMDL );
SetVisible( true );
// Used to poll input
vgui::ivgui()->AddTickSignal( GetVPanel() );
// Deal with the default cubemap
ITexture *pCubemapTexture = vgui::MaterialSystem()->FindTexture( "editor/cubemap", NULL, true );
m_DefaultEnvCubemap.Init( pCubemapTexture );
pCubemapTexture = vgui::MaterialSystem()->FindTexture( "editor/cubemap.hdr", NULL, true );
m_DefaultHDREnvCubemap.Init( pCubemapTexture );
KeyValues *pMaterialKeys = new KeyValues( "Wireframe", "$model", "1" );
pMaterialKeys->SetString( "$vertexcolor", "1" );
m_Wireframe.Init( "mdlpanelwireframe", pMaterialKeys );
m_bDrawCollisionModel = false;
m_bWireFrame = false;
m_bGroundGrid = false;
m_bLockView = false;
m_bIsExternalMDL = false;
}
CMDLPanel::~CMDLPanel()
{
CDisableUndoScopeGuard guard;
m_pDag->SetShape( NULL );
m_DefaultEnvCubemap.Shutdown( );
m_DefaultHDREnvCubemap.Shutdown();
if ( !m_bIsExternalMDL )
{
DestroyElement( m_hMDL );
m_hMDL = NULL;
}
g_pDataModel->DestroyElement( m_pDag->GetHandle() );
}
//-----------------------------------------------------------------------------
// Scheme settings
//-----------------------------------------------------------------------------
void CMDLPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetBorder( pScheme->GetBorder( "MenuBorder") );
}
//-----------------------------------------------------------------------------
// DMEPanel..
//-----------------------------------------------------------------------------
void CMDLPanel::SetDmeElement( CDmeMDLMakefile *pMDLMakefile )
{
CDisableUndoScopeGuard sg;
if ( !m_bIsExternalMDL )
{
DestroyElement( m_hMDL );
m_hMDL = NULL;
}
CDmeMDL *pMDL = NULL;
if ( pMDLMakefile != NULL )
{
pMDL = CastElement< CDmeMDL >( pMDLMakefile->GetOutputElement( true ) );
m_bIsExternalMDL = ( pMDL != NULL );
}
if ( !pMDL )
{
pMDL = CreateElement< CDmeMDL >( "mdl", DMFILEID_INVALID );
}
m_hMDL = pMDL;
m_hMDL->DrawInEngine( true );
m_pDag->SetShape( pMDL );
}
//-----------------------------------------------------------------------------
// Rendering options
//-----------------------------------------------------------------------------
void CMDLPanel::SetCollsionModel( bool bVisible )
{
m_bDrawCollisionModel = bVisible;
}
void CMDLPanel::SetGroundGrid( bool bVisible )
{
m_bGroundGrid = bVisible;
}
void CMDLPanel::SetWireFrame( bool bVisible )
{
m_bWireFrame = bVisible;
}
void CMDLPanel::SetLockView( bool bLocked )
{
m_bLockView = bLocked;
}
void CMDLPanel::SetLookAtCamera( bool bLookAtCamera )
{
m_bLookAtCamera = bLookAtCamera;
}
//-----------------------------------------------------------------------------
// Stores the clip
//-----------------------------------------------------------------------------
void CMDLPanel::SetMDL( MDLHandle_t handle )
{
CDisableUndoScopeGuard sg;
m_hMDL->SetMDL( handle );
}
//-----------------------------------------------------------------------------
// Sets the camera to look at the model
//-----------------------------------------------------------------------------
void CMDLPanel::LookAtMDL( )
{
if ( m_bLockView )
return;
float flRadius;
Vector vecCenter;
m_hMDL->GetBoundingSphere( vecCenter, flRadius );
LookAt( vecCenter, flRadius );
}
//-----------------------------------------------------------------------------
// FIXME: This should be moved into studiorender
//-----------------------------------------------------------------------------
static ConVar r_showenvcubemap( "r_showenvcubemap", "0", FCVAR_CHEAT );
static ConVar r_eyegloss ( "r_eyegloss", "1", FCVAR_ARCHIVE ); // wet eyes
static ConVar r_eyemove ( "r_eyemove", "1", FCVAR_ARCHIVE ); // look around
static ConVar r_eyeshift_x ( "r_eyeshift_x", "0", FCVAR_ARCHIVE ); // eye X position
static ConVar r_eyeshift_y ( "r_eyeshift_y", "0", FCVAR_ARCHIVE ); // eye Y position
static ConVar r_eyeshift_z ( "r_eyeshift_z", "0", FCVAR_ARCHIVE ); // eye Z position
static ConVar r_eyesize ( "r_eyesize", "0", FCVAR_ARCHIVE ); // adjustment to iris textures
static ConVar mat_softwareskin( "mat_softwareskin", "0" );
static ConVar r_nohw ( "r_nohw", "0", FCVAR_CHEAT );
static ConVar r_nosw ( "r_nosw", "0", FCVAR_CHEAT );
static ConVar r_teeth ( "r_teeth", "1" );
static ConVar r_drawentities ( "r_drawentities", "1", FCVAR_CHEAT );
static ConVar r_flex ( "r_flex", "1" );
static ConVar r_eyes ( "r_eyes", "1" );
static ConVar r_skin ( "r_skin","0" );
static ConVar r_maxmodeldecal ( "r_maxmodeldecal", "50" );
static ConVar r_modelwireframedecal ( "r_modelwireframedecal", "0", FCVAR_CHEAT );
static ConVar mat_normals ( "mat_normals", "0", FCVAR_CHEAT );
static ConVar r_eyeglintlodpixels ( "r_eyeglintlodpixels", "0", FCVAR_CHEAT );
static ConVar r_rootlod ( "r_rootlod", "0", FCVAR_CHEAT );
static StudioRenderConfig_t s_StudioRenderConfig;
void CMDLPanel::UpdateStudioRenderConfig( void )
{
memset( &s_StudioRenderConfig, 0, sizeof(s_StudioRenderConfig) );
s_StudioRenderConfig.bEyeMove = !!r_eyemove.GetInt();
s_StudioRenderConfig.fEyeShiftX = r_eyeshift_x.GetFloat();
s_StudioRenderConfig.fEyeShiftY = r_eyeshift_y.GetFloat();
s_StudioRenderConfig.fEyeShiftZ = r_eyeshift_z.GetFloat();
s_StudioRenderConfig.fEyeSize = r_eyesize.GetFloat();
if( mat_softwareskin.GetInt() || m_bWireFrame )
{
s_StudioRenderConfig.bSoftwareSkin = true;
}
else
{
s_StudioRenderConfig.bSoftwareSkin = false;
}
s_StudioRenderConfig.bNoHardware = !!r_nohw.GetInt();
s_StudioRenderConfig.bNoSoftware = !!r_nosw.GetInt();
s_StudioRenderConfig.bTeeth = !!r_teeth.GetInt();
s_StudioRenderConfig.drawEntities = r_drawentities.GetInt();
s_StudioRenderConfig.bFlex = !!r_flex.GetInt();
s_StudioRenderConfig.bEyes = !!r_eyes.GetInt();
s_StudioRenderConfig.bWireframe = m_bWireFrame;
s_StudioRenderConfig.bDrawNormals = mat_normals.GetBool();
s_StudioRenderConfig.skin = r_skin.GetInt();
s_StudioRenderConfig.maxDecalsPerModel = r_maxmodeldecal.GetInt();
s_StudioRenderConfig.bWireframeDecals = r_modelwireframedecal.GetInt() != 0;
s_StudioRenderConfig.fullbright = false;
s_StudioRenderConfig.bSoftwareLighting = false;
s_StudioRenderConfig.bShowEnvCubemapOnly = r_showenvcubemap.GetBool();
s_StudioRenderConfig.fEyeGlintPixelWidthLODThreshold = r_eyeglintlodpixels.GetFloat();
StudioRender()->UpdateConfig( s_StudioRenderConfig );
}
void CMDLPanel::DrawCollisionModel()
{
vcollide_t *pCollide = MDLCache()->GetVCollide( m_hMDL->GetMDL() );
if ( !pCollide || pCollide->solidCount <= 0 )
return;
static color32 color = {255,0,0,0};
IVPhysicsKeyParser *pParser = g_pPhysicsCollision->VPhysicsKeyParserCreate( pCollide );
CStudioHdr studioHdr( g_pMDLCache->GetStudioHdr( m_hMDL->GetMDL() ), g_pMDLCache );
matrix3x4_t pBoneToWorld[MAXSTUDIOBONES];
matrix3x4_t shapeToWorld;
m_pDag->GetTransform()->GetTransform( shapeToWorld );
m_hMDL->SetUpBones( shapeToWorld, MAXSTUDIOBONES, pBoneToWorld );
// PERFORMANCE: Just parse the script each frame. It's fast enough for tools. If you need
// this to go faster then cache off the bone index mapping in an array like HLMV does
while ( !pParser->Finished() )
{
const char *pBlock = pParser->GetCurrentBlockName();
if ( !stricmp( pBlock, "solid" ) )
{
solid_t solid;
pParser->ParseSolid( &solid, NULL );
int boneIndex = Studio_BoneIndexByName( &studioHdr, solid.name );
Vector *outVerts;
int vertCount = g_pPhysicsCollision->CreateDebugMesh( pCollide->solids[solid.index], &outVerts );
if ( vertCount )
{
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
pRenderContext->CullMode( MATERIAL_CULLMODE_CCW );
// NOTE: assumes these have been set up already by the model render code
// So this is a little bit of a back door to a cache of the bones
// this code wouldn't work unless you draw the model this frame before calling
// this routine. CMDLPanel always does this, but it's worth noting.
// A better solution would be to move the ragdoll visulization into the CDmeMdl
// and either draw it there or make it queryable and query/draw here.
matrix3x4_t xform;
SetIdentityMatrix( xform );
if ( boneIndex >= 0 )
{
MatrixCopy( pBoneToWorld[ boneIndex ], xform );
}
IMesh *pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, m_Wireframe );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, vertCount/3 );
for ( int j = 0; j < vertCount; j++ )
{
Vector out;
VectorTransform( outVerts[j].Base(), xform, out.Base() );
meshBuilder.Position3fv( out.Base() );
meshBuilder.Color4ub( color.r, color.g, color.b, color.a );
meshBuilder.TexCoord2f( 0, 0, 0 );
meshBuilder.AdvanceVertex();
}
meshBuilder.End();
pMesh->Draw();
}
g_pPhysicsCollision->DestroyDebugMesh( vertCount, outVerts );
}
else
{
pParser->SkipBlock();
}
}
g_pPhysicsCollision->VPhysicsKeyParserDestroy( pParser );
}
//-----------------------------------------------------------------------------
// paint it!
//-----------------------------------------------------------------------------
void CMDLPanel::OnPaint3D()
{
if ( !m_hMDL.Get() )
return;
// FIXME: Move this call into DrawModel in StudioRender
StudioRenderConfig_t oldStudioRenderConfig;
StudioRender()->GetCurrentConfig( oldStudioRenderConfig );
UpdateStudioRenderConfig();
CMatRenderContextPtr pRenderContext( vgui::MaterialSystem() );
ITexture *pLocalCube = pRenderContext->GetLocalCubemap();
if ( vgui::MaterialSystemHardwareConfig()->GetHDRType() == HDR_TYPE_NONE )
{
ITexture *pMyCube = HasLightProbe() ? GetLightProbeCubemap( false ) : m_DefaultEnvCubemap;
pRenderContext->BindLocalCubemap( pMyCube );
}
else
{
ITexture *pMyCube = HasLightProbe() ? GetLightProbeCubemap( true ) : m_DefaultHDREnvCubemap;
pRenderContext->BindLocalCubemap( pMyCube );
}
if ( m_bGroundGrid )
{
DrawGrid();
}
if ( m_bLookAtCamera )
{
CDisableUndoScopeGuard sg;
matrix3x4_t worldToCamera;
ComputeCameraTransform( &worldToCamera );
Vector vecPosition;
MatrixGetColumn( worldToCamera, 3, vecPosition );
m_hMDL->m_bWorldSpaceViewTarget = true;
m_hMDL->m_vecViewTarget = vecPosition;
}
// Draw the MDL
m_pDag->Draw();
if ( m_bDrawCollisionModel )
{
DrawCollisionModel();
}
pRenderContext->Flush();
StudioRender()->UpdateConfig( oldStudioRenderConfig );
pRenderContext->BindLocalCubemap( pLocalCube );
}
//-----------------------------------------------------------------------------
// Sets the current sequence
//-----------------------------------------------------------------------------
void CMDLPanel::SetSequence( int nSequence )
{
CDisableUndoScopeGuard guard;
m_hMDL->m_nSequence = nSequence;
}
void CMDLPanel::SetSkin( int nSkin )
{
CDisableUndoScopeGuard guard;
m_hMDL->m_nSkin = nSkin;
}
//-----------------------------------------------------------------------------
// Purpose: Keeps a global clock to autoplay sequences to run from
// Also deals with speedScale changes
//-----------------------------------------------------------------------------
float GetAutoPlayTime( void )
{
static int g_prevTicks;
static float g_time;
int ticks = Plat_MSTime();
// limit delta so that float time doesn't overflow
if (g_prevTicks == 0)
{
g_prevTicks = ticks;
}
g_time += ( ticks - g_prevTicks ) / 1000.0f;
g_prevTicks = ticks;
return g_time;
}
//-----------------------------------------------------------------------------
// called when we're ticked...
//-----------------------------------------------------------------------------
void CMDLPanel::OnTick()
{
BaseClass::OnTick();
if ( m_hMDL->GetMDL() != MDLHANDLE_INVALID )
{
CDisableUndoScopeGuard guard;
m_hMDL->m_flTime = GetAutoPlayTime();
}
}
//-----------------------------------------------------------------------------
// input
//-----------------------------------------------------------------------------
void CMDLPanel::OnMouseDoublePressed( vgui::MouseCode code )
{
float flRadius;
Vector vecCenter;
m_hMDL->GetBoundingSphere( vecCenter, flRadius );
LookAt( vecCenter, flRadius );
BaseClass::OnMouseDoublePressed( code );
}
//-----------------------------------------------------------------------------
// Draws the grid under the MDL
//-----------------------------------------------------------------------------
void CMDLPanel::DrawGrid()
{
matrix3x4_t transform;
SetIdentityMatrix( transform );
CMatRenderContextPtr pRenderContext( MaterialSystem() );
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->LoadMatrix( transform );
pRenderContext->Bind( m_Wireframe );
IMesh *pMesh = pRenderContext->GetDynamicMesh();
int nGridDim = 10;
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_LINES, 2 * nGridDim + 2 );
float bounds = 100.0f;
float delta = 2 * bounds / nGridDim;
for ( int i = 0; i < nGridDim + 1; ++i )
{
float xy = -bounds + delta * i;
meshBuilder.Position3f( xy, -bounds, 0 );
meshBuilder.Color4ub( 255, 255, 255, 255 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( xy, bounds, 0 );
meshBuilder.Color4ub( 255, 255, 255, 255 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( -bounds, xy, 0 );
meshBuilder.Color4ub( 255, 255, 255, 255 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( bounds, xy, 0 );
meshBuilder.Color4ub( 255, 255, 255, 255 );
meshBuilder.AdvanceVertex();
}
meshBuilder.End();
pMesh->Draw();
}

View File

@@ -0,0 +1,889 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "dme_controls/particlesystempanel.h"
#include "dme_controls/dmepanel.h"
#include "movieobjects/dmeparticlesystemdefinition.h"
#include "materialsystem/imesh.h"
#include "materialsystem/imaterial.h"
#include "vguimatsurface/imatsystemsurface.h"
#include "matsys_controls/matsyscontrols.h"
#include "vgui/ivgui.h"
#include "vgui_controls/propertypage.h"
#include "vgui_controls/propertysheet.h"
#include "vgui_controls/textentry.h"
#include "vgui_controls/splitter.h"
#include "vgui_controls/checkbutton.h"
#include "matsys_controls/colorpickerpanel.h"
#include "particles/particles.h"
#include "tier1/keyvalues.h"
#include "tier1/utlbuffer.h"
#include "tier2/renderutils.h"
using namespace vgui;
//-----------------------------------------------------------------------------
// Enums
//-----------------------------------------------------------------------------
enum
{
SCROLLBAR_SIZE=18, // the width of a scrollbar
WINDOW_BORDER_WIDTH=2 // the width of the window's border
};
#define SPHERE_RADIUS 10.0f
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CParticleSystemPanel::CParticleSystemPanel( vgui::Panel *pParent, const char *pName ) : BaseClass( pParent, pName )
{
m_pParticleSystem = NULL;
m_flLastTime = FLT_MAX;
m_bRenderBounds = false;
m_bRenderCullBounds = false;
m_bRenderHelpers = false;
m_bRenderControlPoints = false;
m_bPerformNameBasedLookup = true;
m_bTickMyself = true;
m_bAutoView = false;
m_bSuppressAutoView = false;
m_ParticleSystemName = NULL;
InvalidateUniqueId( &m_ParticleSystemId );
InvalidateUniqueId( &m_RenderHelperId );
LookAt( SPHERE_RADIUS );
m_pLightmapTexture.Init( "//platform/materials/debug/defaultlightmap", "editor" );
m_DefaultEnvCubemap.Init( "editor/cubemap", "editor", true );
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
SetControlPointValue( i, vec3_invalid );
}
}
CParticleSystemPanel::~CParticleSystemPanel()
{
m_pLightmapTexture.Shutdown();
m_DefaultEnvCubemap.Shutdown();
delete m_pParticleSystem;
m_pParticleSystem = NULL;
}
void CParticleSystemPanel::ResetView()
{
BaseClass::ResetView();
LookAt(SPHERE_RADIUS);
m_BestViewBoundsMin = vec3_origin;
m_BestViewBoundsMax = vec3_origin;
m_bSuppressAutoView = false;
}
//-----------------------------------------------------------------------------
// Scheme
//-----------------------------------------------------------------------------
void CParticleSystemPanel::ApplySchemeSettings( vgui::IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
SetBorder( pScheme->GetBorder( "MenuBorder") );
}
//-----------------------------------------------------------------------------
// Stop System
//-----------------------------------------------------------------------------
void CParticleSystemPanel::StopEffect()
{
if ( !m_pParticleSystem )
return;
m_pParticleSystem->StopEmission(false, false, false, true );
}
//-----------------------------------------------------------------------------
// Indicates that the grid should be drawn
//-----------------------------------------------------------------------------
void CParticleSystemPanel::RenderGrid( bool bEnable )
{
m_bRenderGrid = bEnable;
}
//-----------------------------------------------------------------------------
// Indicates that bounds should be drawn
//-----------------------------------------------------------------------------
void CParticleSystemPanel::RenderBounds( bool bEnable )
{
m_bRenderBounds = bEnable;
}
//-----------------------------------------------------------------------------
// Indicates that control points should be drawn
//-----------------------------------------------------------------------------
void CParticleSystemPanel::RenderControlPoints( bool bEnable )
{
m_bRenderControlPoints = bEnable;
}
//-----------------------------------------------------------------------------
// Indicates that cull sphere should be drawn
//-----------------------------------------------------------------------------
void CParticleSystemPanel::RenderCullBounds( bool bEnable )
{
m_bRenderCullBounds = bEnable;
}
//-----------------------------------------------------------------------------
// Indicates that bounds should be drawn
//-----------------------------------------------------------------------------
void CParticleSystemPanel::RenderHelpers( bool bEnable )
{
m_bRenderHelpers = bEnable;
}
//-----------------------------------------------------------------------------
// Indicates which helper to draw
//-----------------------------------------------------------------------------
void CParticleSystemPanel::SetRenderedHelper( CDmeParticleFunction *pOp )
{
if ( !pOp )
{
InvalidateUniqueId( &m_RenderHelperId );
}
else
{
CopyUniqueId( pOp->GetId(), &m_RenderHelperId );
}
}
//-----------------------------------------------------------------------------
// Simulate the particle system
//-----------------------------------------------------------------------------
void CParticleSystemPanel::OnTick()
{
BaseClass::OnTick();
if( m_bTickMyself )
{
Simulate();
}
}
void CParticleSystemPanel::Simulate()
{
if ( !m_pParticleSystem )
return;
float flTime = Plat_FloatTime();
if ( m_flLastTime == FLT_MAX )
{
m_flLastTime = flTime;
}
float flDt = flTime - m_flLastTime;
m_flLastTime = flTime;
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( !m_pParticleSystem->ReadsControlPoint( i ) || m_pControlPointValue[i] == vec3_invalid )
continue;
m_pParticleSystem->SetControlPoint( i, m_pControlPointValue[i] );
m_pParticleSystem->SetControlPointOrientation( i, Vector( 1, 0, 0 ), Vector( 0, -1, 0 ), Vector( 0, 0, 1 ) );
m_pParticleSystem->SetControlPointParent( i, i );
}
// Restart the particle system if it's finished
bool bIsInvalid = !m_pParticleSystem->IsFullyValid();
if ( m_pParticleSystem->IsFinished() || bIsInvalid )
{
delete m_pParticleSystem;
m_pParticleSystem = NULL;
if ( m_bPerformNameBasedLookup )
{
if ( m_ParticleSystemName.Length() )
{
CParticleCollection *pNewParticleSystem = g_pParticleSystemMgr->CreateParticleCollection( m_ParticleSystemName );
m_pParticleSystem = pNewParticleSystem;
}
}
else
{
if ( IsUniqueIdValid( m_ParticleSystemId ) )
{
CParticleCollection *pNewParticleSystem = g_pParticleSystemMgr->CreateParticleCollection( m_ParticleSystemId );
m_pParticleSystem = pNewParticleSystem;
}
}
if ( bIsInvalid )
{
PostActionSignal( new KeyValues( "ParticleSystemReconstructed" ) );
}
m_flLastTime = FLT_MAX;
}
else
{
m_pParticleSystem->Simulate( flDt );
}
if( m_bAutoView && !m_bSuppressAutoView )
{
UseAutoView();
}
}
//-----------------------------------------------------------------------------
// Startup, shutdown particle collection
//-----------------------------------------------------------------------------
void CParticleSystemPanel::StartupParticleCollection()
{
if ( m_pParticleSystem && m_bTickMyself )
{
vgui::ivgui()->AddTickSignal( GetVPanel(), 0 );
}
m_flLastTime = FLT_MAX;
}
void CParticleSystemPanel::ShutdownParticleCollection()
{
if ( m_pParticleSystem )
{
if( m_bTickMyself )
{
vgui::ivgui()->RemoveTickSignal( GetVPanel() );
}
delete m_pParticleSystem;
m_pParticleSystem = NULL;
}
}
void CParticleSystemPanel::SetSelfSimulation(bool bSelfSimulate )
{
if( m_pParticleSystem && ( m_bTickMyself != bSelfSimulate ) )
{
if ( !bSelfSimulate )
{
vgui::ivgui()->RemoveTickSignal( GetVPanel() );
}
else
{
vgui::ivgui()->AddTickSignal( GetVPanel(), 0 );
}
}
m_bTickMyself = bSelfSimulate;
}
//-----------------------------------------------------------------------------
// Set the particle system to draw
//-----------------------------------------------------------------------------
void CParticleSystemPanel::SetParticleSystem( CDmeParticleSystemDefinition *pDef )
{
ShutdownParticleCollection();
if ( pDef )
{
m_bPerformNameBasedLookup = pDef->UseNameBasedLookup();
if ( m_bPerformNameBasedLookup )
{
m_ParticleSystemName = pDef->GetName();
Assert( g_pParticleSystemMgr->IsParticleSystemDefined( m_ParticleSystemName ) );
m_pParticleSystem = g_pParticleSystemMgr->CreateParticleCollection( m_ParticleSystemName );
}
else
{
CopyUniqueId( pDef->GetId(), &m_ParticleSystemId );
Assert( g_pParticleSystemMgr->IsParticleSystemDefined( m_ParticleSystemId ) );
m_pParticleSystem = g_pParticleSystemMgr->CreateParticleCollection( m_ParticleSystemId );
}
PostActionSignal( new KeyValues( "ParticleSystemReconstructed" ) );
}
StartupParticleCollection();
}
void CParticleSystemPanel::SetParticleSystem( const char* szParticleSystemName )
{
ShutdownParticleCollection();
if ( szParticleSystemName )
{
m_ParticleSystemName = szParticleSystemName;
if ( g_pParticleSystemMgr->IsParticleSystemDefined( m_ParticleSystemName ) )
{
m_pParticleSystem = g_pParticleSystemMgr->CreateParticleCollection( m_ParticleSystemName );
}
else
{
m_pParticleSystem = NULL;
}
PostActionSignal( new KeyValues( "ParticleSystemReconstructed" ) );
}
StartupParticleCollection();
}
void CParticleSystemPanel::SetDmeElement( CDmeParticleSystemDefinition *pDef )
{
SetParticleSystem( pDef );
}
CParticleCollection *CParticleSystemPanel::GetParticleSystem()
{
return m_pParticleSystem;
}
//-----------------------------------------------------------------------------
// Auto-viewing
//-----------------------------------------------------------------------------
void CParticleSystemPanel::EnterManipulationMode( ManipulationMode_t manipMode, bool bMouseCapture, vgui::MouseCode mouseCode )
{
BaseClass::EnterManipulationMode(manipMode,bMouseCapture,mouseCode);
if( manipMode != CAMERA_ROTATE )
{
m_bSuppressAutoView = true;
}
}
void CParticleSystemPanel::EnableAutoViewing( bool bEnable )
{
m_bAutoView = bEnable;
m_BestViewBoundsMin = vec3_origin;
m_BestViewBoundsMax = vec3_origin;
if ( m_bAutoView )
{
m_bSuppressAutoView = false;
}
}
void CParticleSystemPanel::UseAutoView()
{
Vector vecMins, vecMaxs;
m_pParticleSystem->GetBounds( &vecMins, &vecMaxs );
m_BestViewBoundsMin = m_BestViewBoundsMin.Min(vecMins);
m_BestViewBoundsMax = m_BestViewBoundsMax.Max(vecMaxs);
float flBestViewRad = MAX( 5.0f, 0.25f*(m_BestViewBoundsMax-m_BestViewBoundsMin).Length() );
Vector viewCenter = ( m_BestViewBoundsMin + m_BestViewBoundsMax ) * 0.5f;
LookAt( viewCenter, flBestViewRad );
}
//-----------------------------------------------------------------------------
// Draw bounds
//-----------------------------------------------------------------------------
void CParticleSystemPanel::DrawBounds()
{
Vector vecMins, vecMaxs;
m_pParticleSystem->GetBounds( &vecMins, &vecMaxs );
RenderWireframeBox( vec3_origin, vec3_angle, vecMins, vecMaxs, Color( 0, 255, 255, 255 ), true );
}
//-----------------------------------------------------------------------------
// Draw cull bounds
//-----------------------------------------------------------------------------
void CParticleSystemPanel::DrawCullBounds()
{
Vector vecCenter;
m_pParticleSystem->GetControlPointAtTime( m_pParticleSystem->m_pDef->GetCullControlPoint(), m_pParticleSystem->m_flCurTime, &vecCenter );
RenderWireframeSphere( vecCenter, m_pParticleSystem->m_pDef->GetCullRadius(), 32, 16, Color( 0, 255, 255, 255 ), true );
}
//-----------------------------------------------------------------------------
// paint it!
//-----------------------------------------------------------------------------
#define AXIS_SIZE 5.0f
void CParticleSystemPanel::OnPaint3D()
{
if ( !m_pParticleSystem )
return;
CMatRenderContextPtr pRenderContext( MaterialSystem() );
pRenderContext->BindLightmapTexture( m_pLightmapTexture );
pRenderContext->BindLocalCubemap( m_DefaultEnvCubemap );
// Draw axes
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity( );
if ( m_bRenderGrid )
{
DrawGrid();
}
if ( m_bRenderBounds )
{
DrawBounds();
}
if ( m_bRenderCullBounds )
{
DrawCullBounds();
}
if ( m_bRenderHelpers && IsUniqueIdValid( m_RenderHelperId ) )
{
m_pParticleSystem->VisualizeOperator( &m_RenderHelperId );
}
Vector4D vecDiffuseModulation( 1.0f, 1.0f, 1.0f, 1.0f );
m_pParticleSystem->Render( 0, pRenderContext, vecDiffuseModulation );
m_pParticleSystem->VisualizeOperator( );
RenderAxes( vec3_origin, AXIS_SIZE, true );
if ( m_bRenderControlPoints )
{
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( m_pParticleSystem->ReadsControlPoint( i ) )
{
Vector vP;
m_pParticleSystem->GetControlPointAtTime( i, m_pParticleSystem->m_flCurTime, &vP );
RenderAxes( vP, 3.0f, true );
}
}
}
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PopMatrix();
}
//-----------------------------------------------------------------------------
//
// Control point page
//
//-----------------------------------------------------------------------------
class CControlPointPage : public vgui::PropertyPage
{
DECLARE_CLASS_SIMPLE( CControlPointPage, vgui::PropertyPage );
public:
// constructor, destructor
CControlPointPage( vgui::Panel *pParent, const char *pName, CParticleSystemPanel *pParticleSystemPanel );
virtual void PerformLayout();
void CreateControlPointControls( );
private:
MESSAGE_FUNC_PARAMS( OnTextChanged, "TextChanged", params );
MESSAGE_FUNC_PARAMS( OnNewLine, "TextNewLine", params );
void LayoutControlPointControls();
void CleanUpControlPointControls();
vgui::Label *m_pControlPointName[MAX_PARTICLE_CONTROL_POINTS];
vgui::TextEntry *m_pControlPointValue[MAX_PARTICLE_CONTROL_POINTS];
CParticleSystemPanel *m_pParticleSystemPanel;
};
//-----------------------------------------------------------------------------
// Contstructor
//-----------------------------------------------------------------------------
CControlPointPage::CControlPointPage( vgui::Panel *pParent, const char *pName, CParticleSystemPanel *pParticleSystemPanel ) :
BaseClass( pParent, pName )
{
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
m_pControlPointName[i] = NULL;
m_pControlPointValue[i] = NULL;
}
m_pParticleSystemPanel = pParticleSystemPanel;
}
//-----------------------------------------------------------------------------
// Called when the text entry for a control point is changed
//-----------------------------------------------------------------------------
void CControlPointPage::OnTextChanged( KeyValues *pParams )
{
vgui::Panel *pPanel = (vgui::Panel *)pParams->GetPtr( "panel" );
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( pPanel != m_pControlPointValue[i] )
continue;
char pBuf[512];
m_pControlPointValue[i]->GetText( pBuf, sizeof(pBuf) );
Vector vecValue( 0, 0, 0 );
sscanf( pBuf, "%f %f %f", &vecValue.x, &vecValue.y, &vecValue.z );
m_pParticleSystemPanel->SetControlPointValue( i, vecValue );
break;
}
}
//-----------------------------------------------------------------------------
// Called when the text entry for a control point is changed
//-----------------------------------------------------------------------------
void CControlPointPage::OnNewLine( KeyValues *pParams )
{
vgui::Panel *pPanel = (vgui::Panel *)pParams->GetPtr( "panel" );
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( pPanel != m_pControlPointValue[i] )
continue;
char pBuf[512];
m_pControlPointValue[i]->GetText( pBuf, sizeof(pBuf) );
Vector vecValue( 0, 0, 0 );
sscanf( pBuf, "%f %f %f", &vecValue.x, &vecValue.y, &vecValue.z );
m_pParticleSystemPanel->SetControlPointValue( i, vecValue );
vecValue = m_pParticleSystemPanel->GetControlPointValue( i );
Q_snprintf( pBuf, sizeof(pBuf), "%.3f %.3f %.3f", vecValue.x, vecValue.y, vecValue.z );
m_pControlPointValue[i]->SetText( pBuf );
break;
}
}
//-----------------------------------------------------------------------------
// Called when the particle system changes
//-----------------------------------------------------------------------------
void CControlPointPage::PerformLayout()
{
BaseClass::PerformLayout();
LayoutControlPointControls();
}
//-----------------------------------------------------------------------------
// Creates controls used to modify control point values
//-----------------------------------------------------------------------------
void CControlPointPage::CreateControlPointControls()
{
CleanUpControlPointControls();
CParticleCollection* pParticleSystem = m_pParticleSystemPanel->GetParticleSystem();
if ( !pParticleSystem )
return;
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( !pParticleSystem->ReadsControlPoint( i ) )
continue;
char pName[512];
Q_snprintf( pName, sizeof(pName), "Pt #%d:", i );
m_pControlPointName[i] = new Label( this, pName, pName );
Q_snprintf( pName, sizeof(pName), "Entry #%d:", i );
m_pControlPointValue[i] = new TextEntry( this, pName );
m_pControlPointValue[i]->AddActionSignalTarget( this );
m_pControlPointValue[i]->SendNewLine( true );
m_pControlPointValue[i]->SetMultiline( false );
Vector vecValue = m_pParticleSystemPanel->GetControlPointValue( i );
if ( vecValue == vec3_invalid )
vecValue = vec3_origin;
Q_snprintf( pName, sizeof(pName), "%.3f %.3f %.3f", vecValue.x, vecValue.y, vecValue.z );
m_pControlPointValue[i]->SetText( pName );
}
LayoutControlPointControls();
}
//-----------------------------------------------------------------------------
// Lays out the controls
//-----------------------------------------------------------------------------
void CControlPointPage::LayoutControlPointControls()
{
int nFoundControlCount = 0;
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( !m_pControlPointName[i] )
continue;
int yVal = 8 + nFoundControlCount * 28;
m_pControlPointName[i]->SetBounds( 8, yVal, 48, 24 );
m_pControlPointValue[i]->SetBounds( 64, yVal, 160, 24 );
++nFoundControlCount;
}
}
//-----------------------------------------------------------------------------
// Cleans up controls used to modify control point values
//-----------------------------------------------------------------------------
void CControlPointPage::CleanUpControlPointControls( )
{
for ( int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i )
{
if ( m_pControlPointName[i] )
{
delete m_pControlPointName[i];
m_pControlPointName[i] = NULL;
}
if ( m_pControlPointValue[i] )
{
delete m_pControlPointValue[i];
m_pControlPointValue[i] = NULL;
}
}
}
//-----------------------------------------------------------------------------
//
// CParticleSystemPreviewPanel
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Dme panel connection
//-----------------------------------------------------------------------------
IMPLEMENT_DMEPANEL_FACTORY( CParticleSystemPreviewPanel, DmeParticleSystemDefinition, "DmeParticleSystemDefinitionViewer", "Particle System Viewer", false );
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CParticleSystemPreviewPanel::CParticleSystemPreviewPanel( vgui::Panel *pParent, const char *pName ) :
BaseClass( pParent, pName )
{
m_pUnlockSystem = NULL;
m_Splitter = new vgui::Splitter( this, "Splitter", SPLITTER_MODE_VERTICAL, 1 );
vgui::Panel *pSplitterLeftSide = m_Splitter->GetChild( 0 );
vgui::Panel *pSplitterRightSide = m_Splitter->GetChild( 1 );
m_pParticleSystemPanel = new CParticleSystemPanel( pSplitterRightSide, "ParticlePreview" );
m_pParticleSystemPanel->AddActionSignalTarget( this );
m_pParticleSystemPanel->SetBackgroundColor( 0, 0, 0 );
m_pParticleCount = new vgui::Label( pSplitterRightSide, "ParticleCountLabel", "" );
m_pParticleCount->SetZPos( 1 );
m_pControlSheet = new vgui::PropertySheet( pSplitterLeftSide, "ControlSheet" );
m_pRenderPage = new vgui::PropertyPage( m_pControlSheet, "RenderPage" );
m_pRenderBounds = new vgui::CheckButton( m_pRenderPage, "RenderBounds", "Render Bounding Box" );
m_pRenderBounds->AddActionSignalTarget( this );
m_pRenderControlPoints = new vgui::CheckButton( m_pRenderPage, "RenderControlPoints", "Render Control Points" );
m_pRenderControlPoints->AddActionSignalTarget( this );
m_pRenderCullBounds = new vgui::CheckButton( m_pRenderPage, "RenderCullBounds", "Render Culling Bounds" );
m_pRenderCullBounds->AddActionSignalTarget( this );
m_pRenderHelpers = new vgui::CheckButton( m_pRenderPage, "RenderHelpers", "Render Helpers" );
m_pRenderHelpers->AddActionSignalTarget( this );
m_pRenderGrid = new vgui::CheckButton( m_pRenderPage, "RenderGrid", "Render Grid" );
m_pRenderGrid->AddActionSignalTarget( this );
m_pBackgroundColor = new CColorPickerButton( m_pRenderPage, "BackgroundColor", this );
m_pBackgroundColor->SetColor( m_pParticleSystemPanel->GetBackgroundColor() );
m_pLockPreview = new vgui::CheckButton( m_pRenderPage, "LockPreview", "Lock Preview System" );
m_pLockPreview->AddActionSignalTarget( this );
m_pStopEffect = new vgui::Button( m_pRenderPage, "StopEffect", "Stop Effect", this, "StopEffect" );
m_pRenderPage->LoadControlSettingsAndUserConfig( "resource/particlesystempreviewpanel_renderpage.res" );
m_pControlPointPage = new CControlPointPage( m_pControlSheet, "ControlPointPage", m_pParticleSystemPanel );
// Load layout settings; has to happen before pinning occurs in code
LoadControlSettingsAndUserConfig( "resource/particlesystempreviewpanel.res" );
// NOTE: Page adding happens *after* LoadControlSettingsAndUserConfig
// because the layout of the sheet is correct at this point.
m_pControlSheet->AddPage( m_pRenderPage, "Render" );
m_pControlSheet->AddPage( m_pControlPointPage, "Ctrl Pts" );
}
CParticleSystemPreviewPanel::~CParticleSystemPreviewPanel()
{
}
//-----------------------------------------------------------------------------
// Set the particle system to draw
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::OnThink()
{
BaseClass::OnThink();
CParticleCollection* pParticleSystem = m_pParticleSystemPanel->GetParticleSystem();
if ( !pParticleSystem )
{
m_pParticleCount->SetText( "" );
}
else
{
char buf[256];
Q_snprintf( buf, sizeof(buf), "Particle Count: %5d/%5d",
pParticleSystem->m_nActiveParticles, pParticleSystem->m_nAllocatedParticles );
m_pParticleCount->SetText( buf );
}
}
//-----------------------------------------------------------------------------
// Called when the particle system changes
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::OnParticleSystemReconstructed()
{
m_pControlPointPage->CreateControlPointControls();
}
//-----------------------------------------------------------------------------
// Set the particle system to draw
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::SetParticleSystem( CDmeParticleSystemDefinition *pDef, bool bOverrideLock )
{
bool bLocked = m_pLockPreview->IsSelected();
if ( bOverrideLock || !bLocked )
{
m_pParticleSystemPanel->SetParticleSystem( pDef );
if ( bOverrideLock && bLocked )
{
m_pLockPreview->SetSelected(false);
m_pUnlockSystem = NULL;
}
else
{
m_pUnlockSystem = pDef;
}
}
else
{
m_pUnlockSystem = pDef;
}
}
void CParticleSystemPreviewPanel::ClearParticleSystemLock()
{
m_pLockPreview->SetSelected(false);
m_pUnlockSystem = NULL;
}
void CParticleSystemPreviewPanel::SetDmeElement( CDmeParticleSystemDefinition *pDef )
{
SetParticleSystem( pDef, false );
}
//-----------------------------------------------------------------------------
// Indicates which helper to draw
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::SetParticleFunction( CDmeParticleFunction *pFunction )
{
m_pParticleSystemPanel->SetRenderedHelper( pFunction );
}
//-----------------------------------------------------------------------------
// Called when the check button is checked
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::OnCheckButtonChecked( KeyValues *pParams )
{
bool bState = pParams->GetBool( "state", false );
vgui::Panel *pPanel = (vgui::Panel*)pParams->GetPtr( "panel" );
if ( pPanel == m_pRenderGrid )
{
m_pParticleSystemPanel->RenderGrid( bState );
return;
}
if ( pPanel == m_pLockPreview )
{
if ( !m_pLockPreview->IsSelected() )
{
// unchecked the lock - switch to the latest requested selection
m_pParticleSystemPanel->SetParticleSystem( m_pUnlockSystem );
}
return;
}
if ( pPanel == m_pRenderBounds )
{
m_pParticleSystemPanel->RenderBounds( bState );
return;
}
if ( pPanel == m_pRenderCullBounds )
{
m_pParticleSystemPanel->RenderCullBounds( bState );
return;
}
if ( pPanel == m_pRenderHelpers )
{
m_pParticleSystemPanel->RenderHelpers( bState );
return;
}
if ( pPanel == m_pRenderControlPoints )
{
m_pParticleSystemPanel->RenderControlPoints( bState );
return;
}
}
//-----------------------------------------------------------------------------
// Called when a new background color is picked
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::OnBackgroundColorChanged( KeyValues *pParams )
{
m_pParticleSystemPanel->SetBackgroundColor( pParams->GetColor( "color" ) );
}
void CParticleSystemPreviewPanel::OnBackgroundColorPreview( KeyValues *pParams )
{
m_pParticleSystemPanel->SetBackgroundColor( pParams->GetColor( "color" ) );
}
void CParticleSystemPreviewPanel::OnBackgroundColorCancel( KeyValues *pParams )
{
m_pParticleSystemPanel->SetBackgroundColor( pParams->GetColor( "startingColor" ) );
}
//-----------------------------------------------------------------------------
// Called when buttons are clicked
//-----------------------------------------------------------------------------
void CParticleSystemPreviewPanel::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "StopEffect" ) )
{
m_pParticleSystemPanel->StopEffect();
return;
}
BaseClass::OnCommand( pCommand );
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,194 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: Dialog allowing users to select presets from within a preset group
//
//===========================================================================//
#include "dme_controls/presetpicker.h"
#include "tier1/keyvalues.h"
#include "tier1/utlbuffer.h"
#include "vgui/ivgui.h"
#include "vgui_controls/button.h"
#include "vgui_controls/listpanel.h"
#include "vgui_controls/splitter.h"
#include "vgui_controls/messagebox.h"
#include "movieobjects/dmeanimationset.h"
#include "datamodel/dmelement.h"
#include "matsys_controls/picker.h"
#include "dme_controls/dmecontrols_utils.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
static int __cdecl PresetNameSortFunc( vgui::ListPanel *pPanel, const vgui::ListPanelItem &item1, const vgui::ListPanelItem &item2 )
{
const char *string1 = item1.kv->GetString( "name" );
const char *string2 = item2.kv->GetString( "name" );
return Q_stricmp( string1, string2 );
}
CPresetPickerFrame::CPresetPickerFrame( vgui::Panel *pParent, const char *pTitle, bool bAllowMultiSelect ) :
BaseClass( pParent, "PresetPickerFrame" )
{
SetDeleteSelfOnClose( true );
m_pContextKeyValues = NULL;
m_pPresetList = new vgui::ListPanel( this, "PresetList" );
m_pPresetList->AddColumnHeader( 0, "name", "Preset Name", 52, 0 );
m_pPresetList->SetSelectIndividualCells( false );
m_pPresetList->SetMultiselectEnabled( bAllowMultiSelect );
m_pPresetList->SetEmptyListText( "No presets" );
m_pPresetList->AddActionSignalTarget( this );
m_pPresetList->SetSortFunc( 0, PresetNameSortFunc );
m_pPresetList->SetSortColumn( 0 );
m_pOpenButton = new vgui::Button( this, "OkButton", "#MessageBox_OK", this, "Ok" );
m_pCancelButton = new vgui::Button( this, "CancelButton", "#MessageBox_Cancel", this, "Cancel" );
SetBlockDragChaining( true );
LoadControlSettingsAndUserConfig( "resource/presetpicker.res" );
SetTitle( pTitle, false );
}
CPresetPickerFrame::~CPresetPickerFrame()
{
CleanUpMessage();
}
//-----------------------------------------------------------------------------
// Refreshes the list of presets
//-----------------------------------------------------------------------------
void CPresetPickerFrame::RefreshPresetList( CDmElement *pPresetGroup, bool bSelectAll )
{
m_pPresetList->RemoveAll();
const CDmrElementArray< CDmePreset > presets( pPresetGroup, "presets" );
if ( !presets.IsValid() )
return;
int nCount = presets.Count();
if ( nCount == 0 )
return;
for ( int i = 0; i < nCount; ++i )
{
CDmePreset *pPreset = presets[i];
const char *pName = pPreset->GetName();
if ( !pName || !pName[0] )
{
pName = "<no name>";
}
KeyValues *kv = new KeyValues( "node" );
kv->SetString( "name", pName );
SetElementKeyValue( kv, "preset", pPreset );
int nItemID = m_pPresetList->AddItem( kv, 0, false, false );
if ( bSelectAll )
{
m_pPresetList->AddSelectedItem( nItemID );
}
}
m_pPresetList->SortList();
}
//-----------------------------------------------------------------------------
// Deletes the message
//-----------------------------------------------------------------------------
void CPresetPickerFrame::CleanUpMessage()
{
if ( m_pContextKeyValues )
{
m_pContextKeyValues->deleteThis();
m_pContextKeyValues = NULL;
}
}
//-----------------------------------------------------------------------------
// Sets the current scene + animation list
//-----------------------------------------------------------------------------
void CPresetPickerFrame::DoModal( CDmElement *pPresetGroup, bool bSelectAll, KeyValues *pContextKeyValues )
{
CleanUpMessage();
RefreshPresetList( pPresetGroup, bSelectAll );
m_pContextKeyValues = pContextKeyValues;
BaseClass::DoModal();
}
//-----------------------------------------------------------------------------
// On command
//-----------------------------------------------------------------------------
void CPresetPickerFrame::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "Ok" ) )
{
int nSelectedItemCount = m_pPresetList->GetSelectedItemsCount();
if ( nSelectedItemCount == 0 )
return;
KeyValues *pActionKeys = new KeyValues( "PresetPicked" );
if ( m_pPresetList->IsMultiselectEnabled() )
{
pActionKeys->SetInt( "count", nSelectedItemCount );
// Adds them in selection order
for ( int i = 0; i < nSelectedItemCount; ++i )
{
char pBuf[32];
Q_snprintf( pBuf, sizeof(pBuf), "%d", i );
int nItemID = m_pPresetList->GetSelectedItem( i );
KeyValues *pKeyValues = m_pPresetList->GetItem( nItemID );
CDmePreset *pPreset = GetElementKeyValue<CDmePreset>( pKeyValues, "preset" );
SetElementKeyValue( pActionKeys, pBuf, pPreset );
}
}
else
{
int nItemID = m_pPresetList->GetSelectedItem( 0 );
KeyValues *pKeyValues = m_pPresetList->GetItem( nItemID );
CDmePreset *pPreset = GetElementKeyValue<CDmePreset>( pKeyValues, "preset" );
SetElementKeyValue( pActionKeys, "preset", pPreset );
}
if ( m_pContextKeyValues )
{
pActionKeys->AddSubKey( m_pContextKeyValues );
// This prevents them from being deleted later
m_pContextKeyValues = NULL;
}
PostActionSignal( pActionKeys );
CloseModal();
return;
}
if ( !Q_stricmp( pCommand, "Cancel" ) )
{
KeyValues *pActionKeys = new KeyValues( "PresetPickCancelled" );
if ( m_pContextKeyValues )
{
pActionKeys->AddSubKey( m_pContextKeyValues );
// This prevents them from being deleted later
m_pContextKeyValues = NULL;
}
PostActionSignal( pActionKeys );
CloseModal();
return;
}
BaseClass::OnCommand( pCommand );
}

View File

@@ -0,0 +1,89 @@
//======= Copyright (c) 1996-2009, Valve Corporation, All rights reserved. ======
//
// CSheetEditorPanel - Tool panel for editing sprite sheet information
//
//===============================================================================
#include "dme_controls/sheeteditorpanel.h"
#include "dme_controls/dmepanel.h"
#include "movieobjects/dmeparticlesystemdefinition.h"
#include "materialsystem/imesh.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include "vguimatsurface/imatsystemsurface.h"
#include "matsys_controls/matsyscontrols.h"
#include "vgui/ivgui.h"
#include "vgui_controls/propertypage.h"
#include "vgui_controls/propertysheet.h"
#include "vgui_controls/textentry.h"
#include "vgui_controls/splitter.h"
#include "vgui_controls/checkbutton.h"
#include "matsys_controls/colorpickerpanel.h"
#include "particles/particles.h"
#include "tier1/keyvalues.h"
#include "tier1/utlbuffer.h"
#include "tier2/renderutils.h"
#include "bitmap/psheet.h"
#include "matsys_controls/vmtpicker.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// CSheetEditorPanel
//
//-----------------------------------------------------------------------------
//IMPLEMENT_DMEPANEL_FACTORY( CParticleSystemDmePanel, DmeParticleSystemDefinition, "DmeParticleSystemDefinitionEditor", "Particle System Editor", true );
CSheetEditorPanel::CSheetEditorPanel( vgui::Panel *pParent, const char *pName ) :
BaseClass( pParent, pName ),
m_pSheetInfo(NULL)
{
m_pTitleLabel = new vgui::Label( this, "TestLabel", "<Title>" );
m_pTitleLabel->SetPinCorner( Panel::PIN_TOPLEFT, 12, 12 );
m_pTitleLabel->SetWide( 400 );
m_pVMTPicker = new CVMTPicker( this, "SheetPreview" );
m_pVMTPicker->SetAutoResize( Panel::PIN_TOPLEFT, Panel::AUTORESIZE_DOWNANDRIGHT, 200, 42, -12, -12 );
}
void CSheetEditorPanel::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
m_pTitleLabel->SetBgColor( Color( 200, 200, 200, 255 ) );
m_pTitleLabel->SetFgColor( Color( 0, 0, 0, 255 ) );
SetBgColor( Color( 100, 200, 100, 255 ) );
}
CSheetEditorPanel::~CSheetEditorPanel()
{
}
void CSheetEditorPanel::SetParticleSystem( CDmeParticleSystemDefinition *pParticleSystem )
{
char strBuffer[ 256 ];
const char *pSystemName = "<no system>";
const char *pVMTName = "<no vmt>";
if ( pParticleSystem != NULL )
{
pSystemName = pParticleSystem->GetName();
if ( !pSystemName || !pSystemName[0] )
{
pSystemName = "<no name>";
}
}
if ( pParticleSystem != NULL )
{
pVMTName = pParticleSystem->GetValueString( "material" );
}
Q_snprintf( strBuffer, sizeof(strBuffer), "%s: %s", pSystemName, pVMTName );
m_pTitleLabel->SetText( strBuffer );
}

View File

@@ -0,0 +1,609 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include <windows.h>
#undef PropertySheet
#include "filesystem.h"
#include "dme_controls/soundpicker.h"
#include "tier1/keyvalues.h"
#include "vgui_controls/ListPanel.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/PropertySheet.h"
#include "vgui_controls/PropertyPage.h"
#include "dme_controls/filtercombobox.h"
#include "vgui/isurface.h"
#include "vgui/iinput.h"
#include "dme_controls/dmecontrols.h"
#include "soundemittersystem/isoundemittersystembase.h"
#include "mathlib/mathlib.h"
#include "soundchars.h"
#include "tier1/fmtstr.h"
// FIXME: Move sound code out of the engine + into a library!
#include "toolframework/ienginetool.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Sound Picker
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Sort by sound name
//-----------------------------------------------------------------------------
static int __cdecl GameSoundSortFunc( vgui::ListPanel *pPanel, const ListPanelItem &item1, const ListPanelItem &item2 )
{
bool bRoot1 = item1.kv->GetInt("root") != 0;
bool bRoot2 = item2.kv->GetInt("root") != 0;
if ( bRoot1 != bRoot2 )
return bRoot1 ? -1 : 1;
const char *string1 = item1.kv->GetString("gamesound");
const char *string2 = item2.kv->GetString("gamesound");
return Q_stricmp( string1, string2 );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CSoundPicker::CSoundPicker( vgui::Panel *pParent, int nFlags ) :
BaseClass( pParent, "Sound Files", "wav", "sound", "wavName" )
{
m_nSoundSuppressionCount = 0;
m_nPlayingSound = 0;
// Connection problem if this failed
Assert( SoundEmitterSystem() );
m_pViewsSheet = new vgui::PropertySheet( this, "ViewsSheet" );
m_pViewsSheet->AddActionSignalTarget( this );
// game sounds
m_pGameSoundPage = NULL;
m_pGameSoundList = NULL;
if ( nFlags & PICK_GAMESOUNDS )
{
m_pGameSoundPage = new PropertyPage( m_pViewsSheet, "GameSoundPage" );
m_pGameSoundList = new ListPanel( m_pGameSoundPage, "GameSoundsList" );
m_pGameSoundList->AddColumnHeader( 0, "GameSound", "Game Sound", 52, 0 );
m_pGameSoundList->AddActionSignalTarget( this );
m_pGameSoundList->SetSelectIndividualCells( true );
m_pGameSoundList->SetEmptyListText("No game sounds");
m_pGameSoundList->SetDragEnabled( true );
m_pGameSoundList->SetAutoResize( Panel::PIN_TOPLEFT, Panel::AUTORESIZE_DOWNANDRIGHT, 0, 0, 0, 0 );
m_pGameSoundList->SetSortFunc( 0, GameSoundSortFunc );
m_pGameSoundList->SetSortColumn( 0 );
m_pGameSoundList->SetMultiselectEnabled( ( nFlags & ALLOW_MULTISELECT ) != 0 );
// filter selection
m_pGameSoundFilter = new TextEntry( m_pGameSoundPage, "GameSoundFilter" );
m_pGameSoundFilter->AddActionSignalTarget( this );
m_pGameSoundPage->LoadControlSettings( "resource/soundpickergamesoundpage.res" );
m_pViewsSheet->AddPage( m_pGameSoundPage, "Game Sounds" );
}
// wav files
m_pWavPage = NULL;
if ( nFlags & PICK_WAVFILES )
{
m_pWavPage = new PropertyPage( m_pViewsSheet, "WavPage" );
bool bAllowMultiselect = ( nFlags & ALLOW_MULTISELECT ) != 0;
CreateStandardControls( m_pWavPage, bAllowMultiselect );
AddExtension( "mp3" );
m_pWavPage->LoadControlSettings( "resource/soundpickerwavpage.res" );
m_pViewsSheet->AddPage( m_pWavPage, "WAVs" );
}
LoadControlSettings( "resource/soundpicker.res" );
}
//-----------------------------------------------------------------------------
// Purpose: called to open
//-----------------------------------------------------------------------------
void CSoundPicker::Activate()
{
BaseClass::Activate();
if ( m_pGameSoundPage )
{
BuildGameSoundList();
}
}
//-----------------------------------------------------------------------------
// Sets the current sound choice
//-----------------------------------------------------------------------------
void CSoundPicker::SetSelectedSound( PickType_t type, const char *pSoundName )
{
if ( type == PICK_NONE || !pSoundName )
return;
if ( m_pGameSoundPage && ( type == PICK_GAMESOUNDS ) )
{
m_pViewsSheet->SetActivePage( m_pGameSoundPage );
m_pGameSoundFilter->SetText( pSoundName );
}
if ( m_pWavPage && ( type == PICK_WAVFILES ) )
{
m_pViewsSheet->SetActivePage( m_pWavPage );
SetInitialSelection( pSoundName );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CSoundPicker::OnKeyCodeTyped( KeyCode code )
{
if ( m_pGameSoundPage && ( m_pViewsSheet->GetActivePage() == m_pGameSoundPage ) )
{
if (( code == KEY_UP ) || ( code == KEY_DOWN ) || ( code == KEY_PAGEUP ) || ( code == KEY_PAGEDOWN ))
{
KeyValues *pMsg = new KeyValues( "KeyCodeTyped", "code", code );
vgui::ipanel()->SendMessage( m_pGameSoundList->GetVPanel(), pMsg, GetVPanel() );
pMsg->deleteThis();
return;
}
}
BaseClass::OnKeyCodeTyped( code );
}
//-----------------------------------------------------------------------------
// Purpose: builds the gamesound list
//-----------------------------------------------------------------------------
bool CSoundPicker::IsGameSoundVisible( int hGameSound )
{
const char *pSoundName = SoundEmitterSystem()->GetSoundName( hGameSound );
return ( !m_GameSoundFilter.Length() || Q_stristr( pSoundName, m_GameSoundFilter.Get() ) );
}
//-----------------------------------------------------------------------------
// Updates the column header in the chooser
//-----------------------------------------------------------------------------
void CSoundPicker::UpdateGameSoundColumnHeader( int nMatchCount, int nTotalCount )
{
char pColumnTitle[512];
Q_snprintf( pColumnTitle, sizeof(pColumnTitle), "%s (%d/%d)",
"Game Sound", nMatchCount, nTotalCount );
m_pGameSoundList->SetColumnHeaderText( 0, pColumnTitle );
}
//-----------------------------------------------------------------------------
// Purpose: builds the gamesound list
//-----------------------------------------------------------------------------
void CSoundPicker::BuildGameSoundList()
{
if ( !m_pGameSoundList )
return;
m_pGameSoundList->RemoveAll();
int nTotalCount = 0;
int i = SoundEmitterSystem()->First();
while ( i != SoundEmitterSystem()->InvalidIndex() )
{
const char *pSoundName = SoundEmitterSystem()->GetSoundName( i );
bool bInRoot = !strchr( pSoundName, '\\' ) && !strchr( pSoundName, '/' );
KeyValues *kv = new KeyValues( "node", "gamesound", pSoundName );
kv->SetInt( "gameSoundHandle", i );
kv->SetInt( "root", bInRoot );
int nItemID = m_pGameSoundList->AddItem( kv, 0, false, false );
m_pGameSoundList->SetItemVisible( nItemID, IsGameSoundVisible( i ) );
KeyValues *pDrag = new KeyValues( "drag", "text", pSoundName );
pDrag->SetString( "texttype", "gamesoundName" );
m_pGameSoundList->SetItemDragData( nItemID, pDrag );
++nTotalCount;
i = SoundEmitterSystem()->Next( i );
}
m_pGameSoundList->SortList();
if ( m_pGameSoundList->GetItemCount() > 0 )
{
int nItemID = m_pGameSoundList->GetItemIDFromRow( 0 );
// This prevents the refreshing of the sound list from playing the sound
++m_nSoundSuppressionCount;
m_pGameSoundList->SetSelectedCell( nItemID, 0 );
}
UpdateGameSoundColumnHeader( nTotalCount, nTotalCount );
}
//-----------------------------------------------------------------------------
// Purpose: refreshes the gamesound list
//-----------------------------------------------------------------------------
void CSoundPicker::RefreshGameSoundList()
{
if ( !m_pGameSoundList )
return;
// Check the filter matches
int nMatchingGameSounds = 0;
int nTotalCount = 0;
for ( int nItemID = m_pGameSoundList->FirstItem(); nItemID != m_pGameSoundList->InvalidItemID(); nItemID = m_pGameSoundList->NextItem( nItemID ) )
{
KeyValues *kv = m_pGameSoundList->GetItem( nItemID );
int hGameSound = kv->GetInt( "gameSoundHandle", SoundEmitterSystem()->InvalidIndex() );
if ( hGameSound == SoundEmitterSystem()->InvalidIndex() )
continue;
bool bIsVisible = IsGameSoundVisible( hGameSound );
m_pGameSoundList->SetItemVisible( nItemID, bIsVisible );
if ( bIsVisible )
{
++nMatchingGameSounds;
}
++nTotalCount;
}
UpdateGameSoundColumnHeader( nMatchingGameSounds, nTotalCount );
if ( ( m_pGameSoundList->GetSelectedItemsCount() == 0 ) && ( m_pGameSoundList->GetItemCount() > 0 ) )
{
int nItemID = m_pGameSoundList->GetItemIDFromRow( 0 );
// This prevents the refreshing of the sound list from playing the sound
++m_nSoundSuppressionCount;
m_pGameSoundList->SetSelectedCell( nItemID, 0 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Update filter when text changes
//-----------------------------------------------------------------------------
void CSoundPicker::OnGameSoundFilterTextChanged( )
{
int nLength = m_pGameSoundFilter->GetTextLength();
m_GameSoundFilter.SetLength( nLength );
if ( nLength > 0 )
{
m_pGameSoundFilter->GetText( m_GameSoundFilter.Get(), nLength+1 );
}
RefreshGameSoundList();
}
//-----------------------------------------------------------------------------
// Purpose: refreshes dialog on filter changing
//-----------------------------------------------------------------------------
void CSoundPicker::OnTextChanged( KeyValues *pKeyValues )
{
vgui::Panel *pSource = (vgui::Panel*)pKeyValues->GetPtr( "panel" );
if ( pSource == m_pGameSoundFilter )
{
OnGameSoundFilterTextChanged();
return;
}
BaseClass::OnTextChanged( pKeyValues );
}
//-----------------------------------------------------------------------------
// Purpose: Called when a page is shown
//-----------------------------------------------------------------------------
void CSoundPicker::RequestGameSoundFilterFocus( )
{
m_pGameSoundFilter->SelectAllOnFirstFocus( true );
m_pGameSoundFilter->RequestFocus();
}
//-----------------------------------------------------------------------------
// Purpose: Called when a page is shown
//-----------------------------------------------------------------------------
void CSoundPicker::OnPageChanged( )
{
StopSoundPreview();
if ( m_pGameSoundPage && ( m_pViewsSheet->GetActivePage() == m_pGameSoundPage ) )
{
RequestGameSoundFilterFocus();
}
if ( m_pWavPage && ( m_pViewsSheet->GetActivePage() == m_pWavPage ) )
{
RequestFilterFocus();
}
}
//-----------------------------------------------------------------------------
// Stop sound preview
//-----------------------------------------------------------------------------
void CSoundPicker::StopSoundPreview( )
{
if ( m_nPlayingSound != 0 )
{
EngineTool()->StopSoundByGuid( m_nPlayingSound );
m_nPlayingSound = 0;
}
}
//-----------------------------------------------------------------------------
// Plays a gamesound
//-----------------------------------------------------------------------------
void CSoundPicker::PlayGameSound( const char *pSoundName )
{
StopSoundPreview();
CSoundParameters params;
if ( SoundEmitterSystem()->GetParametersForSound( pSoundName, params, GENDER_NONE ) )
{
m_nPlayingSound = EngineTool()->StartSound( 0, true, -1, CHAN_STATIC, params.soundname,
params.volume, params.soundlevel, vec3_origin, vec3_origin, 0,
params.pitch, false, params.delay_msec / 1000.0f );
}
}
//-----------------------------------------------------------------------------
// Plays a wav file
//-----------------------------------------------------------------------------
void CSoundPicker::PlayWavSound( const char *pSoundName )
{
StopSoundPreview();
if ( pSoundName[ 0 ] )
{
EngineTool()->ValidateSoundCache( CFmtStr( "sound\\%s", PSkipSoundChars( pSoundName ) ) );
m_nPlayingSound = EngineTool()->StartSound( 0, true, -1, CHAN_STATIC, pSoundName,
VOL_NORM, SNDLVL_NONE, vec3_origin, vec3_origin, 0, PITCH_NORM, false, 0 );
}
}
//-----------------------------------------------------------------------------
// Don't play a sound when the next selection is a default selection
//-----------------------------------------------------------------------------
void CSoundPicker::OnNextSelectionIsDefault()
{
++m_nSoundSuppressionCount;
}
//-----------------------------------------------------------------------------
// Derived classes have this called when the previewed asset changes
//-----------------------------------------------------------------------------
void CSoundPicker::OnSelectedAssetPicked( const char *pAssetName )
{
bool bPlaySounds = true;
if ( m_nSoundSuppressionCount > 0 )
{
--m_nSoundSuppressionCount;
bPlaySounds = false;
}
if ( pAssetName && bPlaySounds )
{
PlayWavSound( pAssetName );
}
}
//-----------------------------------------------------------------------------
// Purpose: refreshes dialog on text changing
//-----------------------------------------------------------------------------
void CSoundPicker::OnItemSelected( KeyValues *kv )
{
Panel *pPanel = (Panel *)kv->GetPtr( "panel", NULL );
if ( m_pGameSoundList && (pPanel == m_pGameSoundList ) )
{
bool bPlaySounds = true;
if ( m_nSoundSuppressionCount > 0 )
{
--m_nSoundSuppressionCount;
bPlaySounds = false;
}
const char *pGameSoundName = GetSelectedSoundName();
if ( pGameSoundName && bPlaySounds )
{
int len = V_strlen( pGameSoundName );
char *soundname = ( char* )stackalloc( len + 2 );
soundname[ 0 ] = '#'; // mark sound to bypass the dsp
V_strncpy( soundname + 1, pGameSoundName, len + 1 );
PlayGameSound( soundname );
}
return;
}
BaseClass::OnItemSelected( kv );
}
//-----------------------------------------------------------------------------
// Gets the selected sound type
//-----------------------------------------------------------------------------
CSoundPicker::PickType_t CSoundPicker::GetSelectedSoundType( )
{
if ( m_pGameSoundPage && ( m_pViewsSheet->GetActivePage() == m_pGameSoundPage ) )
return PICK_GAMESOUNDS;
if ( m_pWavPage && ( m_pViewsSheet->GetActivePage() == m_pWavPage ) )
return PICK_WAVFILES;
return PICK_NONE;
}
//-----------------------------------------------------------------------------
// Returns the selected sound count
//-----------------------------------------------------------------------------
int CSoundPicker::GetSelectedSoundCount()
{
if ( m_pGameSoundPage && ( m_pViewsSheet->GetActivePage() == m_pGameSoundPage ) )
return m_pGameSoundList->GetSelectedItemsCount();
if ( m_pWavPage && ( m_pViewsSheet->GetActivePage() == m_pWavPage ) )
return GetSelectedAssetCount();
return 0;
}
//-----------------------------------------------------------------------------
// Returns the selected sound
//-----------------------------------------------------------------------------
const char *CSoundPicker::GetSelectedSoundName( int nSelectionIndex )
{
if ( m_pGameSoundPage && ( m_pViewsSheet->GetActivePage() == m_pGameSoundPage ) )
{
int nCount = m_pGameSoundList->GetSelectedItemsCount();
if ( nCount == 0 )
return NULL;
if ( nSelectionIndex < 0 )
{
nSelectionIndex = nCount - 1;
}
int nIndex = m_pGameSoundList->GetSelectedItem( nSelectionIndex );
if ( nIndex >= 0 )
{
KeyValues *pkv = m_pGameSoundList->GetItem( nIndex );
return pkv->GetString( "gamesound", NULL );
}
return NULL;
}
if ( m_pWavPage && ( m_pViewsSheet->GetActivePage() == m_pWavPage ) )
return GetSelectedAsset( nSelectionIndex );
return NULL;
}
//-----------------------------------------------------------------------------
//
// Purpose: Modal picker frame
//
//-----------------------------------------------------------------------------
CSoundPickerFrame::CSoundPickerFrame( vgui::Panel *pParent, const char *pTitle, int nFlags ) :
BaseClass( pParent )
{
SetAssetPicker( new CSoundPicker( this, nFlags ) );
LoadControlSettingsAndUserConfig( "resource/soundpickerframe.res" );
SetTitle( pTitle, false );
}
CSoundPickerFrame::~CSoundPickerFrame()
{
}
void CSoundPickerFrame::OnClose()
{
CSoundPicker *pPicker = static_cast <CSoundPicker*>( GetAssetPicker() );
pPicker->StopSoundPreview();
BaseClass::OnClose();
}
//-----------------------------------------------------------------------------
// Purpose: Activate the dialog
//-----------------------------------------------------------------------------
void CSoundPickerFrame::DoModal( CSoundPicker::PickType_t initialType, const char *pInitialValue, KeyValues *pContextKeyValues )
{
vgui::surface()->SetCursor( dc_hourglass );
CSoundPicker *pPicker = static_cast <CSoundPicker*>( GetAssetPicker() );
if ( initialType != CSoundPicker::PICK_NONE && pInitialValue )
{
pPicker->SetSelectedSound( initialType, pInitialValue );
}
BaseClass::DoModal( pContextKeyValues );
}
//-----------------------------------------------------------------------------
// On command
//-----------------------------------------------------------------------------
void CSoundPickerFrame::OnCommand( const char *pCommand )
{
CSoundPicker *pPicker = static_cast <CSoundPicker*>( GetAssetPicker() );
if ( !Q_stricmp( pCommand, "Open" ) )
{
CSoundPicker::PickType_t type = pPicker->GetSelectedSoundType( );
if (( type == CSoundPicker::PICK_GAMESOUNDS ) || ( type == CSoundPicker::PICK_WAVFILES ))
{
const char *pSoundName = pPicker->GetSelectedSoundName();
if ( !pSoundName )
{
CloseModal();
return;
}
int len = V_strlen( pSoundName );
char *soundname = ( char* )stackalloc( len + 2 );
soundname[ 0 ] = '#'; // mark sound to bypass the dsp
V_strncpy( soundname + 1, pSoundName, len + 1 );
int nSoundCount = pPicker->GetSelectedSoundCount();
KeyValues *pActionKeys = new KeyValues( "SoundSelected" );
pActionKeys->SetInt( "count", nSoundCount );
KeyValues *pSoundList = NULL;
if ( type == CSoundPicker::PICK_GAMESOUNDS )
{
pActionKeys->SetString( "gamesound", soundname );
if ( pPicker->IsMultiselectEnabled() )
{
pSoundList = pActionKeys->FindKey( "gamesounds", true );
}
}
else
{
pActionKeys->SetString( "wav", soundname );
if ( pPicker->IsMultiselectEnabled() )
{
pSoundList = pActionKeys->FindKey( "wavs", true );
}
}
if ( pSoundList )
{
// Adds them in selection order
for ( int i = 0; i < nSoundCount; ++i )
{
char pBuf[32];
Q_snprintf( pBuf, sizeof(pBuf), "%d", i );
const char *pSoundName = pPicker->GetSelectedSoundName( i );
int len = V_strlen( pSoundName );
char *soundname = ( char* )stackalloc( len + 2 );
soundname[ 0 ] = '#'; // mark sound to bypass the dsp
V_strncpy( soundname + 1, pSoundName, len + 1 );
pSoundList->SetString( pBuf, soundname );
}
}
PostMessageAndClose( pActionKeys );
CloseModal();
}
return;
}
BaseClass::OnCommand( pCommand );
}

View File

@@ -0,0 +1,212 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#include "dme_controls/soundrecordpanel.h"
#include "filesystem.h"
#include "tier1/keyvalues.h"
#include "vgui_controls/Button.h"
#include "vgui_controls/TextEntry.h"
#include "dme_controls/dmecontrols.h"
#include "vgui_controls/messagebox.h"
#include "soundemittersystem/isoundemittersystembase.h"
#include "vgui/ivgui.h"
#include "mathlib/mathlib.h"
// FIXME: Move sound code out of the engine + into a library!
#include "toolframework/ienginetool.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//-----------------------------------------------------------------------------
//
// Sound Record Dialog
//
//-----------------------------------------------------------------------------
CSoundRecordPanel::CSoundRecordPanel( vgui::Panel *pParent, const char *pTitle ) :
BaseClass( pParent, "SoundRecordPanel" )
{
m_bIsRecording = false;
m_nPlayingSound = 0;
SetDeleteSelfOnClose( true );
m_pOkButton = new Button( this, "OkButton", "#FileOpenDialog_Open", this, "Ok" );
m_pCancelButton = new Button( this, "CancelButton", "#FileOpenDialog_Cancel", this, "Cancel" );
m_pPlayButton = new Button( this, "PlayButton", "Play", this, "Play" );
m_pRecordButton = new Button( this, "Record", "Record", this, "ToggleRecord" );
m_pRecordTime = new TextEntry( this, "RecordTime" );
m_pFileName = new TextEntry( this, "FileName" );
LoadControlSettingsAndUserConfig( "resource/soundrecordpanel.res" );
SetTitle( pTitle, false );
}
CSoundRecordPanel::~CSoundRecordPanel()
{
StopSoundPreview();
}
//-----------------------------------------------------------------------------
// Purpose: Activate the dialog
//-----------------------------------------------------------------------------
void CSoundRecordPanel::DoModal( const char *pFileName )
{
Assert( EngineTool() );
char pRelativeWAVPath[MAX_PATH];
g_pFullFileSystem->FullPathToRelativePath( pFileName, pRelativeWAVPath, sizeof(pRelativeWAVPath) );
// Check to see if this file is not hidden owing to search paths
bool bBadDirectory = false;
char pRelativeDir[MAX_PATH];
Q_strncpy( pRelativeDir, pRelativeWAVPath, sizeof( pRelativeDir ) );
Q_StripFilename( pRelativeDir );
char pFoundFullPath[MAX_PATH];
g_pFullFileSystem->RelativePathToFullPath( pRelativeDir, "MOD", pFoundFullPath, sizeof( pFoundFullPath ) );
if ( StringHasPrefix( pFileName, pFoundFullPath ) )
{
// Strip 'sound/' prefix
m_FileName = pRelativeWAVPath;
const char *pSoundName = StringAfterPrefix( pRelativeWAVPath, "sound\\" );
if ( !pSoundName )
{
pSoundName = pRelativeWAVPath;
bBadDirectory = true;
}
m_EngineFileName = pSoundName;
}
else
{
bBadDirectory = true;
}
if ( bBadDirectory )
{
char pBuf[1024];
Q_snprintf( pBuf, sizeof(pBuf), "File %s is in a bad directory!\nAudio must be recorded into your mod's sound/ directory.\n", pFileName );
vgui::MessageBox *pMessageBox = new vgui::MessageBox( "Bad Save Directory!\n", pBuf, GetParent() );
pMessageBox->DoModal( );
return;
}
m_pFileName->SetText( pFileName );
m_pOkButton->SetEnabled( false );
m_pPlayButton->SetEnabled( false );
BaseClass::DoModal();
}
//-----------------------------------------------------------------------------
// Stop sound preview
//-----------------------------------------------------------------------------
void CSoundRecordPanel::StopSoundPreview( )
{
if ( m_nPlayingSound != 0 )
{
EngineTool()->StopSoundByGuid( m_nPlayingSound );
m_nPlayingSound = 0;
}
}
//-----------------------------------------------------------------------------
// Plays a wav file
//-----------------------------------------------------------------------------
void CSoundRecordPanel::PlaySoundPreview( )
{
StopSoundPreview();
m_nPlayingSound = EngineTool()->StartSound( 0, true, -1, CHAN_STATIC, m_EngineFileName,
VOL_NORM, SNDLVL_NONE, vec3_origin, vec3_origin, 0, PITCH_NORM, false, 0 );
}
//-----------------------------------------------------------------------------
// Updates sound record time during recording
//-----------------------------------------------------------------------------
void CSoundRecordPanel::UpdateTimeRecorded()
{
float flTime = Plat_FloatTime() - m_flRecordStartTime;
char pTimeBuf[64];
Q_snprintf( pTimeBuf, sizeof(pTimeBuf), "%.3f", flTime );
m_pRecordTime->SetText( pTimeBuf );
}
//-----------------------------------------------------------------------------
// Updates sound record time during recording
//-----------------------------------------------------------------------------
void CSoundRecordPanel::OnTick()
{
BaseClass::OnTick();
// Update the amount of time recorded
UpdateTimeRecorded();
}
//-----------------------------------------------------------------------------
// On command
//-----------------------------------------------------------------------------
void CSoundRecordPanel::OnCommand( const char *pCommand )
{
if ( !Q_stricmp( pCommand, "ToggleRecord" ) )
{
if ( !m_bIsRecording )
{
StopSoundPreview();
g_pFullFileSystem->RemoveFile( m_FileName, "MOD" );
EngineTool()->StartRecordingVoiceToFile( m_FileName, "MOD" );
m_pRecordButton->SetText( "Stop Recording" );
m_pPlayButton->SetEnabled( false );
m_pOkButton->SetEnabled( false );
m_pCancelButton->SetEnabled( true );
m_flRecordStartTime = Plat_FloatTime();
vgui::ivgui()->AddTickSignal( GetVPanel(), 0 );
}
else
{
EngineTool()->StopRecordingVoiceToFile();
EngineTool()->ReloadSound( m_EngineFileName );
ivgui()->RemoveTickSignal( GetVPanel() );
UpdateTimeRecorded();
m_pOkButton->SetEnabled( true );
m_pCancelButton->SetEnabled( true );
m_pPlayButton->SetEnabled( true );
m_pRecordButton->SetText( "Record" );
}
m_bIsRecording = !m_bIsRecording;
return;
}
if ( !Q_stricmp( pCommand, "Play" ) )
{
PlaySoundPreview();
return;
}
if ( !Q_stricmp( pCommand, "Ok" ) )
{
PostActionSignal( new KeyValues( "SoundRecorded", "relativepath", m_EngineFileName.Get() ) );
CloseModal();
return;
}
if ( !Q_stricmp( pCommand, "Cancel" ) )
{
g_pFullFileSystem->RemoveFile( m_FileName, "MOD" );
CloseModal();
return;
}
BaseClass::OnCommand( pCommand );
}

View File

@@ -0,0 +1,820 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "gamelayer.h"
#include "gamerect.h"
#include "tier1/keyvalues.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include "tier1/utlbuffer.h"
#include "tier2/tier2.h"
#include "filesystem.h"
#include "rendersystem/irendercontext.h"
#include "tier2/fileutils.h"
#include "gameuisystemsurface.h"
#include "gameuidefinition.h"
#include "tier1/fmtstr.h"
#include "gamerect.h"
#include "gametext.h"
#include "hitarea.h"
#include "graphicgroup.h"
#include "dynamicrect.h"
#include "gameuiscript.h"
#include "gameuisystemmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DMXELEMENT_UNPACK ( CGameLayer )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
END_DMXELEMENT_UNPACK( CGameLayer, s_GameLayerUnpack )
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameLayer::CGameLayer( SublayerTypes_t layerType )
{
m_pName = "";
m_LayerType = layerType;
m_pTextureName = "";
m_hTexture = RENDER_TEXTURE_HANDLE_INVALID;
m_Material = NULL;
m_Sheet = NULL;
m_SheetSymbol = UTL_INVAL_SYMBOL;
m_bSheetSymbolCached = false;
}
//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
CGameLayer::~CGameLayer()
{
if ( m_Material.IsValid() )
{
m_Material.Shutdown( true );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::Shutdown()
{
int nGraphicsCount = m_LayerGraphics.Count();
for ( int j = 0; j < nGraphicsCount; ++j )
{
Assert( !m_LayerGraphics[j]->IsGroup() );
delete m_LayerGraphics[j];
m_LayerGraphics[j] = NULL;
}
m_LayerGraphics.RemoveAll();
}
//-----------------------------------------------------------------------------
// Load data from dmx file
//-----------------------------------------------------------------------------
bool CGameLayer::Unserialize( CDmxElement *pLayer, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping )
{
pLayer->UnpackIntoStructure( this, s_GameLayerUnpack );
// Static graphics
if ( m_LayerType == SUBLAYER_STATIC )
{
CDmxAttribute *pGraphics = pLayer->GetAttribute( "staticGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphics->GetArray< CDmxElement * >( );
int nCount = graphics.Count();
for ( int i = 0; i < nCount; ++i )
{
// What kind of graphic is this?
const char *pType = graphics[i]->GetValueString( "classtype" );
if ( !Q_stricmp( pType, "CDmeRectGeometry" ) )
{
CGameRect *pGraphic = new CGameRect( "" );
if ( !pGraphic->Unserialize( graphics[i] ) )
{
delete pGraphic;
return false;
}
m_LayerGraphics.AddToTail( pGraphic );
char pBuf[255];
UniqueIdToString( graphics[i]->GetId(), pBuf, 255 );
unserializedGraphicMapping.Insert( pBuf, pGraphic );
}
else if ( !Q_stricmp( pType, "CDmeHitAreaGeometry" ) )
{
CHitArea *pGraphic = new CHitArea( "" );
if ( !pGraphic->Unserialize( graphics[i] ) )
{
delete pGraphic;
return false;
}
m_LayerGraphics.AddToTail( pGraphic );
char pBuf[255];
UniqueIdToString( graphics[i]->GetId(), pBuf, 255 );
unserializedGraphicMapping.Insert( pBuf, pGraphic );
}
else
{
Warning( "CGameUIDefinition: Warning unknown static graphic type\n" );
}
}
CDmxAttribute *pTextureName = pLayer->GetAttribute( "statictexture" );
if ( !pTextureName || pTextureName->GetType() != AT_STRING )
{
return false;
}
char textureName[128];
pTextureName->GetValueAsString( textureName, 128 );
InitSheetTexture( textureName );
}
// Dynamic graphics
else if ( m_LayerType == SUBLAYER_DYNAMIC )
{
CDmxAttribute *pGraphicsAttr = pLayer->GetAttribute( "dynamicGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphicsAttr->GetArray< CDmxElement * >( );
for ( int i = 0; i < graphics.Count(); ++i )
{
// What kind of graphic is this?
const char *pType = graphics[i]->GetValueString( "classtype" );
if ( !Q_stricmp( pType, "CDmeDynamicRectGeometry" ) )
{
CDynamicRect *pGraphic = new CDynamicRect( "" );
if ( !pGraphic->Unserialize( graphics[i] ) )
{
delete pGraphic;
return false;
}
m_LayerGraphics.AddToTail( pGraphic );
char pBuf[255];
UniqueIdToString( graphics[i]->GetId(), pBuf, 255 );
unserializedGraphicMapping.Insert( pBuf, pGraphic );
}
else
{
Warning( "CGameUIDefinition: Warning unknown static graphic type\n" );
}
}
}
// Font graphics
else if ( m_LayerType == SUBLAYER_FONT )
{
CDmxAttribute *pGraphics = pLayer->GetAttribute( "fontGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphics->GetArray< CDmxElement * >( );
int nCount = graphics.Count();
for ( int i = 0; i < nCount; ++i )
{
// What kind of graphic is this?
const char *pType = graphics[i]->GetValueString( "classtype" );
if ( !Q_stricmp( pType, "CDmeTextGeometry" ) )
{
CGameText *pGraphic = new CGameText( "" );
if ( !pGraphic->Unserialize( graphics[i] ) )
{
delete pGraphic;
return false;
}
m_LayerGraphics.AddToTail( pGraphic );
char pBuf[255];
UniqueIdToString( graphics[i]->GetId(), pBuf, 255 );
GameGraphicMap_t graphicMapEntry;
graphicMapEntry.m_Id = graphics[i]->GetId();
graphicMapEntry.pGraphic = pGraphic;
unserializedGraphicMapping.Insert( pBuf, pGraphic );
}
else
{
Warning( "CGameUIDefinition: Warning unknown font graphic type in gui file.\n" );
}
}
}
else
{
Assert(0); // Unknown layer type!!
}
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CGameLayer::InitSheetTexture()
{
Assert( m_pTextureName );
return InitSheetTexture( m_pTextureName );
}
//-----------------------------------------------------------------------------
// FIXME: Must go into rendersystem at some point
//-----------------------------------------------------------------------------
static HRenderTexture CreateTextureFromVTFFile( const char *pFileName, CSheet **ppSheet )
{
static intp s_UniqueID = 0x4000000;
*ppSheet = NULL;
char pTemp[MAX_PATH];
Q_ComposeFileName( "materials/", pFileName, pTemp, sizeof(pTemp) );
Q_SetExtension( pTemp, "vtf", sizeof(pTemp) );
pFileName = pTemp;
char pTemp360[MAX_PATH];
if ( PLATFORM_EXT[0] )
{
CreatePlatformFilename( pFileName, pTemp360, sizeof(pTemp360) );
pFileName = pTemp360;
}
CUtlBuffer fBuf;
if ( !g_pFullFileSystem->ReadFile( pFileName, "GAME", fBuf ) )
{
Warning( "Unable to read texture file %s\n", pFileName );
return RENDER_TEXTURE_HANDLE_INVALID;
}
IVTFTexture *pVtfTexture = CreateVTFTexture();
#if !defined( _GAMECONSOLE )
pVtfTexture->Unserialize( fBuf );
#else
pVtfTexture->UnserializeFromBuffer( fBuf, true, false, false, 0 );
#endif
// we are only going to load the high mip
// pCurData is pointing at pixel data now
TextureHeader_t spec;
memset( &spec, 0, sizeof(TextureHeader_t) );
spec.m_nWidth = pVtfTexture->Width();
spec.m_nHeight = pVtfTexture->Height();
spec.m_nNumMipLevels = 1; //pVtfTexture->MipCount();
spec.m_nDepth = pVtfTexture->Depth();
spec.m_nImageFormat = pVtfTexture->Format();
//spec.m_vecAverageColor.Init( pVtfTexture->Reflectivity().x, pVtfTexture->Reflectivity().y, pVtfTexture->Reflectivity().z, 1 );
char pResourceName[16];
Q_snprintf( pResourceName, sizeof(pResourceName), "%d", s_UniqueID );
HRenderTexture hRet = g_pRenderDevice->FindOrCreateTexture( "gamelayer", pResourceName, &spec );
ResourceAddRef( hRet );
s_UniqueID++;
IRenderContext *pCtx = g_pRenderDevice->GetRenderContext( );
pCtx->SetTextureData( hRet, &spec, pVtfTexture->ImageData( 0, 0, 0 ), pVtfTexture->ComputeTotalSize(), pVtfTexture->IsPreTiled() );
pCtx->Submit( );
g_pRenderDevice->ReleaseRenderContext( pCtx );
ResourceRelease( hRet );
size_t nSheetByteCount;
const void *pSheetData = pVtfTexture->GetResourceData( VTF_RSRC_SHEET, &nSheetByteCount );
if ( pSheetData )
{
// expand compact sheet into fatter runtime form
CUtlBuffer bufLoad( pSheetData, nSheetByteCount, CUtlBuffer::READ_ONLY );
*ppSheet = new CSheet( bufLoad );
}
DestroyVTFTexture( pVtfTexture );
return hRet;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CGameLayer::InitSheetTexture( const char *pBaseTextureName )
{
m_pTextureName = pBaseTextureName;
if ( !g_pRenderDevice )
{
// Material names must be different for each menu.
CFmtStr materialName;
switch ( m_LayerType )
{
case SUBLAYER_STATIC:
materialName.sprintf( "statictx_%s", pBaseTextureName );
break;
case SUBLAYER_DYNAMIC:
materialName.sprintf( "dynamictx_%s", pBaseTextureName );
break;
case SUBLAYER_FONT:
materialName.sprintf( "fonttx_%s", pBaseTextureName );
break;
default:
Assert(0);
break;
};
KeyValues *pVMTKeyValues = new KeyValues( "GameControls" );
pVMTKeyValues->SetString( "$basetexture", pBaseTextureName );
m_Material.Init( materialName, TEXTURE_GROUP_OTHER, pVMTKeyValues );
m_Material->Refresh();
m_Sheet.Set( LoadSheet( m_Material ) );
}
else
{
CUtlString materialName;
switch ( m_LayerType )
{
case SUBLAYER_STATIC:
CSheet *pSheet;
m_hTexture = CreateTextureFromVTFFile( pBaseTextureName, &pSheet );
m_Sheet.Set( pSheet );
break;
case SUBLAYER_DYNAMIC:
break;
case SUBLAYER_FONT:
break;
default:
Assert(0);
break;
};
}
return true;
}
//-----------------------------------------------------------------------------
// UI sheets
//-----------------------------------------------------------------------------
CSheet *CGameLayer::LoadSheet( IMaterial *pMaterial )
{
if ( !pMaterial )
return NULL;
bool bFoundVar = false;
IMaterialVar *pVar = pMaterial->FindVar( "$basetexture", &bFoundVar, true );
if ( bFoundVar && pVar && pVar->IsDefined() )
{
ITexture *pTex = pVar->GetTextureValue();
if ( pTex && !pTex->IsError() )
{
return LoadSheet( pTex->GetName(), pTex );
}
}
return NULL;
}
void CGameLayer::GetSheetTextureSize( int &nWidth, int &nHeight )
{
if ( !m_Material )
return;
bool bFoundVar = false;
IMaterialVar *pVar = m_Material->FindVar( "$basetexture", &bFoundVar, true );
if ( bFoundVar && pVar && pVar->IsDefined() )
{
ITexture *pTex = pVar->GetTextureValue();
if ( pTex && !pTex->IsError() )
{
nWidth = pTex->GetActualWidth();
nHeight = pTex->GetActualHeight();
}
}
}
//--------------------------------------------------------------------------------
// UI sheets
//--------------------------------------------------------------------------------
CSheet *CGameLayer::LoadSheet( char const *pszFname, ITexture *pTexture )
{
//if ( !m_bShouldLoadSheets )
// return NULL;
//if ( m_SheetList.Defined( pszFname ) )
// return m_SheetList[ pszFname ];
CSheet *pNewSheet = NULL;
// get compact sheet representation held by texture
size_t numBytes;
void const *pSheet = pTexture->GetResourceData( VTF_RSRC_SHEET, &numBytes );
if ( pSheet )
{
// expand compact sheet into fatter runtime form
CUtlBuffer bufLoad( pSheet, numBytes, CUtlBuffer::READ_ONLY );
pNewSheet = new CSheet( bufLoad );
}
//m_SheetList[ pszFname ] = pNewSheet;
return pNewSheet;
}
//--------------------------------------------------------------------------------
// Add a graphic to the list.
//--------------------------------------------------------------------------------
int CGameLayer::AddGraphic( CGameGraphic *pGraphic )
{
return m_LayerGraphics.AddToTail( pGraphic );
}
//--------------------------------------------------------------------------------
// Remove a graphic from the list.
// Returns true if it was found and removed.
//--------------------------------------------------------------------------------
bool CGameLayer::RemoveGraphic( CGameGraphic *pGraphic )
{
return m_LayerGraphics.FindAndRemove( pGraphic );
}
//--------------------------------------------------------------------------------
// Clear out the graphics list
//--------------------------------------------------------------------------------
void CGameLayer::ClearGraphics()
{
m_LayerGraphics.RemoveAll();
}
//--------------------------------------------------------------------------------
// Clear out the graphics list
//--------------------------------------------------------------------------------
bool CGameLayer::HasGraphic( CGameGraphic *pGraphic )
{
int nCount = m_LayerGraphics.Count();
for ( int i = 0; i < nCount; ++i )
{
if ( pGraphic == m_LayerGraphics[i] )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
IMaterial *CGameLayer::GetMaterial()
{
// FIXME
// NOTE: This has to be this way to ensure we don't load every freaking material @ startup
//Assert( IsPrecached() );
//if ( !IsPrecached() )
// return NULL;
return m_Material;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::InvalidateSheetSymbol()
{
m_bSheetSymbolCached = false;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::CacheSheetSymbol( CUtlSymbol sheetSymbol )
{
m_SheetSymbol = sheetSymbol;
m_bSheetSymbolCached = true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CUtlSymbol CGameLayer::GetSheetSymbol() const
{
Assert( IsSheetSymbolCached() );
return m_SheetSymbol;
}
//-----------------------------------------------------------------------------
// Start playing animations
//-----------------------------------------------------------------------------
void CGameLayer::StartPlaying()
{
int nCount = m_LayerGraphics.Count();
for ( int i = 0; i < nCount; ++i )
{
m_LayerGraphics[i]->StartPlaying();
}
}
//-----------------------------------------------------------------------------
// Stop playing animations
//-----------------------------------------------------------------------------
void CGameLayer::StopPlaying()
{
int nCount = m_LayerGraphics.Count();
for ( int i = 0; i < nCount; ++i )
{
m_LayerGraphics[i]->StopPlaying();
}
}
//-----------------------------------------------------------------------------
// Move to the next available animation state
//-----------------------------------------------------------------------------
void CGameLayer::AdvanceState()
{
int nCount = m_LayerGraphics.Count();
for ( int i = 0; i < nCount; ++i )
{
m_LayerGraphics[i]->AdvanceState();
}
}
//-----------------------------------------------------------------------------
// Set all graphics to "default" state.
//-----------------------------------------------------------------------------
void CGameLayer::InitAnims()
{
int nCount = m_LayerGraphics.Count();
for ( int i = 0; i < nCount; ++i )
{
m_LayerGraphics[i]->SetState( "default" );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::UpdateGeometry()
{
int nGraphicsCount = m_LayerGraphics.Count();
if ( nGraphicsCount == 0 )
{
return;
}
for ( int i = 0; i < nGraphicsCount; ++i )
{
m_LayerGraphics[i]->UpdateGeometry();
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo )
{
int nGraphicsCount = m_LayerGraphics.Count();
if ( nGraphicsCount == 0 )
{
return;
}
for ( int i = 0; i < nGraphicsCount; ++i )
{
m_LayerGraphics[i]->UpdateRenderTransforms( stageRenderInfo );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameLayer::UpdateRenderData( CGameUIDefinition &gameUIDef, color32 parentColor, CUtlVector< LayerRenderLists_t > &renderLists )
{
bool bDrawExtents = false;
int nGraphicsCount = m_LayerGraphics.Count();
if ( nGraphicsCount == 0 )
{
return;
}
// Basic algorithm is one renderList per material.
// Static graphics are sorted so that they all use the same sheet texture.
// Font graphics are sorted by render order. Their rendergeometry contains the font ID to use
// Dynamic graphics could add renderlists, since the material can change.
// Dynamic graphics will keep adding to the same renderlist until the material's don't match.
// This adds draw calls but preserves render order.
if ( m_LayerType == SUBLAYER_DYNAMIC )
{
int listIndex = -1;
int layerIndex = -1;
for ( int i = 0; i < nGraphicsCount; ++i )
{
// Groups should never be in lists of layer graphics.
Assert( !m_LayerGraphics[i]->IsGroup() );
CGraphicGroup *pGroup = m_LayerGraphics[i]->GetGroup();
Assert( pGroup );
// Only dynamic graphics are allowed in dynamic sublayers.
Assert( m_LayerGraphics[i]->IsDynamic() );
// Get the material this graphic uses.
const char *pAlias = m_LayerGraphics[i]->GetMaterialAlias();
IMaterial *pAliasMaterial = g_pGameUISystemMgrImpl->GetImageAliasMaterial( pAlias );
// Is the material this graphic uses the same as the one in our current renderlist?
if ( i == 0 || renderLists[layerIndex].m_pMaterial != pAliasMaterial )
{
// Our material has changed. Add a new renderlist for this material.
layerIndex = renderLists.AddToTail();
listIndex = renderLists[layerIndex].m_RenderGeometryLists.AddToTail();
renderLists[layerIndex].m_LayerType = m_LayerType;
renderLists[layerIndex].m_pMaterial = pAliasMaterial;
renderLists[layerIndex].m_pSheet = NULL;
renderLists[layerIndex].m_hTexture = m_hTexture;
}
CUtlVector< RenderGeometryList_t > &renderGeometryLists = renderLists[layerIndex].m_RenderGeometryLists;
Assert( layerIndex != -1 );
Assert( listIndex != -1 );
m_LayerGraphics[i]->UpdateRenderData( pGroup->GetResultantColor(), renderGeometryLists, listIndex );
}
}
else if ( m_LayerType == SUBLAYER_STATIC )
{
int listIndex = -1;
int layerIndex = -1;
layerIndex = renderLists.AddToTail();
listIndex = renderLists[layerIndex].m_RenderGeometryLists.AddToTail();
renderLists[layerIndex].m_LayerType = m_LayerType;
renderLists[layerIndex].m_pMaterial = m_Material;
renderLists[layerIndex].m_pSheet = m_Sheet;
renderLists[layerIndex].m_hTexture = m_hTexture;
CUtlVector< RenderGeometryList_t > &renderGeometryLists = renderLists[layerIndex].m_RenderGeometryLists;
Assert( layerIndex != -1 );
Assert( listIndex != -1 );
for ( int i = 0; i < nGraphicsCount; ++i )
{
// Groups should never be in lists of layer graphics.
Assert( !m_LayerGraphics[i]->IsGroup() );
CGraphicGroup *pGroup = m_LayerGraphics[i]->GetGroup();
Assert( pGroup );
m_LayerGraphics[i]->UpdateRenderData( pGroup->GetResultantColor(), renderGeometryLists, listIndex );
}
if ( bDrawExtents )
{
for ( int i = 0; i < nGraphicsCount; ++i )
{
if ( !m_LayerGraphics[i]->IsGroup() )
{
m_LayerGraphics[i]->DrawExtents( renderGeometryLists, listIndex );
}
}
}
}
else if ( m_LayerType == SUBLAYER_FONT )
{
int listIndex = -1;
int layerIndex = -1;
layerIndex = renderLists.AddToTail();
listIndex = renderLists[layerIndex].m_RenderGeometryLists.AddToTail();
renderLists[layerIndex].m_LayerType = m_LayerType;
renderLists[layerIndex].m_pMaterial = m_Material;
renderLists[layerIndex].m_pSheet = m_Sheet;
renderLists[layerIndex].m_hTexture = m_hTexture;
CUtlVector< RenderGeometryList_t > &renderGeometryLists = renderLists[layerIndex].m_RenderGeometryLists;
Assert( layerIndex != -1 );
Assert( listIndex != -1 );
for ( int i = 0; i < nGraphicsCount; ++i )
{
// Groups should never be in lists of layer graphics.
Assert( !m_LayerGraphics[i]->IsGroup() );
CGraphicGroup *pGroup = m_LayerGraphics[i]->GetGroup();
Assert( pGroup );
m_LayerGraphics[i]->UpdateRenderData( pGroup->GetResultantColor(), renderGeometryLists, listIndex );
}
if ( bDrawExtents )
{
// Find the static material and sheet
for ( int i = 0; i < renderLists.Count(); ++i )
{
if ( renderLists[i].m_LayerType == SUBLAYER_STATIC )
{
// Make another layer for rendering extents
// Only do this if there is a static texture around to use for rendering.
layerIndex = renderLists.AddToTail();
listIndex = renderLists[layerIndex].m_RenderGeometryLists.AddToTail();
renderLists[layerIndex].m_LayerType = SUBLAYER_STATIC; // must be static since these render as triangles.
renderLists[layerIndex].m_pMaterial = renderLists[i].m_pMaterial;
renderLists[layerIndex].m_pSheet = renderLists[i].m_pSheet;
renderLists[layerIndex].m_hTexture = renderLists[i].m_hTexture;
CUtlVector< RenderGeometryList_t > &renderGeometryLists2 = renderLists[layerIndex].m_RenderGeometryLists;
Assert( layerIndex != -1 );
Assert( listIndex != -1 );
for ( int i = 0; i < nGraphicsCount; ++i )
{
CGameText *pText = dynamic_cast<CGameText *>( m_LayerGraphics[i] );
Assert( pText );
pText->DrawExtents( renderGeometryLists2, listIndex );
}
break;
}
}
}
}
}
//-----------------------------------------------------------------------------
// Given a position, return the front most graphic under it.
//-----------------------------------------------------------------------------
CGameGraphic *CGameLayer::GetGraphic( int x, int y )
{
int nGraphicCount = m_LayerGraphics.Count();
for ( int i = nGraphicCount-1; i >= 0; --i )
{
CGameGraphic *pGraphic = m_LayerGraphics[i];
if ( pGraphic->HitTest( x, y ) )
return pGraphic;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Given a position, return the front most graphic that can take input under it.
//-----------------------------------------------------------------------------
CGameGraphic *CGameLayer::GetMouseFocus( int x, int y )
{
int nGraphicCount = m_LayerGraphics.Count();
for ( int i = nGraphicCount-1; i >= 0; --i )
{
CGameGraphic *pGraphic = m_LayerGraphics[i];
if ( pGraphic->CanAcceptInput() && pGraphic->HitTest( x, y ) )
return pGraphic;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Given a position, return the front most graphic that can take input under it.
//-----------------------------------------------------------------------------
CGameGraphic *CGameLayer::GetNextFocus( bool &bGetNext, CGameGraphic *pCurrentGraphic )
{
int nGraphicCount = m_LayerGraphics.Count();
for ( int i = 0; i < nGraphicCount; ++i )
{
CGameGraphic *pGraphic = m_LayerGraphics[i];
if ( bGetNext && pGraphic->CanAcceptInput() )
{
return pGraphic;
}
if ( pCurrentGraphic == pGraphic )
{
bGetNext = true;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Given a name of a graphic, find it in this layer
//-----------------------------------------------------------------------------
CGameGraphic *CGameLayer::FindGraphicByName( const char *pName )
{
int nGraphicCount = m_LayerGraphics.Count();
for ( int i = 0; i < nGraphicCount; ++i )
{
CGameGraphic *pGraphic = m_LayerGraphics[i]->FindGraphicByName( pName );
if ( pGraphic )
{
// Match.
return pGraphic;
}
}
return NULL;
}

View File

@@ -0,0 +1,767 @@
//=========== (C) Copyright 1999 Valve, L.L.C. All rights reserved. ===========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// $Header: $
// $NoKeywords: $
//
//=============================================================================
#include "gameuisystem.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imesh.h"
#include "gameuidefinition.h"
#include "gamelayer.h"
#include "tier0/vprof.h"
#include "rendersystem/irenderdevice.h"
#include "rendersystem/irendercontext.h"
#include "gameuisystemsurface.h"
#include "inputgameui.h"
#include "gameuisystemmgr.h"
#include "gameuiscript.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define MAX_LAYERS 10
#define DEBUG_DRAW_REPORT 1
#define HIDE_ALL_TEXT 0
#define HIDE_FONT_TEXTURES 1
// A list of script handles exposed by the system
static int32 g_iSerialHandle = 0;
static CUtlMap< int32, CGameUISystem * > g_mapScriptHandles( DefLessFunc( int32 ) );
CGameUISystem::CGameUISystem() :
m_GameUIDef( this ),
m_iScriptHandle( ++g_iSerialHandle )
{
m_bDrawReport = true;
g_mapScriptHandles.InsertOrReplace( m_iScriptHandle, this );
}
CGameUISystem::~CGameUISystem()
{
g_mapScriptHandles.Remove( m_iScriptHandle );
}
CGameUISystem * CGameUISystem::FromScriptHandle( int32 iScriptHandle )
{
unsigned short usIdx = g_mapScriptHandles.Find( iScriptHandle );
return ( usIdx == g_mapScriptHandles.InvalidIndex() ) ? NULL : g_mapScriptHandles.Element( usIdx );
}
char const * CGameUISystem::GetName()
{
return m_GameUIDef.GetName();
}
//-----------------------------------------------------------------------------
// Init, shutdown
//-----------------------------------------------------------------------------
bool CGameUISystem::Init( KeyValues *kvLoadSettings )
{
DevMsg( "CGameUISystem[%p]::Init( name = %s )\n", this, GetName() );
KeyValuesDumpAsDevMsg( kvLoadSettings );
return true;
}
void CGameUISystem::Release()
{
DevMsg( "CGameUISystem[%p]::Release( name = %s )\n", this, GetName() );
g_pGameUISystemMgrImpl->OnScreenReleased( this );
m_GameUIDef.Shutdown();
delete this;
}
//-----------------------------------------------------------------------------
// Creates an empty game UI.
//-----------------------------------------------------------------------------
void CGameUISystem::LoadEmptyGameUI( const char *pName )
{
m_GameUIDef.Shutdown();
m_GameUIDef.CreateDefault( pName );
}
//-----------------------------------------------------------------------------
// Read the game UI config file from a utlbuffer
//-----------------------------------------------------------------------------
bool CGameUISystem::LoadGameUIDefinition( CUtlBuffer &buf, const char *pFileName )
{
DECLARE_DMX_CONTEXT();
CDmxElement *pRoot = NULL;
if ( !UnserializeDMX( buf, &pRoot, pFileName ) )
{
Warning( "Unable to read game UI config %s! UtlBuffer is the wrong type!\n", pFileName );
return false;
}
bool bOk = m_GameUIDef.Unserialize( pRoot );
CleanupDMX( pRoot );
if ( !bOk )
return false;
m_GameUIDef.InitializeScripts();
// Start the animations all at the same time.
//Start();
//TextTest();
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CGameUISystem::ExecuteScript( KeyValues *kvEvent, KeyValues **ppResult )
{
return m_GameUIDef.ExecuteScript( kvEvent, ppResult );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUISystem::SetStageSize( int nWide, int nTall )
{
m_GameUIDef.SetStageSize( nWide, nTall);
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUISystem::GetStageSize( Vector2D &stageSize )
{
m_GameUIDef.GetStageSize( stageSize );
}
//-----------------------------------------------------------------------------
// 3 draw calls per layer.
// Render in source 1
//-----------------------------------------------------------------------------
void CGameUISystem::Render( const Rect_t &viewport )
{
if ( !m_GameUIDef.GetVisible() )
return;
VPROF_BUDGET( "Render", "Render" );
Assert( g_pMaterialSystem );
m_GameUIDef.UpdateGeometry();
m_GameUIDef.UpdateRenderTransforms( viewport );
CUtlVector< LayerRenderLists_t > renderLists;
m_GameUIDef.GetRenderData( renderLists );
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
// Clear back buffer to green. Useful for debugging graphics that you think should be there and are not.
//pRenderContext->ClearColor4ub( 76, 88, 68, 255 );
//pRenderContext->ClearBuffers( true, true );
pRenderContext->MatrixMode( MATERIAL_PROJECTION );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
pRenderContext->Scale( 1, -1, 1 );
float flPixelOffsetX = .5;
float flPixelOffsetY = .5;
pRenderContext->Ortho( viewport.x + flPixelOffsetX, viewport.y + flPixelOffsetY, viewport.width + flPixelOffsetX, viewport.height + flPixelOffsetY, -1.0f, 1.0f );
// make sure there is no translation and rotation laying around
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
int nStaticDrawCalls = 0;
int nDynamicDrawCalls = 0;
int nFontDrawCalls = 0;
int nLists = renderLists.Count();
for ( int i = 0; i < nLists; ++i )
{
if ( renderLists[i].m_LayerType == SUBLAYER_STATIC )
{
for ( int j = 0; j < renderLists[i].m_RenderGeometryLists.Count(); ++j )
{
RenderStaticLayer( renderLists[i], j );
nStaticDrawCalls++;
}
}
else if ( renderLists[i].m_LayerType == SUBLAYER_DYNAMIC )
{
// For dynamic texture viewing.
//int x = 900;
//int y = 0;
for ( int j = 0; j < renderLists[i].m_RenderGeometryLists.Count(); ++j )
{
RenderDynamicLayer( renderLists[i], j );
nDynamicDrawCalls++;
// For dynamic texture viewing.
//g_pGameUISystemMgrImpl->DrawDynamicTexture( renderLists[i].m_RenderGeometryLists[j][0].m_pImageAlias, x, y );
//y += 256 + 30;
}
}
else if ( renderLists[i].m_LayerType == SUBLAYER_FONT )
{
// For font texture viewing.
//int x = 900;
//int y = 30;
for ( int j = 0; j < renderLists[i].m_RenderGeometryLists.Count(); ++j )
{
RenderTextLayer( renderLists[i].m_RenderGeometryLists[j] );
nFontDrawCalls++;
// For font texture viewing.
//g_pGameUISystemSurface->DrawFontTexture( renderLists[i].m_RenderGeometryLists[j][0].m_FontTextureID, x, y );
//y += 256 + 30;
}
}
}
#if ( DEBUG_DRAW_REPORT )
if ( m_bDrawReport )
{
m_bDrawReport = false;
Msg( "Total static draw calls in UI: %d\n", nStaticDrawCalls );
Msg( "Total dynamic draw calls in UI: %d\n", nDynamicDrawCalls );
Msg( "Total font draw calls in UI: %d\n", nFontDrawCalls );
Msg( "Total draw calls in UI: %d\n", nStaticDrawCalls + nDynamicDrawCalls + nFontDrawCalls );
}
#endif
// Restore the matrices
pRenderContext->MatrixMode( MATERIAL_PROJECTION );
pRenderContext->PopMatrix();
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PopMatrix();
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->PopMatrix();
}
//-----------------------------------------------------------------------------
// Render a static layer in source 1
//-----------------------------------------------------------------------------
void CGameUISystem::RenderStaticLayer( LayerRenderLists_t &renderList, int geometryIndex )
{
// Do not call draw on an empty mesh.
int nTotalTriCount = 0;
for( int i = 0; i < renderList.m_RenderGeometryLists[geometryIndex].Count(); ++i )
{
nTotalTriCount += renderList.m_RenderGeometryLists[geometryIndex][i].GetTriangleCount();
}
if ( nTotalTriCount == 0 )
return;
if ( renderList.m_pSheet == NULL )
{
Assert(0);
return;
}
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
pRenderContext->Bind( renderList.m_pMaterial, NULL );
IMesh* pMesh = pRenderContext->GetDynamicMesh( true );
GenerateUIMesh( pRenderContext, pMesh, renderList.m_RenderGeometryLists[geometryIndex],
renderList.m_pSheet );
pMesh->Draw();
}
//-----------------------------------------------------------------------------
// Render a dynamic layer in source 1
//-----------------------------------------------------------------------------
void CGameUISystem::RenderDynamicLayer( LayerRenderLists_t &renderList, int geometryIndex )
{
// Do not call draw on an empty mesh.
int nTotalTriCount = 0;
for( int i = 0; i < renderList.m_RenderGeometryLists[geometryIndex].Count(); ++i )
{
nTotalTriCount += renderList.m_RenderGeometryLists[geometryIndex][i].GetTriangleCount();
}
if ( nTotalTriCount == 0 )
return;
if ( renderList.m_pMaterial == NULL )
return;
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
IMesh* pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, renderList.m_pMaterial ); // this fxn will also bind the material
if ( !pMesh )
return;
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, nTotalTriCount );
CUtlVector< CRenderGeometry > &renderGeometry = renderList.m_RenderGeometryLists[geometryIndex];
int nGraphicCount = renderGeometry.Count();
int nIndex = 0;
for( int i = 0; i < nGraphicCount; ++i )
{
for ( int j = 0; j < renderGeometry[i].m_Positions.Count(); ++j )
{
// First anim frame
float flX = renderGeometry[i].m_Positions[j].x;
float flY = renderGeometry[i].m_Positions[j].y;
meshBuilder.Position3f( flX, flY, 0.0f );
color32 c = renderGeometry[i].m_VertexColors[j];
meshBuilder.Color4ub( c.r, c.g, c.b, c.a );
float texCoordX = renderGeometry[i].m_TextureCoords[j].x;
float texCoordY = renderGeometry[i].m_TextureCoords[j].y;
meshBuilder.TexCoord3f( 0, texCoordX, texCoordY, 0 );
meshBuilder.AdvanceVertex();
}
Assert( renderGeometry[i].m_Positions.Count() == 4 );
// FIXME make this work with generic convex shapes.
// Quads only.
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 1 );
meshBuilder.FastIndex( nIndex + 2 );
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 2 );
meshBuilder.FastIndex( nIndex + 3 );
nIndex += (4);
}
meshBuilder.End();
pMesh->Draw();
}
//-----------------------------------------------------------------------------
// Render a font layer in source 1
//-----------------------------------------------------------------------------
void CGameUISystem::RenderTextLayer( CUtlVector< CRenderGeometry > &renderGeometry )
{
if ( renderGeometry.Count() == 0 )
return;
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
// get the character texture from the cache
IMaterial *pMaterial = g_pGameUISystemSurface->GetMaterial( renderGeometry[0].m_FontTextureID ); /// Everything in a text rendering layer uses the same font texture, and the texture id is in the seq #
IMesh* pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, pMaterial ); // this fxn will also bind the material
if ( !pMesh )
return;
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, renderGeometry.Count() );
for ( int i = 0; i < renderGeometry.Count(); ++i )
{
Assert( renderGeometry[i].m_Positions.Count() == 4 );
for ( int j = 0; j < renderGeometry[i].m_Positions.Count(); ++j )
{
meshBuilder.Position3f( renderGeometry[i].m_Positions[j].x, renderGeometry[i].m_Positions[j].y, 0.0f );
meshBuilder.Color4ub( renderGeometry[i].m_VertexColors[j].r, renderGeometry[i].m_VertexColors[j].g, renderGeometry[i].m_VertexColors[j].b, renderGeometry[i].m_VertexColors[j].a );
meshBuilder.TexCoord3f( 0, renderGeometry[i].m_TextureCoords[j].x, renderGeometry[i].m_TextureCoords[j].y, 0 );
meshBuilder.AdvanceVertex();
}
}
meshBuilder.End();
pMesh->Draw();
}
//-----------------------------------------------------------------------------
// Create geometry mesh in source 1
//-----------------------------------------------------------------------------
void CGameUISystem::GenerateUIMesh( IMatRenderContext *pRenderContext,
IMesh* pMesh,
CUtlVector< CRenderGeometry > &renderGeometry,
CSheet *pSheet )
{
int nTotalTriCount = 0;
for( int i = 0; i < renderGeometry.Count(); ++i )
{
nTotalTriCount += renderGeometry[i].GetTriangleCount();
}
Assert( nTotalTriCount != 0 );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_TRIANGLES, nTotalTriCount * 2 );
int x, y, width, height;
pRenderContext->GetViewport( x, y, width, height);
static long flAge = 0;
{
VPROF_BUDGET( "meshBuilder", "meshBuilder" );
int nGraphicCount = renderGeometry.Count();
int nIndex = 0;
for( int i = 0; i < nGraphicCount; ++i )
{
const SheetSequenceSample_t *pSample = NULL;
int seqNum = renderGeometry[i].m_SheetSequenceNumber;
if ( renderGeometry[i].m_bAnimate )
{
DmeTime_t flStartTime = renderGeometry[i].GetAnimStartTime();
DmeTime_t flAgeInSeconds = ( g_pGameUISystemMgrImpl->GetTime() - flStartTime );
float m_flAnimationRate = renderGeometry[i].m_AnimationRate;
float flAgeScale = m_flAnimationRate * SEQUENCE_SAMPLE_COUNT;
flAgeScale /= pSheet->m_SheetInfo[seqNum].m_flFrameSpan;
pSample = pSheet->GetSampleForSequence( flAgeInSeconds.GetSeconds(), flAgeScale, seqNum, true );
}
else
{
pSample = pSheet->m_SheetInfo[seqNum].m_pSamples;
}
Assert( pSample );
const SequenceSampleTextureCoords_t *pSample0 = &(pSample->m_TextureCoordData[0]);
Assert( pSample0 );
for ( int j = 0; j < renderGeometry[i].m_Positions.Count(); ++j )
{
// First anim frame
float flX = renderGeometry[i].m_Positions[j].x;
float flY = renderGeometry[i].m_Positions[j].y;
meshBuilder.Position3f( flX, flY, 0.0f );
color32 c = renderGeometry[i].m_VertexColors[j];
c.a *= ( 1 - pSample->m_fBlendFactor );
meshBuilder.Color4ub( c.r, c.g, c.b, c.a );
float sampleWidth = pSample0->m_fRight_U0 - pSample0->m_fLeft_U0;
float sampleHeight = pSample0->m_fBottom_V0 - pSample0->m_fTop_V0;
float texCoordX = pSample0->m_fLeft_U0 + renderGeometry[i].m_TextureCoords[j].x * sampleWidth;
float texCoordY = pSample0->m_fTop_V0 + renderGeometry[i].m_TextureCoords[j].y * sampleHeight;
meshBuilder.TexCoord3f( 0, texCoordX, texCoordY, 0 );
meshBuilder.AdvanceVertex();
// Ugh, right now we have to do this second frame because of the total triangle count being set before we figure out if we need it.
// Second anim frame
//if ( pSample->m_fBlendFactor < 1.0 )
{
meshBuilder.Position3f( flX, flY, 0.0f );
c = renderGeometry[i].m_VertexColors[j];
c.a *= ( pSample->m_fBlendFactor );
meshBuilder.Color4ub( c.r, c.g, c.b, c.a );
float texCoordX = pSample0->m_fLeft_U1 + renderGeometry[i].m_TextureCoords[j].x * sampleWidth;
float texCoordY = pSample0->m_fTop_V1 + renderGeometry[i].m_TextureCoords[j].y * sampleHeight;
meshBuilder.TexCoord3f( 0, texCoordX, texCoordY, 0 );
meshBuilder.AdvanceVertex();
}
}
//if ( pSample->m_fBlendFactor < 1.0 )
{
// FIME make this work with generic convex shapes.
// Quads only.
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 2 );
meshBuilder.FastIndex( nIndex + 4 );
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 4 );
meshBuilder.FastIndex( nIndex + 6 );
meshBuilder.FastIndex( nIndex + 1 );
meshBuilder.FastIndex( nIndex + 3 );
meshBuilder.FastIndex( nIndex + 5 );
meshBuilder.FastIndex( nIndex + 1 );
meshBuilder.FastIndex( nIndex + 5 );
meshBuilder.FastIndex( nIndex + 7 );
nIndex += (4 * 2);
}
/*
else
{
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 1 );
meshBuilder.FastIndex( nIndex + 2 );
meshBuilder.FastIndex( nIndex );
meshBuilder.FastIndex( nIndex + 2 );
meshBuilder.FastIndex( nIndex + 3 );
nIndex += (4 * 1);
}
*/
}
}
meshBuilder.End();
}
//-----------------------------------------------------------------------------
// 3 draw calls per layer.
// Render the UI in source 2
//-----------------------------------------------------------------------------
void CGameUISystem::Render( IRenderContext *pRenderContext, const Rect_t &viewport )
{
if ( !m_GameUIDef.GetVisible() )
return;
m_GameUIDef.UpdateGeometry();
m_GameUIDef.UpdateRenderTransforms( viewport );
CUtlVector< LayerRenderLists_t > renderLists;
m_GameUIDef.GetRenderData( renderLists );
// Note this is not scaling correctly!
pRenderContext->SetCullMode( RENDER_CULLMODE_CULL_NONE );
pRenderContext->SetBlendMode( RENDER_BLEND_ALPHABLENDING );
pRenderContext->BindVertexShader( g_pGameUISystemMgrImpl->m_hVertexShader, g_pGameUISystemMgrImpl->m_hInputLayout );
pRenderContext->BindShader( RENDER_PIXEL_SHADER, g_pGameUISystemMgrImpl->m_hPixelShader );
float pViewportInfo[4] = { viewport.x + 0.5f, viewport.y + 0.5f, viewport.width, viewport.height };
pRenderContext->SetConstantBufferData( g_pGameUISystemMgrImpl->m_hConstBuffer, pViewportInfo, 4 * sizeof( float ) );
pRenderContext->BindConstantBuffer( RENDER_VERTEX_SHADER, g_pGameUISystemMgrImpl->m_hConstBuffer, 0, 0 );
int nLists = renderLists.Count();
for ( int i = 0; i < nLists; ++i )
{
if ( renderLists[i].m_LayerType == SUBLAYER_STATIC )
{
for ( int j = 0; j < renderLists[i].m_RenderGeometryLists.Count(); ++j )
{
RenderStaticLayer( pRenderContext, renderLists[i], j );
}
}
else if ( renderLists[i].m_LayerType == SUBLAYER_FONT )
{
for ( int j = 0; j < renderLists[i].m_RenderGeometryLists.Count(); ++j )
{
RenderTextLayer( pRenderContext, renderLists[i].m_RenderGeometryLists[j] );
}
}
}
}
//-----------------------------------------------------------------------------
// Render a font layer in source 2
//-----------------------------------------------------------------------------
void CGameUISystem::RenderTextLayer( IRenderContext *pRenderContext, CUtlVector< CRenderGeometry > &renderGeometry )
{
if ( renderGeometry.Count() == 0 )
return;
// get the character texture from the cache
HRenderTexture fontTextureHandle = g_pGameUISystemSurface->GetTextureHandle( renderGeometry[0].m_FontTextureID );
pRenderContext->BindTexture( 0, fontTextureHandle );
CDynamicVertexData< GameUIVertex_t > vb( pRenderContext, renderGeometry.Count() * 4, "gamelayer", "game_controls" );
vb.Lock();
for ( int i = 0; i < renderGeometry.Count(); ++i )
{
Assert( renderGeometry[i].m_Positions.Count() == 4 );
for ( int j = 0; j < renderGeometry[i].m_Positions.Count(); ++j )
{
vb->m_vecPosition.Init( renderGeometry[i].m_Positions[j].x, renderGeometry[i].m_Positions[j].y, 0.0f );
vb->m_color = renderGeometry[i].m_VertexColors[j];
vb->m_vecTexCoord.Init( renderGeometry[i].m_TextureCoords[j].x, renderGeometry[i].m_TextureCoords[j].y );
vb.AdvanceVertex();
}
}
vb.Unlock();
vb.Bind( 0, 0 );
CDynamicIndexData< uint16 > ib( pRenderContext, renderGeometry.Count() * 6, "gamelayer", "game_controls" );
ib.Lock();
int nIndex = 0;
for( int i = 0; i < renderGeometry.Count(); ++i )
{
ib.Index( nIndex );
ib.Index( nIndex + 1 );
ib.Index( nIndex + 2 );
ib.Index( nIndex );
ib.Index( nIndex + 2 );
ib.Index( nIndex + 3 );
nIndex += 4;
}
ib.Unlock();
ib.Bind( 0 );
pRenderContext->DrawIndexed( RENDER_PRIM_TRIANGLES, 0, renderGeometry.Count() * 6 );
// For debugging.
//int x = 300;
//int y = 300;
//g_pGameUISystemSurface->DrawFontTexture( pRenderContext, renderGeometry[0].m_FontTextureID, x, y );
//x += 256;
}
//-----------------------------------------------------------------------------
// Renders the static layer in source 2
//-----------------------------------------------------------------------------
void CGameUISystem::RenderStaticLayer( IRenderContext *pRenderContext, LayerRenderLists_t &renderList, int geometryIndex )
{
int nGraphicCount = renderList.m_RenderGeometryLists[geometryIndex].Count();
if ( !nGraphicCount )
return;
int nTotalIndexCount = 0;
int nTotalVertexCount = 0;
int nGeometryCount = renderList.m_RenderGeometryLists[geometryIndex].Count();
for( int i = 0; i < nGeometryCount; ++i )
{
nTotalIndexCount += renderList.m_RenderGeometryLists[geometryIndex][i].GetTriangleCount() * 3;
nTotalVertexCount += renderList.m_RenderGeometryLists[geometryIndex][i].GetVertexCount();
}
if ( nTotalIndexCount == 0 )
return;
pRenderContext->BindTexture( 0, renderList.m_hTexture );
CDynamicVertexData< GameUIVertex_t > vb( pRenderContext, nTotalVertexCount * 2, "gamelayer", "game_controls" );
vb.Lock();
for( int i = 0; i < nGeometryCount; ++i )
{
CRenderGeometry *pGeometry = &renderList.m_RenderGeometryLists[geometryIndex][i];
const SheetSequenceSample_t *pSample = NULL;
int seqNum = pGeometry->m_SheetSequenceNumber;
if ( pGeometry->m_bAnimate )
{
DmeTime_t flStartTime = pGeometry->GetAnimStartTime();
DmeTime_t flAgeInSeconds = ( g_pGameUISystemMgrImpl->GetTime() - flStartTime );
float m_flAnimationRate = pGeometry->m_AnimationRate;
float flAgeScale = m_flAnimationRate * SEQUENCE_SAMPLE_COUNT;
flAgeScale /= renderList.m_pSheet->m_SheetInfo[seqNum].m_flFrameSpan;
pSample = renderList.m_pSheet->GetSampleForSequence( flAgeInSeconds.GetSeconds(), flAgeScale, seqNum, true );
}
else
{
pSample = renderList.m_pSheet->m_SheetInfo[seqNum].m_pSamples;
}
Assert( pSample );
const SequenceSampleTextureCoords_t *pSample0 = &(pSample->m_TextureCoordData[0]);
Assert( pSample0 );
for ( int j = 0; j < pGeometry->m_Positions.Count(); ++j )
{
// First anim frame
float flX = pGeometry->m_Positions[j].x;
float flY = pGeometry->m_Positions[j].y;
vb->m_vecPosition.Init( flX, flY, 0.0f );
color32 c = pGeometry->m_VertexColors[j];
c.a *= ( 1 - pSample->m_fBlendFactor );
vb->m_color = c;
float sampleWidth = pSample0->m_fRight_U0 - pSample0->m_fLeft_U0;
float sampleHeight = pSample0->m_fBottom_V0 - pSample0->m_fTop_V0;
float texCoordX = pSample0->m_fLeft_U0 + pGeometry->m_TextureCoords[j].x * sampleWidth;
float texCoordY = pSample0->m_fTop_V0 + pGeometry->m_TextureCoords[j].y * sampleHeight;
vb->m_vecTexCoord.Init( texCoordX, texCoordY );
vb.AdvanceVertex();
// Second anim frame
//if ( pSample->m_fBlendFactor < 1.0 )
{
c = pGeometry->m_VertexColors[j];
c.a *= ( pSample->m_fBlendFactor );
vb->m_color = c;
float texCoordX = pSample0->m_fLeft_U1 + pGeometry->m_TextureCoords[j].x * sampleWidth;
float texCoordY = pSample0->m_fTop_V1 + pGeometry->m_TextureCoords[j].y * sampleHeight;
vb->m_vecTexCoord.Init( texCoordX, texCoordY );
vb.AdvanceVertex();
}
}
}
vb.Unlock();
vb.Bind( 0, 0 );
CDynamicIndexData< uint16 > ib( pRenderContext, nTotalIndexCount * 2, "gamelayer", "game_controls" );
ib.Lock();
int nIndex = 0;
for( int i = 0; i < nGeometryCount; ++i )
{
ib.Index( nIndex );
ib.Index( nIndex + 2 );
ib.Index( nIndex + 4 );
ib.Index( nIndex );
ib.Index( nIndex + 4 );
ib.Index( nIndex + 6 );
ib.Index( nIndex + 1 );
ib.Index( nIndex + 3 );
ib.Index( nIndex + 5 );
ib.Index( nIndex + 1 );
ib.Index( nIndex + 5 );
ib.Index( nIndex + 7 );
nIndex += (4 * 2);
/*
// FIXME: Deal with sometimes only rendering 1 triangle above
CGeometry *pGeometry = geometry[i];
int nTriangleCount = pGeometry->m_Triangles.Count();
for ( int j = 0; j < nTriangleCount; ++j )
{
CTriangle *pTriangle = &pGeometry->m_Triangles[j];
//if ( pSample->m_fBlendFactor < 1.0 )
{
ib.Index( nIndex + pTriangle->m_PointIndex[0] * 2 );
ib.Index( nIndex + pTriangle->m_PointIndex[1] * 2 );
ib.Index( nIndex + pTriangle->m_PointIndex[2] * 2 );
ib.Index( nIndex + pTriangle->m_PointIndex[0] * 2 + 1 );
ib.Index( nIndex + pTriangle->m_PointIndex[1] * 2 + 1 );
ib.Index( nIndex + pTriangle->m_PointIndex[2] * 2 + 1 );
}
else
{
//ib.Index( nIndex + pTriangle->m_PointIndex[0] );
//ib.Index( nIndex + pTriangle->m_PointIndex[1] );
//ib.Index( nIndex + pTriangle->m_PointIndex[2] );
//nIndex += 3;
}
}
nIndex += (3 * 2) * nTriangleCount;
*/
}
ib.Unlock();
ib.Bind( 0 );
pRenderContext->DrawIndexed( RENDER_PRIM_TRIANGLES, 0, nTotalIndexCount * 2 );
}

View File

@@ -0,0 +1,154 @@
// ----------------------------------------- //
// File generated by VPC //
// ----------------------------------------- //
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\animdata.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\animdata.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\animdata.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Debug output file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Release output file: F:\csgo_64\cstrike15_src\common\debug_lib_check.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\dynamicrect.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\dynamicrect.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\dynamicrect.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamegraphic.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamegraphic.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamegraphic.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameLayer.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameLayer.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameLayer.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamerect.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamerect.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamerect.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamestage.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamestage.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gamestage.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gametext.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gametext.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gametext.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidefinition.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidefinition.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidefinition.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidynamictextures.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidynamictextures.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuidynamictextures.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuischeme.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuischeme.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuischeme.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameUISystem.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameUISystem.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\GameUISystem.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemmgr.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemmgr.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemmgr.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemsurface.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemsurface.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuisystemsurface.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicgroup.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicgroup.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicgroup.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\hitarea.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\hitarea.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\hitarea.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\inputgameui.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\inputgameui.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\inputgameui.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\keyrepeat.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\keyrepeat.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\keyrepeat.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\textdisplay.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\textdisplay.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\textdisplay.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\typedlog.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\typedlog.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\typedlog.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\uigeometry.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\uigeometry.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\uigeometry.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscript.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscript.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscript.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptinterface.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptinterface.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptinterface.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptsystem.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptsystem.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\gameuiscriptsystem.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicscriptinterface.cpp
Debug output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicscriptinterface.cpp
Release output file: F:\csgo_64\cstrike15_src\vgui2\game_controls\graphicscriptinterface.cpp
Containing unity file:
PCH file:

View File

@@ -0,0 +1,126 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "animdata.h"
#include "dmxloader/dmxelement.h"
//#include "tier1/utlvector.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DMXELEMENT_UNPACK ( CAnimData )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pStateName )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "animalias", "", m_pAnimAlias )
DMXELEMENT_UNPACK_FIELD( "textureanimsequencesheetnumber", "0", int, m_TextureAnimSheetSeqNumber )
DMXELEMENT_UNPACK_FIELD( "animationrate", "1", float, m_AnimationRate )
END_DMXELEMENT_UNPACK( CAnimData, s_AnimDataUnpack )
//-----------------------------------------------------------------------------
// Constructor, Destructor
//-----------------------------------------------------------------------------
CAnimData::CAnimData( )
{
m_pStateName = "";
m_pAnimAlias = "";
m_TextureAnimSheetSeqNumber = 0;
m_AnimationRate = 1.0;
}
CAnimData::~CAnimData( )
{
}
//-----------------------------------------------------------------------------
// Populate with data from file.
//-----------------------------------------------------------------------------
bool CAnimData::Unserialize( CDmxElement *pElement )
{
pElement->UnpackIntoStructure( this, s_AnimDataUnpack );
CDmxAttribute *pAnimAttr = pElement->GetAttribute( "colorlog" );
if ( pAnimAttr )
{
CDmxElement *pAnim = pAnimAttr->GetValue< CDmxElement * >();
if ( !m_ColorAnim.Unserialize( pAnim ))
return false;
}
pAnimAttr = pElement->GetAttribute( "centerlog" );
if ( pAnimAttr )
{
CDmxElement *pAnim = pAnimAttr->GetValue< CDmxElement * >();
if ( !m_CenterPosAnim.Unserialize( pAnim ) )
return false;
}
pAnimAttr = pElement->GetAttribute( "scalelog" );
if ( pAnimAttr )
{
CDmxElement *pAnim = pAnimAttr->GetValue< CDmxElement * >();
if ( !m_ScaleAnim.Unserialize( pAnim ) )
return false;
}
pAnimAttr = pElement->GetAttribute( "rotationlog" );
if ( pAnimAttr )
{
CDmxElement *pAnim = pAnimAttr->GetValue< CDmxElement * >();
if ( !m_RotationAnim.Unserialize( pAnim ) )
return false;
}
pAnimAttr = pElement->GetAttribute( "fontlog" );
if ( pAnimAttr )
{
CDmxElement *pAnim = pAnimAttr->GetValue< CDmxElement * >();
if ( !m_FontAnim.Unserialize( pAnim ) )
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Return true if this anim is done playing.
//-----------------------------------------------------------------------------
bool CAnimData::IsDone( DmeTime_t time )
{
if ( m_ColorAnim.IsDone( time ) &&
m_CenterPosAnim.IsDone( time ) &&
m_ScaleAnim.IsDone( time ) &&
m_RotationAnim.IsDone( time ) &&
m_FontAnim.IsDone( time ) )
{
return true;
}
return false;
}

View File

@@ -0,0 +1,46 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef ANIMDATA_H
#define ANIMDATA_H
#ifdef _WIN32
#pragma once
#endif
#include "typedlog.h"
#include "tier1/utlstring.h"
#include "dmxloader/dmxelement.h"
class CAnimData
{
DECLARE_DMXELEMENT_UNPACK()
public:
CAnimData();
~CAnimData();
bool Unserialize( CDmxElement *pElement );
bool IsDone( DmeTime_t time );
CUtlString m_pStateName;
CUtlString m_pAnimAlias;
int m_TextureAnimSheetSeqNumber;
float m_AnimationRate;
CTypedLog< color32 > m_ColorAnim;
CTypedLog< Vector2D > m_CenterPosAnim;
CTypedLog< Vector2D > m_ScaleAnim;
CTypedLog< float > m_RotationAnim;
CTypedLog< CUtlString > m_FontAnim;
};
#endif // ANIMDATA_H

View File

@@ -0,0 +1,174 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "dynamicrect.h"
// To handle scaling
#include "materialsystem/imaterialsystem.h"
#include "animdata.h"
#include "Color.h"
#include "gameuisystemmgr.h"
#include "gameuidefinition.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// Class factory for scripting.
class CDynamicRectClassFactory : IGameUIGraphicClassFactory
{
public:
CDynamicRectClassFactory()
{
Assert( g_pGameUISystemMgrImpl );
g_pGameUISystemMgrImpl->RegisterGraphicClassFactory( "rect", this );
}
// Returns an instance of a graphic interface (keyvalues owned by caller)
virtual CGameGraphic *CreateNewGraphicClass( KeyValues *kvRequest, CGameUIDefinition *pMenu )
{
Assert( pMenu );
CDynamicRect *pNewGraphic = NULL;
const char *pName = kvRequest->GetString( "name", NULL );
if ( pName )
{
pNewGraphic = new CDynamicRect( pName );
// Rects are normally 0,0, doing this so we can see script created rects.
pNewGraphic->SetScale( 100, 100 );
pMenu->AddGraphicToLayer( pNewGraphic, SUBLAYER_DYNAMIC );
// Now set the attributes.
for ( KeyValues *arg = kvRequest->GetFirstSubKey(); arg != NULL; arg = arg->GetNextKey() )
{
pNewGraphic->HandleScriptCommand( arg );
}
}
return pNewGraphic;
}
};
static CDynamicRectClassFactory g_CDynamicRectClassFactory;
BEGIN_DMXELEMENT_UNPACK ( CDynamicRect )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "imagealias", "", m_ImageAlias )
END_DMXELEMENT_UNPACK( CDynamicRect, s_GameDynamicRectUnpack )
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CDynamicRect::CDynamicRect( const char *pName ) : CGameRect( pName )
{
// The default maps to white pixel.
m_ImageAlias = "defaultImageAlias";
}
CDynamicRect::~CDynamicRect()
{
g_pGameUISystemMgrImpl->ReleaseImageAlias( m_ImageAlias );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CDynamicRect::Unserialize( CDmxElement *pGraphic )
{
CGameRect::Unserialize( pGraphic );
pGraphic->UnpackIntoStructure( this, s_GameDynamicRectUnpack );
m_CurrentState = -1;
g_pGameUISystemMgrImpl->InitImageAlias( m_ImageAlias );
g_pGameUISystemMgrImpl->LoadImageAliasTexture( m_ImageAlias, "vguiedit/pixel" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CDynamicRect::UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
if ( !m_Geometry.m_bVisible )
return;
m_Geometry.SetResultantColor( parentColor );
int i = renderGeometryLists[firstListIndex].AddToTail();
CRenderGeometry &renderGeometry = renderGeometryLists[firstListIndex][i];
// Now transform our array of positions into local graphic coord system.
int nCount = m_Geometry.m_RelativePositions.Count();
for ( int i = 0; i < nCount; ++i )
{
// Position
Vector relativePosition( m_Geometry.m_RelativePositions[i].x, m_Geometry.m_RelativePositions[i].y, 0 );
Vector screenpos;
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenpos );
renderGeometry.m_Positions.AddToTail( Vector2D( screenpos.x, screenpos.y ) );;
// TexCoord
Vector2D sheetTexCoords;
g_pGameUISystemMgrImpl->TexCoordsToSheetTexCoords( m_ImageAlias, m_Geometry.m_TextureCoords[i], sheetTexCoords );
renderGeometry.m_TextureCoords.AddToTail( sheetTexCoords );
// Vertex Color
renderGeometry.m_VertexColors.AddToTail( m_Geometry.m_VertexColors[i] );
}
// Triangles
nCount = m_Geometry.m_Triangles.Count();
for ( int i = 0; i < nCount; ++i )
{
renderGeometry.m_Triangles.AddToTail( m_Geometry.m_Triangles[i] );
}
// Anim Info
renderGeometry.m_SheetSequenceNumber = m_Geometry.m_SheetSequenceNumber;
renderGeometry.m_AnimationRate = m_Geometry.m_AnimationRate;
renderGeometry.m_bAnimate = m_Geometry.m_bAnimate;
renderGeometry.m_AnimStartTime = m_Geometry.m_AnimStartTime;
// Set the image alias. This is so we can adjust texture coords if needed if
// This rect's texture gets placed in a sheet.
renderGeometry.m_pImageAlias = m_ImageAlias;
// Now transform our array of positions into local graphic coord system.
nCount = m_Geometry.m_RelativePositions.Count();
m_ScreenPositions.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
// Position
Vector relativePosition( m_Geometry.m_RelativePositions[i].x, m_Geometry.m_RelativePositions[i].y, 0 );
Vector screenpos;
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenpos );
m_ScreenPositions.AddToTail( Vector2D( screenpos.x, screenpos.y ) );
}
}
KeyValues *CDynamicRect::HandleScriptCommand( KeyValues *args )
{
char const *szCommand = args->GetName();
if ( !Q_stricmp( "SetAlias", szCommand ) )
{
g_pGameUISystemMgrImpl->ReleaseImageAlias( m_ImageAlias );
m_ImageAlias = args->GetString( "alias", "defaultImageAlias" );
g_pGameUISystemMgrImpl->InitImageAlias( m_ImageAlias );
return NULL;
}
return CGameRect::HandleScriptCommand( args );
}

View File

@@ -0,0 +1,51 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef DYNAMICRECT_H
#define DYNAMICRECT_H
#ifdef _WIN32
#pragma once
#endif
#include "gamerect.h"
#include "dmxloader/dmxelement.h"
#include "tier1/utlvector.h"
#include "tier1/keyvalues.h"
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CDynamicRect : public CGameRect
{
DECLARE_DMXELEMENT_UNPACK()
public:
CDynamicRect( const char *pName );
virtual ~CDynamicRect();
bool Unserialize( CDmxElement *pGraphic );
virtual void UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual KeyValues *HandleScriptCommand( KeyValues *args );
virtual bool IsDynamic() const { return true; }
virtual const char *GetMaterialAlias(){ return m_ImageAlias; }
protected:
CDynamicRect();
CUtlString m_ImageAlias;
};
#endif // DYNAMICRECT_H

View File

@@ -0,0 +1,97 @@
//-----------------------------------------------------------------------------
// GAME_CONTROLS.VPC
//
// Project Script
//-----------------------------------------------------------------------------
$macro SRCDIR "..\.."
$include "$SRCDIR\vpc_scripts\source_lib_base.vpc"
$Configuration
{
$Compiler
{
$AdditionalIncludeDirectories "$BASE;$SRCDIR\public\game_controls;$SRCDIR\common\game_controls"
$PreprocessorDefinitions "$BASE;GAMECONTROLS_LIB"
$PrecompiledHeaderFile "Debug/game_controls.pch"
}
}
$Project "game_controls"
{
$Folder "Source Files"
{
$File "animdata.cpp"
$File "dynamicrect.cpp"
$File "gamegraphic.cpp"
$File "gametext.cpp"
$File "GameLayer.cpp"
$File "gamerect.cpp"
$File "gamestage.cpp"
$File "gameuidefinition.cpp"
$File "gameuidynamictextures.cpp"
$File "gameuischeme.cpp"
$File "GameUISystem.cpp"
$File "gameuisystemmgr.cpp"
$File "gameuisystemsurface.cpp"
$File "graphicgroup.cpp"
$File "hitarea.cpp"
$File "inputgameui.cpp"
$File "keyrepeat.cpp"
$File "textdisplay.cpp"
$File "typedlog.cpp"
$File "uigeometry.cpp"
$Folder "Scripting Source Files"
{
$File "gameuiscriptsystem.cpp"
$File "gameuiscriptinterface.cpp"
$File "gameuiscript.cpp"
$File "graphicscriptinterface.cpp"
}
}
$Folder "Header Files"
{
$File "animdata.h"
$File "dynamicrect.h"
$File "gametext.h"
$File "gamelayer.h"
$File "gamerect.h"
$File "gamestage.h"
$File "gameuidefinition.h"
$File "gameuidynamictextures.h"
$File "gameuischeme.h"
$File "gameuisystem.h"
$File "gameuisystemmgr.h"
$File "gameuisystemsurface.h"
$File "graphicgroup.h"
$File "hitarea.h"
$File "inputgameui.h"
$File "gamegraphic.h"
$File "keyrepeat.h"
$File "$SRCDIR\common\game_controls\textdisplay.h"
$File "typedlog.h"
$File "uigeometry.h"
$Folder "Scripting Header Files"
{
$File "gameuiscriptsystem.h"
$File "gameuiscriptinterface.h"
$File "gameuiscript.h"
$File "graphicscriptinterface.h"
}
}
$Folder "Public Header Files"
{
$File "$SRCDIR\public\game_controls\igameuisystemmgr.h"
$File "$SRCDIR\common\game_controls\textdisplay.h"
$File "$SRCDIR\public\tier1\utlmemory.h"
$File "$SRCDIR\public\tier1\utlrbtree.h"
$File "$SRCDIR\public\tier1\utlvector.h"
}
}

View File

@@ -0,0 +1,13 @@
"vpc_cache"
{
"CacheVersion" "1"
"win32"
{
"CRCFile" "game_controls.vcxproj.vpc_crc"
"OutputFiles"
{
"0" "game_controls.vcxproj"
"1" "game_controls.vcxproj.filters"
}
}
}

View File

@@ -0,0 +1,321 @@
//========= Copyright © Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "gamegraphic.h"
#include "animdata.h"
#include "gameuisystemmgr.h"
#include "inputgameui.h"
#include "dmxloader/dmxelement.h"
#include "tier1/fmtstr.h"
#include "graphicgroup.h"
#include "gameuiscript.h"
// A list of script handles exposed by the system
static int32 g_iSerialHandle = 0x01000000;
static CUtlMap< int32, CGameGraphic * > g_mapScriptHandles( DefLessFunc( int32 ) );
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CGameGraphic::CGameGraphic() :
m_iScriptHandle( ++g_iSerialHandle )
{
g_mapScriptHandles.InsertOrReplace( m_iScriptHandle, this );
m_pName = "";
m_pGroup = NULL;
m_bCanAcceptInput = false;
m_CurrentState = -1;
m_flAnimTime = DMETIME_ZERO;
}
CGameGraphic::~CGameGraphic()
{
if ( m_pGroup )
{
m_pGroup->RemoveFromGroup( this );
}
int nCount = m_Anims.Count();
for ( int i = 0; i < nCount; ++i )
{
delete m_Anims[i];
m_Anims[i] = NULL;
}
m_Anims.RemoveAll();
g_mapScriptHandles.Remove( m_iScriptHandle );
}
CGameGraphic * CGameGraphic::FromScriptHandle( int32 iScriptHandle )
{
unsigned short usIdx = g_mapScriptHandles.Find( iScriptHandle );
return ( usIdx == g_mapScriptHandles.InvalidIndex() ) ? NULL : g_mapScriptHandles.Element( usIdx );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
DmeTime_t CGameGraphic::GetAnimationTimePassed()
{
if ( m_Geometry.m_bAnimate )
{
m_flAnimTime = g_pGameUISystemMgrImpl->GetTime() - m_Geometry.m_AnimStartTime;
}
return m_flAnimTime;
}
KeyValues * CGameGraphic::HandleScriptCommand( KeyValues *args )
{
char const *szCommand = args->GetName();
if ( !Q_stricmp( "SetCenter", szCommand ) )
{
SetCenter( args->GetFloat( "x" ), args->GetFloat( "y" ) );
return NULL;
}
else if ( !Q_stricmp( "SetScale", szCommand ) )
{
SetScale( args->GetFloat( "x" ), args->GetFloat( "y" ) );
return NULL;
}
else if ( !Q_stricmp( "SetRotation", szCommand ) )
{
m_Geometry.m_Rotation = args->GetFloat( "rotation", 0.0f );
return NULL;
}
else if ( !Q_stricmp( "SetVisible", szCommand ) )
{
SetVisible( args->GetBool( "visible", true ) );
return NULL;
}
else if ( !Q_stricmp( "GetVisible", szCommand ) )
{
return new KeyValues( "", "visible", GetVisible() ? 1 : 0 );
}
else if ( !Q_stricmp( "SetHorizGradient", szCommand ) )
{
m_Geometry.m_bHorizontalGradient = args->GetBool( "horizgradient", true );
return NULL;
}
else if ( !Q_stricmp( "SetColor", szCommand ) )
{
Color c = args->GetColor( "color", Color( 255, 255, 255, 255 ) );
color32 color;
color.r = c[0];
color.g = c[1];
color.b = c[2];
color.a = c[3];
SetColor( color );
return NULL;
}
else if ( !Q_stricmp( "SetState", szCommand ) )
{
SetState( args->GetString( "state" ), args->GetBool( "play", true ) );
SetAnimationTimePassed( DmeTime_t( args->GetFloat( "time" ) ) );
return NULL;
}
else if ( !Q_stricmp( "GetState", szCommand ) )
{
return new KeyValues( "", "state", GetState() );
}
else if ( !Q_stricmp( "IsDonePlaying", szCommand ) )
{
return new KeyValues( "", "done", IsDonePlaying() ? 1 : 0 );
}
DevWarning( "CGameGraphic::HandleScriptCommand for unknown command %s!\n", args->GetName() );
return NULL;
}
//-----------------------------------------------------------------------------
// If you don't want to use the clock, you can set the time yourself.
//----------------------------------------------------------------------------
void CGameGraphic::SetAnimationTimePassed( DmeTime_t time )
{
m_flAnimTime = time;
}
//-----------------------------------------------------------------------------
// Populate lists for rendering
//-----------------------------------------------------------------------------
void CGameGraphic::UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
if ( !m_Geometry.m_bVisible )
return;
m_Geometry.SetResultantColor( parentColor );
m_Geometry.UpdateRenderData( renderGeometryLists, firstListIndex );
}
//-----------------------------------------------------------------------------
// Have to do this separately because extents are drawn as rects.
//-----------------------------------------------------------------------------
void CGameGraphic::DrawExtents( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
Assert( !IsGroup() );
color32 extentLineColor = { 0, 255, 0, 255 };
m_Geometry.DrawExtents( renderGeometryLists, firstListIndex, extentLineColor );
}
//-----------------------------------------------------------------------------
// Populate lists for rendering
//-----------------------------------------------------------------------------
void CGameGraphic::UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo )
{
m_Geometry.UpdateRenderTransforms( stageRenderInfo, GetGroup() );
}
//-----------------------------------------------------------------------------
// Return the index of the anim this state name maps to.
//-----------------------------------------------------------------------------
bool CGameGraphic::HasState( const char *pStateName )
{
return (GetStateIndex( pStateName ) != -1);
}
//-----------------------------------------------------------------------------
// Set the animation state of this graphic.
// Default is to start playing it. If it is called with startplaying false, it will stop it.
//-----------------------------------------------------------------------------
void CGameGraphic::SetState( const char *pStateName, bool bStartPlaying )
{
int newState = GetStateIndex( pStateName );
if ( ( newState != -1 ) && ( m_CurrentState != newState ) )
{
m_CurrentState = newState;
if ( bStartPlaying )
{
StartPlaying();
}
}
if ( !bStartPlaying )
{
StopPlaying();
}
}
//-----------------------------------------------------------------------------
// Return true if anim is done playing its current state.
//-----------------------------------------------------------------------------
bool CGameGraphic::IsDonePlaying()
{
if ( m_CurrentState == -1 )
return true;
return m_Anims[m_CurrentState]->IsDone( GetAnimationTimePassed() );
}
//-----------------------------------------------------------------------------
// Return the index of the anim this state name maps to.
//-----------------------------------------------------------------------------
int CGameGraphic::GetStateIndex( const char *pStateName )
{
for ( int i = 0; i < m_Anims.Count(); i++ )
{
if ( Q_stricmp( pStateName, m_Anims[i]->m_pStateName ) == 0 )
{
if ( Q_stricmp( m_Anims[i]->m_pAnimAlias, "" ) != 0 )
{
return GetStateIndex( m_Anims[i]->m_pAnimAlias );
}
else
{
return i;
}
}
}
return -1;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
const char *CGameGraphic::GetState()
{
if ( m_CurrentState == -1 )
return "";
if ( Q_stricmp( m_Anims[m_CurrentState]->m_pAnimAlias, "" ) != 0 )
{
return m_Anims[m_CurrentState]->m_pAnimAlias;
}
else
{
return m_Anims[m_CurrentState]->m_pStateName;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameGraphic::StartPlaying()
{
m_Geometry.m_bAnimate = true;
m_Geometry.m_AnimStartTime = g_pGameUISystemMgrImpl->GetTime();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameGraphic::StopPlaying()
{
m_Geometry.m_bAnimate = false;
}
//-----------------------------------------------------------------------------
// for demo and unit tests
//-----------------------------------------------------------------------------
void CGameGraphic::AdvanceState()
{
StopPlaying();
int numStates = m_Anims.Count();
if ( numStates == 0 )
return;
int state = m_CurrentState;
state++;
if ( state > numStates -1 )
state = 0;
m_CurrentState = state;
}
//-----------------------------------------------------------------------------
// Is this the graphic with this name?
//-----------------------------------------------------------------------------
bool CGameGraphic::IsGraphicNamed( const char *pName )
{
if ( !Q_stricmp( m_pName.Get(), pName ) )
{
// Match.
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Does this graphic own a graphic with this name?
//-----------------------------------------------------------------------------
CGameGraphic *CGameGraphic::FindGraphicByName( const char *pName ) const
{
return NULL;
}

View File

@@ -0,0 +1,118 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEGRAPHIC_H
#define GAMEGRAPHIC_H
#ifdef _WIN32
#pragma once
#endif
#include "uigeometry.h"
#include "tier1/utlvector.h"
#include "inputsystem/ButtonCode.h"
#include "tier1/utlstring.h"
//#include "gameuiscript.h"
#include "filesystem.h"
struct InputEvent_t;
class CGraphicGroup;
class CGameUIScript;
class CGameUIDefinition;
class CAnimData;
class CDmxElement;
enum EScriptExecution;
struct StageRenderInfo_t
{
Vector parentPos;
Vector2D parentScale;
int parentRot;
matrix3x4_t relToScreen;
matrix3x4_t relToScreenHoldAspectRatio;
};
//-----------------------------------------------------------------------------
// A class that contains a rect or text or hit area
//-----------------------------------------------------------------------------
class CGameGraphic
{
public:
CGameGraphic();
virtual ~CGameGraphic();
// Update geometry and execute scripting.
virtual void UpdateGeometry(){}
// Populate lists for rendering
virtual void UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo );
virtual void UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual void DrawExtents( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual bool HasState( const char *pStateName );
virtual void SetState( const char *pStateName, bool bStartPlaying = true );
bool IsDonePlaying();
const char *GetState();
virtual void StartPlaying();
virtual void StopPlaying();
virtual void AdvanceState();
void SetAnimationTimePassed( DmeTime_t time );
DmeTime_t GetAnimationTimePassed();
virtual KeyValues *HandleScriptCommand( KeyValues *args );
virtual bool HitTest( int x, int y ) { return false; }
CGraphicGroup *GetGroup() const { return m_pGroup; }
void SetGroup( CGraphicGroup *pGroup ) { m_pGroup = pGroup; }
const char *GetName() const { return m_pName; }
bool IsGraphicNamed( const char *pName );
virtual CGameGraphic *FindGraphicByName( const char *pName ) const;
virtual void SetVisible( bool bVisible ){ m_Geometry.m_bVisible = bVisible; }
bool GetVisible( ) const { return m_Geometry.m_bVisible; }
bool CanAcceptInput() const { return m_bCanAcceptInput; }
virtual bool IsHitArea() const { return false; }
virtual bool IsGroup() const { return false; }
virtual bool IsDynamic() const { return false; }
void SetResultantColor( bool bTop, color32 parentColor );
virtual bool MaintainAspectRatio() const { return m_Geometry.m_bMaintainAspectRatio; }
int32 GetScriptHandle() { return m_iScriptHandle; }
static CGameGraphic * FromScriptHandle( int32 iScriptHandle );
virtual const char *GetMaterialAlias(){ return NULL; }
virtual void SetCenter( float x, float y ) { m_Geometry.m_Center = Vector2D( x, y ); }
virtual void SetScale( float xScale, float yScale ) { m_Geometry.m_Scale = Vector2D( xScale, yScale); }
virtual void SetColor( color32 c ){ m_Geometry.m_Color = c; }
protected:
int GetStateIndex( const char *pStateName );
CUtlString m_pName;
CGraphicGroup *m_pGroup;
bool m_bCanAcceptInput;
CGeometry m_Geometry;
CUtlVector< CAnimData * > m_Anims;
int m_CurrentState;
DmeTime_t m_flAnimTime;
int32 m_iScriptHandle;
};
#endif // GAMEGRAPHIC_H

View File

@@ -0,0 +1,116 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMELAYER_H
#define GAMELAYER_H
#ifdef _WIN32
#pragma once
#endif
#include "igameuisystemmgr.h"
#include "gamegraphic.h"
#include "dmxloader/dmxelement.h"
#include "materialsystem/materialsystemutil.h"
#include "bitmap/psheet.h"
#include "rendersystem/irenderdevice.h"
#include "mathlib/vertexcolor.h"
#include "resourcesystem/stronghandle.h"
#include "tier1/utldict.h"
#include "tier1/UtlStringMap.h"
class IRenderContext;
struct GameGraphicMap_t;
class CGameGraphic;
class GameUIDefinition;
//-----------------------------------------------------------------------------
// GameUI vertex format
//-----------------------------------------------------------------------------
struct GameUIVertex_t
{
Vector m_vecPosition;
VertexColor_t m_color;
Vector2D m_vecTexCoord;
};
//-----------------------------------------------------------------------------
// A class that contains all of the rendering objects in a gameui layer
//-----------------------------------------------------------------------------
// There are currently 3 types of these, for static/dynamic/and font.
class CGameLayer
{
DECLARE_DMXELEMENT_UNPACK()
public:
CGameLayer( SublayerTypes_t layerType = SUBLAYER_STATIC );
~CGameLayer();
void Shutdown();
bool Unserialize( CDmxElement *pLayer, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping );
const char *GetName() const { return m_pName; }
const SublayerTypes_t GetLayerType() { return m_LayerType; }
void SetLayerType( SublayerTypes_t layerType ) { m_LayerType = layerType; }
bool InitSheetTexture();
bool InitSheetTexture( const char *pBaseTextureName );
void GetSheetTextureSize( int &nWidth, int &nHeight );
int AddGraphic( CGameGraphic *pGraphic );
bool RemoveGraphic( CGameGraphic *pGraphic );
void ClearGraphics();
bool HasGraphic( CGameGraphic *pGraphic );
CGameGraphic *FindGraphicByName( const char *pName );
IMaterial *GetMaterial();
HRenderTextureStrong GetTexture() { return m_hTexture; }
// Sheet symbols (used to avoid string->symbol conversions)
void InvalidateSheetSymbol();
void CacheSheetSymbol( CUtlSymbol sheetSymbol );
bool IsSheetSymbolCached() const { return m_bSheetSymbolCached; }
CUtlSymbol GetSheetSymbol() const;
void StartPlaying();
void StopPlaying();
void AdvanceState();
void InitAnims();
void UpdateGeometry();
void UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo );
void UpdateRenderData( CGameUIDefinition &gameUIDef, color32 parentColor, CUtlVector< LayerRenderLists_t > &renderLists );
CGameGraphic *GetGraphic( int x, int y );
CGameGraphic *GetMouseFocus( int x, int y );
CGameGraphic *GetNextFocus( bool &bGetNext, CGameGraphic *pCurrentGraphic );
private:
// Graphics in this layer
CUtlVector< CGameGraphic * > m_LayerGraphics;
CSheet *LoadSheet( IMaterial *pMaterial );
CSheet *LoadSheet( char const *pszFname, ITexture *pTexture );
CUtlString m_pName;
SublayerTypes_t m_LayerType;
CUtlString m_pTextureName;
HRenderTextureStrong m_hTexture;
CMaterialReference m_Material;
CUtlReference< CSheet > m_Sheet;
CUtlSymbol m_SheetSymbol;
bool m_bSheetSymbolCached;
};
#endif // GAMELAYER_H

View File

@@ -0,0 +1,297 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "gamerect.h"
// To handle scaling
#include "materialsystem/imaterialsystem.h"
#include "animdata.h"
#include "Color.h"
#include "gameuisystemmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DMXELEMENT_UNPACK ( CGameRect )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
DMXELEMENT_UNPACK_FIELD( "center", "0 0", Vector2D, m_Geometry.m_Center )
DMXELEMENT_UNPACK_FIELD( "scale", "0 0", Vector2D, m_Geometry.m_Scale )
DMXELEMENT_UNPACK_FIELD( "rotation", "0", float, m_Geometry.m_Rotation )
DMXELEMENT_UNPACK_FIELD( "maintainaspectratio", "0", bool, m_Geometry.m_bMaintainAspectRatio )
DMXELEMENT_UNPACK_FIELD( "sublayertype", "0", int, m_Geometry.m_Sublayer )
DMXELEMENT_UNPACK_FIELD( "visible", "1", bool, m_Geometry.m_bVisible )
DMXELEMENT_UNPACK_FIELD( "initialstate", "-1", int, m_CurrentState )
DMXELEMENT_UNPACK_FIELD( "horizgradient", "0", bool, m_Geometry.m_bHorizontalGradient )
DMXELEMENT_UNPACK_FIELD( "color", "255 255 255 255", Color, m_Geometry.m_Color )
DMXELEMENT_UNPACK_FIELD( "topcolor", "255 255 255 255", Color, m_Geometry.m_TopColor )
DMXELEMENT_UNPACK_FIELD( "bottomcolor", "255 255 255 255", Color, m_Geometry.m_BottomColor )
// color is gotten from log.
// sheet seq number is gotten from log.
END_DMXELEMENT_UNPACK( CGameRect, s_GameRectUnpack )
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CGameRect::CGameRect( const char *pName )
{
m_Geometry.m_SheetSequenceNumber = 0; // FIXME, not updating seq numbers yet.
m_bCanAcceptInput = false;
// DME default values.
m_pName = pName;
m_Geometry.m_Center.x = 0;
m_Geometry.m_Center.y = 0;
m_Geometry.m_Scale.x = 0;
m_Geometry.m_Scale.y = 0;
m_Geometry.m_Rotation = 0;
m_Geometry.m_bMaintainAspectRatio = 0;
m_Geometry.m_Sublayer = 0;
m_Geometry.m_bVisible = true;
m_CurrentState = -1;
m_Geometry.m_bHorizontalGradient = false;
m_Geometry.m_Color.r = 255;
m_Geometry.m_Color.g = 255;
m_Geometry.m_Color.b = 255;
m_Geometry.m_Color.a = 255;
m_Geometry.m_TopColor.r = 255;
m_Geometry.m_TopColor.g = 255;
m_Geometry.m_TopColor.b = 255;
m_Geometry.m_TopColor.a = 255;
m_Geometry.m_BottomColor.r = 255;
m_Geometry.m_BottomColor.g = 255;
m_Geometry.m_BottomColor.b = 255;
m_Geometry.m_BottomColor.a = 255;
m_Geometry.m_RelativePositions.AddToTail( Vector2D( -.5, -.5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( .5, -.5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( .5, .5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( -.5, .5 ) );
m_Geometry.m_TextureCoords.AddToTail( Vector2D( 0.0, 0.0 ) );
m_Geometry.m_TextureCoords.AddToTail( Vector2D( 1.0, 0.0 ) );
m_Geometry.m_TextureCoords.AddToTail( Vector2D( 1.0, 1.0 ) );
m_Geometry.m_TextureCoords.AddToTail( Vector2D( 0.0, 1.0 ) );
SetupVertexColors();
CTriangle triangle;
triangle.m_PointIndex[0] = 0;
triangle.m_PointIndex[1] = 1;
triangle.m_PointIndex[2] = 2;
m_Geometry.m_Triangles.AddToTail( triangle );
triangle.m_PointIndex[0] = 0;
triangle.m_PointIndex[1] = 2;
triangle.m_PointIndex[2] = 3;
m_Geometry.m_Triangles.AddToTail( triangle );
}
CGameRect::~CGameRect()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CGameRect::Unserialize( CDmxElement *pGraphic )
{
pGraphic->UnpackIntoStructure( this, s_GameRectUnpack );
// GEOMETRY
CDmxAttribute *pRelativePositions = pGraphic->GetAttribute( "relativepositions" );
if ( !pRelativePositions || pRelativePositions->GetType() != AT_VECTOR2_ARRAY )
{
return false;
}
const CUtlVector< Vector2D > &relpositions = pRelativePositions->GetArray< Vector2D >( );
int nCount = relpositions.Count();
m_Geometry.m_RelativePositions.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relpositions[i].x, relpositions[i].y ) );
}
CDmxAttribute *pTexCoords = pGraphic->GetAttribute( "texcoords" );
if ( !pTexCoords || pTexCoords->GetType() != AT_VECTOR2_ARRAY )
{
return false;
}
const CUtlVector< Vector2D > &texcoords = pTexCoords->GetArray< Vector2D >( );
nCount = texcoords.Count();
m_Geometry.m_TextureCoords.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
m_Geometry.m_TextureCoords.AddToTail( Vector2D( texcoords[i].x, texcoords[i].y ) );
}
SetupVertexColors();
CDmxAttribute *pTriangles = pGraphic->GetAttribute( "triangles" );
if ( !pTriangles || pTriangles->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &triangles = pTriangles->GetArray< CDmxElement * >( );
nCount = triangles.Count();
m_Geometry.m_Triangles.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
CDmxAttribute *pPoints = triangles[i]->GetAttribute( "positionindexes" );
const CUtlVector< int > &points = pPoints->GetArray< int >( );
CTriangle triangle;
triangle.m_PointIndex[0] = points[0];
triangle.m_PointIndex[1] = points[1];
triangle.m_PointIndex[2] = points[2];
m_Geometry.m_Triangles.AddToTail( triangle );
}
// ANIMSTATES
CDmxAttribute *pImageAnims = pGraphic->GetAttribute( "imageanims" );
if ( !pImageAnims || pImageAnims->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &imageanims = pImageAnims->GetArray< CDmxElement * >( );
nCount = imageanims.Count();
for ( int i = 0; i < nCount; ++i )
{
CAnimData *pAnimData = new CAnimData;
if ( !pAnimData->Unserialize( imageanims[i] ) )
{
delete pAnimData;
return false;
}
m_Anims.AddToTail( pAnimData );
}
// Ok the initial state is 0, which is (usually ) default.
// default could be aliased to another state though so if it is fix the initial state here.
// default might also not be the state that is 0 so this sets the graphic's initial
// state to be the default one.
SetState( "default" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameRect::UpdateGeometry()
{
if ( m_CurrentState == -1 )
return;
Assert( m_CurrentState < m_Anims.Count() );
DmeTime_t flAnimTime = GetAnimationTimePassed();
// Update texture
m_Geometry.m_SheetSequenceNumber = m_Anims[ m_CurrentState ]->m_TextureAnimSheetSeqNumber;
m_Geometry.m_AnimationRate = m_Anims[ m_CurrentState ]->m_AnimationRate;
// Update color
m_Anims[ m_CurrentState ]->m_ColorAnim.GetValue( flAnimTime, &m_Geometry.m_Color );
// Update center location
m_Anims[ m_CurrentState ]->m_CenterPosAnim.GetValue( flAnimTime, &m_Geometry.m_Center );
// Update scale
m_Anims[ m_CurrentState ]->m_ScaleAnim.GetValue( flAnimTime, &m_Geometry.m_Scale );
// Update rotation
m_Anims[ m_CurrentState ]->m_RotationAnim.GetValue( flAnimTime, &m_Geometry.m_Rotation );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameRect::UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
if ( !m_Geometry.m_bVisible )
return;
m_Geometry.SetResultantColor( parentColor );
m_Geometry.UpdateRenderData( renderGeometryLists, firstListIndex );
// Now transform our array of positions into local graphic coord system.
int nCount = m_Geometry.m_RelativePositions.Count();
m_ScreenPositions.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
// Position
Vector relativePosition( m_Geometry.m_RelativePositions[i].x, m_Geometry.m_RelativePositions[i].y, 0 );
Vector screenpos;
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenpos );
m_ScreenPositions.AddToTail( Vector2D( screenpos.x, screenpos.y ) );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameRect::SetupVertexColors()
{
m_Geometry.m_VertexColors.RemoveAll();
// Create 4 vertex colors for this rect.
color32 c;
c.r = 255;
c.g = 255;
c.b = 255;
c.a = 255;
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
}
//-----------------------------------------------------------------------------
// Determine if x,y is inside the graphic.
//-----------------------------------------------------------------------------
bool CGameRect::HitTest( int x, int y )
{
if ( !m_Geometry.m_bVisible )
return false;
if ( m_ScreenPositions.Count() == 0 )
return false;
for ( int i = 0; i < m_Geometry.GetTriangleCount(); ++i )
{
if ( PointTriangleHitTest(
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[0] ],
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[1] ],
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[2] ],
Vector2D( x, y ) ) )
{
//Msg( "%d, %d hit\n", x, y );
return true;
}
}
return false;
}

View File

@@ -0,0 +1,56 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMERECT_H
#define GAMERECT_H
#ifdef _WIN32
#pragma once
#endif
#include "gamegraphic.h"
#include "dmxloader/dmxelement.h"
#include "tier1/utlvector.h"
class CAnimData;
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CGameRect : public CGameGraphic
{
DECLARE_DMXELEMENT_UNPACK()
public:
CGameRect( const char *pName );
virtual ~CGameRect();
bool Unserialize( CDmxElement *pGraphic );
// Update geometry and execute scripting.
virtual void UpdateGeometry();
virtual void UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual bool HitTest( int x, int y );
protected:
CGameRect();
void SetupVertexColors();
CUtlVector< Vector2D > m_ScreenPositions;
};
#endif // GAMERECT_H

View File

@@ -0,0 +1,206 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "gamestage.h"
// To handle scaling
#include "materialsystem/imaterialsystem.h"
#include "animdata.h"
#include "Color.h"
#include "gameuisystemmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DMXELEMENT_UNPACK ( CGameStage )
DMXELEMENT_UNPACK_FIELD( "stagesize", "1024 768", Vector2D, m_StageSize )
DMXELEMENT_UNPACK_FIELD( "fullscreen", "1", bool, m_bFullscreen )
END_DMXELEMENT_UNPACK( CGameStage, s_GameStageUnpack )
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CGameStage::CGameStage()
{
m_pName = "stage";
m_CurrentState = -1;
m_StageSize.x = 1024;
m_StageSize.y = 768;
m_bFullscreen = true;
m_Geometry.m_bMaintainAspectRatio = false;
m_StageRenderInfo.parentPos.x = 0;
m_StageRenderInfo.parentPos.y = 0;
m_StageRenderInfo.parentPos.z = 0;
m_StageRenderInfo.parentScale.x = 0;
m_StageRenderInfo.parentScale.y = 0;
m_StageRenderInfo.parentRot = 0;
m_MaintainAspectRatioStageSize.x = 640;
m_MaintainAspectRatioStageSize.y = 480;
}
CGameStage::~CGameStage()
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CGameStage::Unserialize( CDmxElement *pElement, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping )
{
pElement->UnpackIntoStructure( this, s_GameStageUnpack );
if ( !CGraphicGroup::Unserialize( pElement, unserializedGraphicMapping ) )
return false;
// Ok the initial state is 0, which is ( usually ) default.
// default could be aliased to another state though so if it is fix the initial state here.
// default might also not be the state that is 0 so this sets the graphic's initial
// state to be the default one.
SetState( "default" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameStage::UpdateAspectRatio( const Rect_t &viewport )
{
// First do stage scale.
matrix3x4_t scalemat;
float screenScaleX = (float)(viewport.width) / m_StageSize.x;
float screenScaleY = (float)(viewport.height) / m_StageSize.y;
if ( screenScaleX > screenScaleY )
{
screenScaleX = screenScaleY;
}
else
{
screenScaleY = screenScaleX;
}
m_MaintainAspectRatioStageSize.x = screenScaleX * m_StageSize.x;
m_MaintainAspectRatioStageSize.y = screenScaleY * m_StageSize.y;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameStage::UpdateRenderTransforms( const Rect_t &viewport )
{
// Build the raw stage matrix.
// Move the stage to its position.
matrix3x4_t transmat;
SetIdentityMatrix( transmat );
Vector2D screenPos = Vector2D( viewport.width/2, viewport.height/2 );
screenPos += m_Geometry.m_Center;
m_StageRenderInfo.parentPos = Vector( screenPos.x, screenPos.y, 0 );
PositionMatrix( m_StageRenderInfo.parentPos, transmat);
// First do stage scale.
matrix3x4_t scalemat;
float screenScaleX = (float)(viewport.width) / m_StageSize.x;
float screenScaleY = (float)(viewport.height) / m_StageSize.y;
m_StageRenderInfo.parentScale = Vector2D( screenScaleX, screenScaleY );
m_StageRenderInfo.parentScale *= m_Geometry.m_Scale;
SetScaleMatrix( m_StageRenderInfo.parentScale.x, m_StageRenderInfo.parentScale.y, 1, scalemat );
// Build the stage rotation matrix. Normally this is 0.
matrix3x4_t rotmat;
m_StageRenderInfo.parentRot = m_Geometry.m_Rotation;
MatrixBuildRotationAboutAxis( Vector( 0, 0, 1 ), m_StageRenderInfo.parentRot, rotmat );
// Multiply matrices together in the correct order.
matrix3x4_t temp;
MatrixMultiply( rotmat, scalemat, temp );
matrix3x4_t stageRenderMatrix;
MatrixMultiply( transmat, temp, stageRenderMatrix );
m_StageRenderInfo.relToScreen = stageRenderMatrix;
// Now build another stage matrix that holds the aspect ratio.
// This will scale the size of the graphic while maintaining its aspect ratio.
// Move the graphic to its stage position.
SetIdentityMatrix( transmat );
PositionMatrix( m_StageRenderInfo.parentPos, transmat);
if ( screenScaleX > screenScaleY )
{
screenScaleX = screenScaleY;
}
else
{
screenScaleY = screenScaleX;
}
Vector2D screenScale = Vector2D( screenScaleX, screenScaleY );
screenScale *= m_Geometry.m_Scale;
SetScaleMatrix( screenScale.x, screenScale.y, 1, scalemat );
// Build the stage rotation matrix.
MatrixBuildRotationAboutAxis( Vector( 0, 0, 1 ), m_StageRenderInfo.parentRot, rotmat );
// Multiply matrices together in the correct order.
MatrixMultiply( rotmat, scalemat, temp );
matrix3x4_t stageRenderMatrixHoldAspectRatio;
MatrixMultiply( transmat, temp, stageRenderMatrixHoldAspectRatio );
m_StageRenderInfo.relToScreenHoldAspectRatio = stageRenderMatrixHoldAspectRatio;
// Update all children
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->UpdateRenderTransforms( m_StageRenderInfo );
}
m_ResultantColor = m_Geometry.m_Color;
CGraphicGroup::UpdateRenderData( m_Geometry.m_Color );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameStage::SetStageSize( int nWide, int nTall )
{
m_StageSize.x = nWide;
m_StageSize.y = nTall;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameStage::GetRenderTransform( matrix3x4_t &relToScreen, bool bMaintainAspectRatio ) const
{
if ( bMaintainAspectRatio )
{
relToScreen = m_StageRenderInfo.relToScreenHoldAspectRatio;
}
else
{
relToScreen = m_StageRenderInfo.relToScreen;
}
}

View File

@@ -0,0 +1,64 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMESTAGE_H
#define GAMESTAGE_H
#ifdef _WIN32
#pragma once
#endif
#include "graphicgroup.h"
#include "dmxloader/dmxelement.h"
#include "tier1/utlvector.h"
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CGameStage : public CGraphicGroup
{
DECLARE_DMXELEMENT_UNPACK()
public:
CGameStage();
virtual ~CGameStage();
bool Unserialize( CDmxElement *pElement, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping );
// Update geometry and execute scripting.
virtual void UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo, const CGraphicGroup *pGroup ){}
void UpdateRenderTransforms( const Rect_t &viewport );
virtual void GetRenderTransform( matrix3x4_t &relToScreen, bool bMaintainAspectRatio ) const;
const StageRenderInfo_t &GetRenderInfo() const { return m_StageRenderInfo; }
void UpdateAspectRatio( const Rect_t &viewport );
void SetStageSize( int nWide, int nTall );
void GetStageSize( Vector2D &stageSize ) const { stageSize = m_StageSize; }
void GetMaintainAspectRatioStageSize( Vector2D &stageSize ){ stageSize = m_MaintainAspectRatioStageSize; }
color32 GetStageColor() const { return m_Geometry.m_Color; }
virtual bool IsStageGroup() const { return true; }
private:
Vector2D m_StageSize;
Vector2D m_MaintainAspectRatioStageSize;
bool m_bFullscreen;
StageRenderInfo_t m_StageRenderInfo;
};
#endif // GAMESTAGE_H

View File

@@ -0,0 +1,665 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "gametext.h"
#include "vgui/ilocalize.h"
#include "vgui/vgui.h"
#include <ctype.h>
#include "gameuisystemsurface.h"
#include "gameuisystemmgr.h"
#include "gameuischeme.h"
#include "graphicgroup.h"
#include "gameuidefinition.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// Class factory for scripting.
class CGameTextClassFactory : IGameUIGraphicClassFactory
{
public:
CGameTextClassFactory()
{
Assert( g_pGameUISystemMgrImpl );
g_pGameUISystemMgrImpl->RegisterGraphicClassFactory( "text", this );
}
// Returns an instance of a graphic interface (keyvalues owned by caller)
virtual CGameGraphic *CreateNewGraphicClass( KeyValues *kvRequest, CGameUIDefinition *pMenu )
{
Assert( pMenu );
CGameText *pNewGraphic = NULL;
const char *pName = kvRequest->GetString( "name", NULL );
if ( pName )
{
pNewGraphic = new CGameText( pName );
pMenu->AddGraphicToLayer( pNewGraphic, SUBLAYER_FONT );
// Now set the attributes.
for ( KeyValues *arg = kvRequest->GetFirstSubKey(); arg != NULL; arg = arg->GetNextKey() )
{
pNewGraphic->HandleScriptCommand( arg );
}
}
return pNewGraphic;
}
};
static CGameTextClassFactory g_CGameTextClassFactory;
BEGIN_DMXELEMENT_UNPACK ( CGameText )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
DMXELEMENT_UNPACK_FIELD( "center", "0 0", Vector2D, m_Geometry.m_Center )
DMXELEMENT_UNPACK_FIELD( "scale", "1 1", Vector2D, m_Geometry.m_Scale )
DMXELEMENT_UNPACK_FIELD( "rotation", "0", float, m_Geometry.m_Rotation )
DMXELEMENT_UNPACK_FIELD( "maintainaspectratio", "0", bool, m_Geometry.m_bMaintainAspectRatio )
DMXELEMENT_UNPACK_FIELD( "sublayertype", "0", int, m_Geometry.m_Sublayer )
DMXELEMENT_UNPACK_FIELD( "visible", "1", bool, m_Geometry.m_bVisible )
DMXELEMENT_UNPACK_FIELD( "initialstate", "-1", int, m_CurrentState )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "unlocalizedtext", "NONE", m_CharText )
DMXELEMENT_UNPACK_FIELD( "allcaps", "0", bool, m_bAllCaps )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "fontname", "Default", m_FontName )
DMXELEMENT_UNPACK_FIELD( "justfication", "0", int, m_Justification )
DMXELEMENT_UNPACK_FIELD( "color", "255 255 255 255", Color, m_Geometry.m_Color )
DMXELEMENT_UNPACK_FIELD( "topcolor", "255 255 255 255", Color, m_Geometry.m_TopColor )
DMXELEMENT_UNPACK_FIELD( "bottomcolor", "255 255 255 255", Color, m_Geometry.m_BottomColor )
DMXELEMENT_UNPACK_FIELD( "horizgradient", "0", bool, m_Geometry.m_bHorizontalGradient )
// color is gotten from log.
END_DMXELEMENT_UNPACK( CGameText, s_GameTextUnpack )
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameText::CGameText( const char *pName )
{
m_UnicodeText = NULL;
m_TextBufferLen = 0;
m_UnlocalizedTextSymbol = vgui::INVALID_STRING_INDEX;
m_Font = vgui::INVALID_FONT;
m_bCanAcceptInput = false;
// DME default values.
m_pName = pName;
m_Geometry.m_Center.x = 0;
m_Geometry.m_Center.y = 0;
m_Geometry.m_Scale.x = 1;
m_Geometry.m_Scale.y = 1;
m_Geometry.m_Rotation = 0;
m_Geometry.m_bMaintainAspectRatio = 1;
m_Geometry.m_Sublayer = 0;
m_Geometry.m_bVisible = true;
m_CurrentState = -1;
m_CharText = "NONE";
m_bAllCaps = false;
m_FontName = "Default";
m_Justification = JUSTIFICATION_LEFT;
m_Geometry.m_Color.r = 255;
m_Geometry.m_Color.g = 255;
m_Geometry.m_Color.b = 255;
m_Geometry.m_Color.a = 255;
m_Geometry.m_TopColor.r = 255;
m_Geometry.m_TopColor.g = 255;
m_Geometry.m_TopColor.b = 255;
m_Geometry.m_TopColor.a = 255;
m_Geometry.m_BottomColor.r = 255;
m_Geometry.m_BottomColor.g = 255;
m_Geometry.m_BottomColor.b = 255;
m_Geometry.m_BottomColor.a = 255;
m_Geometry.m_bHorizontalGradient = false;
SetText( m_CharText );
SetFont( m_FontName );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CGameText::~CGameText()
{
if ( m_UnicodeText )
{
delete[] m_UnicodeText;
m_UnicodeText = NULL;
}
};
//-----------------------------------------------------------------------------
// Create game text using dme elements
//-----------------------------------------------------------------------------
bool CGameText::Unserialize( CDmxElement *pGraphic )
{
pGraphic->UnpackIntoStructure( this, s_GameTextUnpack );
// GEOMETRY
// Geometry for text is generated. This is because you don't know it until you know the localized text.
// ANIMSTATES
CDmxAttribute *pImageAnims = pGraphic->GetAttribute( "imageanims" );
if ( !pImageAnims || pImageAnims->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &imageanims = pImageAnims->GetArray< CDmxElement * >( );
int nCount = imageanims.Count();
for ( int i = 0; i < nCount; ++i )
{
CAnimData *pAnimData = new CAnimData;
if ( !pAnimData->Unserialize( imageanims[i] ) )
{
delete pAnimData;
return false;
}
m_Anims.AddToTail( pAnimData );
}
SetText( m_CharText );
SetFont( m_FontName );
SetState( "default" );
return true;
}
//-----------------------------------------------------------------------------
// The attributes that can be modified by scripting are a subset of the DME ones.
//-----------------------------------------------------------------------------
KeyValues *CGameText::HandleScriptCommand( KeyValues *args )
{
char const *szCommand = args->GetName();
if ( !Q_stricmp( "SetText", szCommand ) )
{
const char *text = args->GetString( "text" );
SetText( text );
return NULL;
}
else if ( !Q_stricmp( "SetAllCaps", szCommand ) )
{
m_bAllCaps = args->GetBool( "allcaps", false );
return NULL;
}
else if ( !Q_stricmp( "SetFont", szCommand ) )
{
SetFont( args->GetString( "fontname" ) );
return NULL;
}
else if ( !Q_stricmp( "SetJustification", szCommand ) )
{
// FIXME
m_Justification = args->GetInt( "justfication", 0 );
return NULL;
}
else if ( !Q_stricmp( "SetTopColor", szCommand ) )
{
Color c = args->GetColor( "color", Color( 255, 255, 255, 255 ) );
m_Geometry.m_TopColor.r = c[0];
m_Geometry.m_TopColor.g = c[1];
m_Geometry.m_TopColor.b = c[2];
m_Geometry.m_TopColor.a = c[3];
return NULL;
}
else if ( !Q_stricmp( "SetBottomColor", szCommand ) )
{
Color c = args->GetColor( "color", Color( 255, 255, 255, 255 ) );
m_Geometry.m_BottomColor.r = c[0];
m_Geometry.m_BottomColor.g = c[1];
m_Geometry.m_BottomColor.b = c[2];
m_Geometry.m_BottomColor.a = c[3];
return NULL;
}
else if ( !Q_stricmp( "GetFont", szCommand ) )
{
return new KeyValues( "", "font", m_FontName.Get() );
}
return CGameGraphic::HandleScriptCommand( args );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::SetFont( const char *pFontName )
{
m_FontName = pFontName;
if ( m_FontName.Length() )
{
m_Font = g_pGameUISystemMgrImpl->GetCurrentScheme()->GetFont( m_FontName, true );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::SetFont( FontHandle_t font )
{
m_Font = font;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
FontHandle_t CGameText::GetFont()
{
return m_Font;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::SetJustification( Justification_e justify )
{
m_Justification = justify;
}
//-----------------------------------------------------------------------------
// Purpose: takes the string and looks it up in the localization file to convert it to unicode
//-----------------------------------------------------------------------------
void CGameText::SetText( const char *text )
{
if ( !text )
{
text = "";
}
// check for localization
if ( *text == '#' )
{
// try lookup in localization tables
m_UnlocalizedTextSymbol = g_pVGuiLocalize->FindIndex( text + 1 );
if ( m_UnlocalizedTextSymbol != vgui::INVALID_STRING_INDEX )
{
wchar_t *unicode = g_pVGuiLocalize->GetValueByIndex( m_UnlocalizedTextSymbol );
SetText(unicode);
return;
}
}
// convert the ansi string to unicode and use that
wchar_t unicode[1024];
g_pVGuiLocalize->ConvertANSIToUnicode( text, unicode, sizeof(unicode) );
SetText( unicode );
}
//-----------------------------------------------------------------------------
// Purpose: sets unicode text directly
//-----------------------------------------------------------------------------
void CGameText::SetText( const wchar_t *unicode, bool bClearUnlocalizedSymbol )
{
if ( bClearUnlocalizedSymbol )
{
// Clear out unlocalized text symbol so that changing dialog variables
// doesn't stomp over the custom unicode string we're being set to.
m_UnlocalizedTextSymbol = vgui::INVALID_STRING_INDEX;
}
if (!unicode)
{
unicode = L"";
}
// reallocate the buffer if necessary
short textLen = (short)wcslen( unicode );
if ( textLen >= m_TextBufferLen )
{
if ( m_UnicodeText )
{
delete [] m_UnicodeText;
m_UnicodeText = NULL;
}
m_TextBufferLen = (short)( textLen + 1 );
m_UnicodeText = new wchar_t[ m_TextBufferLen ];
}
// store the text as unicode
wcscpy( m_UnicodeText, unicode );
SetupVertexColors();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::UpdateGeometry()
{
if ( m_CurrentState == -1 )
return;
Assert( m_CurrentState < m_Anims.Count() );
DmeTime_t flAnimTime = GetAnimationTimePassed();
// Update color
m_Anims[ m_CurrentState ]->m_ColorAnim.GetValue( flAnimTime, &m_Geometry.m_Color );
// Update center location
m_Anims[ m_CurrentState ]->m_CenterPosAnim.GetValue( flAnimTime, &m_Geometry.m_Center );
// Update scale
m_Anims[ m_CurrentState ]->m_ScaleAnim.GetValue( flAnimTime, &m_Geometry.m_Scale );
// Update rotation
m_Anims[ m_CurrentState ]->m_RotationAnim.GetValue( flAnimTime, &m_Geometry.m_Rotation );
// Update rotation
m_Anims[ m_CurrentState ]->m_FontAnim.GetValue( flAnimTime, &m_FontName );
SetFont( m_FontName );
}
//-----------------------------------------------------------------------------
// Rendering helper
// For text rendering the starting position is top left
// Center text according to justification.
//-----------------------------------------------------------------------------
void CGameText::GetStartingTextPosition( int &x, int &y )
{
x = 0;
y = -GetTextRenderHeight()/2;
switch ( m_Justification )
{
case JUSTIFICATION_LEFT:
break;
case JUSTIFICATION_CENTER:
x = -GetTextRenderWidth()/2;
break;
case JUSTIFICATION_RIGHT:
x = -GetTextRenderWidth();
break;
default:
Assert(0);
break;
}
}
//-----------------------------------------------------------------------------
// Rendering helper
// Determine what list to put this quad into, and make an entry slot for it.
//-----------------------------------------------------------------------------
CRenderGeometry *CGameText::GetGeometryEntry( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex, int fontTextureID )
{
CRenderGeometry *pRenderGeometry = NULL;
if ( renderGeometryLists[firstListIndex].Count() != 0 )
{
for ( int j = firstListIndex; j < renderGeometryLists.Count(); ++j )
{
if ( fontTextureID == renderGeometryLists[j][0].m_FontTextureID )
{
int index = renderGeometryLists[j].AddToTail();
pRenderGeometry = &renderGeometryLists[j][index];
break;
}
}
}
// Didn't find a match for this textureID, time to make a new list of quads for this texture.
if ( pRenderGeometry == NULL )
{
int newListIndex;
if ( renderGeometryLists[firstListIndex].Count() == 0 ) // This is the first quad we are adding to this font layer.
{
newListIndex = firstListIndex;
}
else
{
newListIndex = renderGeometryLists.AddToTail();
}
int index = renderGeometryLists[newListIndex].AddToTail();
pRenderGeometry = &renderGeometryLists[newListIndex][index];
}
return pRenderGeometry;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::SetupVertexColors()
{
// There is no text to generate if these are not set.
if ( !m_UnicodeText )
return;
m_Geometry.m_VertexColors.RemoveAll();
color32 c;
c.r = 255;
c.g = 255;
c.b = 255;
c.a = 255;
for ( wchar_t *wsz = m_UnicodeText; *wsz != 0; wsz++ )
{
// Create 4 vertex colors per letter.
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
m_Geometry.m_VertexColors.AddToTail( c );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameText::UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
if ( !m_Geometry.m_bVisible )
return;
// There is no text to generate if these are not set.
if ( !m_UnicodeText )
return;
if ( m_Font == vgui::INVALID_FONT)
return;
m_Geometry.SetResultantColor( parentColor );
int x, y;
GetStartingTextPosition( x, y );
FontCharRenderInfo info;
info.currentFont = m_Font;
info.drawType = FONT_DRAW_DEFAULT;
int letterIndex = 0;
m_Geometry.m_RelativePositions.RemoveAll();
for ( wchar_t *wsz = m_UnicodeText; *wsz != 0; wsz++, letterIndex += 4 )
{
Assert( letterIndex < m_Geometry.m_VertexColors.Count() );
// Update FontCharRenderInfo
info.x = x;
info.y = y;
info.ch = wsz[0];
if ( m_bAllCaps )
{
info.ch = towupper( info.ch );
}
Vector2D relPositions[4];
g_pGameUISystemSurface->GetUnicodeCharRenderPositions( info, relPositions );
// get the character texture from the cache and the char's texture coords.
float *texCoords = NULL; // note this returns the static from the fonttexturecache... FIXME?
g_pGameUISystemSurface->GetTextureForChar( info, &texCoords );
x += g_pGameUISystemSurface->GetCharacterWidth( m_Font, info.ch );
// Get a geometry from the correct texture list.
CRenderGeometry *pRenderGeometry = GetGeometryEntry( renderGeometryLists, firstListIndex, info.textureId );
Assert( pRenderGeometry != NULL );
// Populate the new entry.
pRenderGeometry->m_FontTextureID = info.textureId;
Vector screenPosition;
Vector relativePosition;
// Top left
relativePosition.Init( relPositions[0].x, relPositions[0].y, 0 );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relPositions[0].x, relPositions[0].y ) );
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenPosition );
pRenderGeometry->m_Positions.AddToTail( Vector2D( floor( screenPosition.x ), floor( screenPosition.y ) ) );
pRenderGeometry->m_VertexColors.AddToTail( m_Geometry.m_VertexColors[letterIndex] );
pRenderGeometry->m_TextureCoords.AddToTail( Vector2D( texCoords[0], texCoords[1] ) );
// Top right
relativePosition.Init( relPositions[1].x, relPositions[1].y, 0 );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relPositions[1].x, relPositions[1].y ) );
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenPosition );
pRenderGeometry->m_Positions.AddToTail( Vector2D( floor( screenPosition.x ), floor( screenPosition.y ) ) );
pRenderGeometry->m_VertexColors.AddToTail( m_Geometry.m_VertexColors[letterIndex + 1] );
pRenderGeometry->m_TextureCoords.AddToTail( Vector2D( texCoords[2], texCoords[1] ) );
// Bottom right
relativePosition.Init( relPositions[2].x, relPositions[2].y, 0 );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relPositions[2].x, relPositions[2].y ) );
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenPosition );
pRenderGeometry->m_Positions.AddToTail( Vector2D( floor( screenPosition.x ), floor( screenPosition.y ) ) );
pRenderGeometry->m_VertexColors.AddToTail( m_Geometry.m_VertexColors[letterIndex + 2] );
pRenderGeometry->m_TextureCoords.AddToTail( Vector2D( texCoords[2], texCoords[3] ) );
// Bottom left
relativePosition.Init( relPositions[3].x, relPositions[3].y, 0 );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relPositions[3].x, relPositions[3].y ) );
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenPosition );
pRenderGeometry->m_Positions.AddToTail( Vector2D( floor( screenPosition.x ), floor( screenPosition.y ) ) );
pRenderGeometry->m_VertexColors.AddToTail( m_Geometry.m_VertexColors[letterIndex + 3] );
pRenderGeometry->m_TextureCoords.AddToTail( Vector2D( texCoords[0], texCoords[3] ) );
pRenderGeometry->m_AnimationRate = m_Geometry.m_AnimationRate;
pRenderGeometry->m_AnimStartTime = m_Geometry.m_AnimStartTime;
pRenderGeometry->m_bAnimate = m_Geometry.m_bAnimate;
pRenderGeometry->m_pImageAlias = NULL;
}
m_Geometry.CalculateExtents();
}
//-----------------------------------------------------------------------------
// Have to do this separately because extents are drawn as rects.
//-----------------------------------------------------------------------------
void CGameText::DrawExtents( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
color32 extentLineColor = { 0, 25, 255, 255 };
m_Geometry.DrawExtents( renderGeometryLists, firstListIndex, extentLineColor );
}
//-----------------------------------------------------------------------------
// Purpose: Get the size of a text string in pixels
//-----------------------------------------------------------------------------
void CGameText::GetTextSize( int &wide, int &tall )
{
wide = 0;
tall = 0;
if ( m_Font == vgui::INVALID_FONT )
return;
// For height, use the remapped font
tall = GetTextRenderHeight();
wide = GetTextRenderWidth();
}
//-----------------------------------------------------------------------------
// Return height of text in pixels
//-----------------------------------------------------------------------------
int CGameText::GetTextRenderWidth()
{
int wordWidth = 0;
int textLen = wcslen( m_UnicodeText );
for ( int i = 0; i < textLen; i++ )
{
wchar_t ch = m_UnicodeText[ i ];
if ( m_bAllCaps )
{
ch = towupper( ch );
}
// handle stupid special characters, these should be removed
if ( ch == '&' && m_UnicodeText[ i + 1 ] != 0 )
{
continue;
}
wordWidth += g_pGameUISystemSurface->GetCharacterWidth( m_Font, ch );
}
return wordWidth;
}
//-----------------------------------------------------------------------------
// Return width of text in pixels
//-----------------------------------------------------------------------------
int CGameText::GetTextRenderHeight()
{
return g_pGameUISystemSurface->GetFontTall( m_Font );
}
//-----------------------------------------------------------------------------
// Note corner colors will be stomped if the base graphic's color changes.
//-----------------------------------------------------------------------------
void CGameText::SetColor( color32 c )
{
m_Geometry.m_TopColor = c;
m_Geometry.m_BottomColor = c;
// Remove first to force the new colors in.
m_Geometry.m_VertexColors.RemoveAll();
SetupVertexColors();
}
//-----------------------------------------------------------------------------
// Determine if x,y is inside the graphic.
//-----------------------------------------------------------------------------
bool CGameText::HitTest( int x, int y )
{
if ( !m_Geometry.m_bVisible )
return false;
// Just using extents for now, note extents don't take into account rotation.
Vector2D point0( m_Geometry.m_Extents.m_TopLeft.x, m_Geometry.m_Extents.m_TopLeft.y );
Vector2D point1( m_Geometry.m_Extents.m_BottomRight.x, m_Geometry.m_Extents.m_TopLeft.y );
Vector2D point2( m_Geometry.m_Extents.m_BottomRight.x, m_Geometry.m_Extents.m_BottomRight.y );
Vector2D point3( m_Geometry.m_Extents.m_TopLeft.x, m_Geometry.m_Extents.m_BottomRight.y );
if ( PointTriangleHitTest( point0, point1, point2, Vector2D( x, y ) ) )
{
//Msg( "%d, %d hit\n", x, y );
return true;
}
if ( PointTriangleHitTest( point0, point2, point3, Vector2D( x, y ) ) )
{
//Msg( "%d, %d hit\n", x, y );
return true;
}
return false;
}

View File

@@ -0,0 +1,95 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMETEXT_H
#define GAMETEXT_H
#ifdef _WIN32
#pragma once
#endif
#include "vgui_surfacelib/ifontsurface.h"
#include "vgui/ilocalize.h"
#include "gamegraphic.h"
#include "dmxloader/dmxelement.h"
#include "animdata.h"
#include "gameuisystemmgr.h"
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CGameText : public CGameGraphic
{
DECLARE_DMXELEMENT_UNPACK()
public:
CGameText( const char *pName );
virtual ~CGameText();
bool Unserialize( CDmxElement *pGraphic );
virtual KeyValues * HandleScriptCommand( KeyValues *args );
void SetFont( const char *pFontName );
void SetText( const char *text );
// where text should go relative to center position.
enum Justification_e
{
JUSTIFICATION_LEFT,
JUSTIFICATION_CENTER,
JUSTIFICATION_RIGHT,
};
void SetJustification( Justification_e justify );
void GetTextSize( int &wide, int &tall );
// from CGameGraphic
virtual void UpdateGeometry();
virtual void UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual void DrawExtents( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual void SetColor( color32 c );
virtual bool HitTest( int x, int y );
private:
CGameText();
void SetText( const wchar_t *unicode, bool bClearUnlocalizedSymbol = false );
void GetStartingTextPosition( int &x, int &y );
CRenderGeometry *GetGeometryEntry( CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex, int fontTextureID );
void SetupVertexColors();
int GetTextRenderWidth();
int GetTextRenderHeight();
void SetFont( FontHandle_t font );
FontHandle_t GetFont();
void GetRenderInfo( CUtlVector< FontCharRenderInfo > &renderInfoList );
wchar_t *m_UnicodeText; // unicode version of the text
short m_TextBufferLen; // size of the text buffer
CUtlString m_CharText; // unlocalized version of the text
vgui::StringIndex_t m_UnlocalizedTextSymbol;
CUtlString m_FontName;
FontHandle_t m_Font;
bool m_bAllCaps;
int m_Justification;
};
#endif // GAMETEXT_H

View File

@@ -0,0 +1,891 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "gameuidefinition.h"
#include "gamelayer.h"
#include "gamerect.h"
#include "gametext.h"
#include "hitarea.h"
#include "graphicgroup.h"
#include "tier1/utlstringmap.h"
#include "tier1/utlbuffer.h"
#include "gameuisystem.h"
#include "gameuiscript.h"
#include "gameuisystemmgr.h"
#include "tier1/fmtstr.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imesh.h"
#include "rendersystem/irenderdevice.h"
#include "rendersystem/irendercontext.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
static unsigned int s_nBaseTextureVarCache = 0;
BEGIN_DMXELEMENT_UNPACK ( CGameUIDefinition )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
END_DMXELEMENT_UNPACK( CGameUIDefinition, s_GameUIDefinitionUnpack )
//-----------------------------------------------------------------------------
// Constructor / Destructor.
//-----------------------------------------------------------------------------
CGameUIDefinition::CGameUIDefinition( IGameUISystem *pGameUISystem /* = NULL */ ) :
m_pGameUISystem( pGameUISystem )
{
m_pName = "";
m_bVisible = true;
m_bCanAcceptInput = false;
m_hScheme = 0;
m_pGameStage = NULL;
// All menus currently default so that
// if mouse focus changes then keyboard focus will match it.
// When keyboard focus changes in response to mouse focus we do not play any anims or send any
// script commands.
// This makes it so one hitarea in the menu has input focus at a time.
// If a menu needs them to be separate we can add a script command to turn this off.
bMouseFocusEqualsKeyboardFocus = true;
}
CGameUIDefinition::~CGameUIDefinition()
{
Shutdown();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDefinition::Shutdown()
{
int nGroups = m_Groups.Count();
for ( int i = 0; i < nGroups; ++i )
{
if ( m_Groups[i] )
{
delete m_Groups[i];
m_Groups[i] = NULL;
}
}
m_Groups.RemoveAll();
int nLayers = m_Layers.Count();
for ( int i = 0; i < nLayers; ++i )
{
m_Layers[i]->Shutdown();
delete m_Layers[i];
m_Layers[i] = NULL;
}
m_Layers.RemoveAll();
int nScripts = m_Scripts.Count();
for ( int i = 0; i < nScripts; ++i )
{
m_Scripts[i]->Shutdown();
delete m_Scripts[i];
m_Scripts[i] = NULL;
}
m_Scripts.RemoveAll();
}
//-----------------------------------------------------------------------------
// Creates an empty GameUI, just has one layer in it. No graphics.
//-----------------------------------------------------------------------------
bool CGameUIDefinition::CreateDefault( const char *pName )
{
m_pName = pName;
const char *pSchemeName = "resource\\ClientScheme.res";
m_hScheme = g_pGameUISchemeManager->LoadSchemeFromFile( pSchemeName, "nouiloadedscheme" );
// Static graphics
CGameLayer *pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_STATIC );
m_Layers.AddToTail( pGameLayer );
// Dynamic graphics.
pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_DYNAMIC );
m_Layers.AddToTail( pGameLayer );
// Font graphics
pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_FONT);
m_Layers.AddToTail( pGameLayer );
// Create a default stage
m_pGameStage = new CGameStage;
m_Groups.InsertBefore( 0, m_pGameStage );
m_bCanAcceptInput = false;
return true;
}
//-----------------------------------------------------------------------------
// Load in data from file
//-----------------------------------------------------------------------------
bool CGameUIDefinition::Unserialize( CDmxElement *pElement )
{
if ( Q_stricmp( pElement->GetTypeString(), "VguiCompiledDoc" ) )
{
return false;
}
pElement->UnpackIntoStructure( this, s_GameUIDefinitionUnpack );
const char *pSchemeName = pElement->GetValueString( "scheme" );
IGameUIScheme *pDefaultScheme = g_pGameUISchemeManager->GetDefaultScheme();
m_hScheme = g_pGameUISchemeManager->GetScheme( pSchemeName );
if ( m_hScheme == pDefaultScheme )
{
// It fell back to the default so didn't find it.
m_hScheme = g_pGameUISchemeManager->LoadSchemeFromFile( pSchemeName, pSchemeName );
Assert( m_hScheme );
}
g_pGameUISystemMgrImpl->SetScheme( m_hScheme );
CDmxAttribute *pLayers = pElement->GetAttribute( "layers" );
if ( !pLayers || pLayers->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
// Create dynamic image mapping.
CDmxAttribute *pImageListAttr = pElement->GetAttribute( "dynamicimagelist" );
if ( pImageListAttr )
{
const CUtlVector< CUtlString > &imageList = pImageListAttr->GetArray< CUtlString >( );
for ( int i = 0; i < imageList.Count(); ++i )
{
const char *pAlias = imageList[i].Get();
g_pGameUISystemMgrImpl->LoadImageAliasTexture( pAlias, "" );
}
}
// Map graphics to their DMX Element.
CUtlDict< CGameGraphic *, int > unserializedGraphicMapping;
const CUtlVector< CDmxElement * > &layers = pLayers->GetArray< CDmxElement * >( );
int nCount = layers.Count();
for ( int i = 0; i < nCount; ++i )
{
if ( !Q_stricmp( layers[i]->GetTypeString(), "DmeCompiledSubLayer" ) )
{
if ( !UnserializeLayer( layers[i], unserializedGraphicMapping ) )
{
return false;
}
}
}
// Add default layers, these layer will contain anything created from scripting.
// Static graphics
CGameLayer *pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_STATIC );
m_Layers.AddToTail( pGameLayer );
// Dynamic graphics.
pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_DYNAMIC );
m_Layers.AddToTail( pGameLayer );
// Font graphics
pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_FONT);
m_Layers.AddToTail( pGameLayer );
// Groups
CDmxAttribute *pGroups = pElement->GetAttribute( "groups" );
if ( !pGroups )
{
return true;
}
if ( pGroups->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &groups = pGroups->GetArray< CDmxElement * >( );
nCount = groups.Count();
if ( nCount == 0 )
{
Msg( "Error: No stage found" );
return false; // no stage would be fail.
}
bool bStageFound = false;
for ( int i = nCount-1; i >= 0; --i )
{
if ( !Q_stricmp( groups[i]->GetTypeString(), "DmeCompiledStage" ) )
{
bStageFound = true;
break;
}
}
if ( !bStageFound )
{
return false; // no stage would be fail.
}
// Add groups to the graphic mapping so groups can contain other groups.
// This means the groups get created and put in the list before they get unserialized.
// Groups should always be in order parents before children.
// This makes sure parents update before children in update loops
for ( int i = 0; i < nCount; ++i )
{
if ( !Q_stricmp( groups[i]->GetTypeString(), "DmeCompiledGroup" ) )
{
CGraphicGroup *pGraphicGroup = new CGraphicGroup;
char pBuf[255];
UniqueIdToString( groups[i]->GetId(), pBuf, 255 );
unserializedGraphicMapping.Insert( pBuf, pGraphicGroup );
m_Groups.AddToTail( pGraphicGroup );
}
else if ( !Q_stricmp( groups[i]->GetTypeString(), "DmeCompiledStage" ) )
{
Assert( i == 0 );
CGameStage *pGraphicGroup = new CGameStage;
m_Groups.InsertBefore( 0, pGraphicGroup );
m_pGameStage = pGraphicGroup;
}
}
// Now unserialize the groups
for ( int i = 0; i < nCount; ++i )
{
if ( !Q_stricmp( groups[i]->GetTypeString(), "DmeCompiledGroup" ) )
{
if ( !m_Groups[i]->Unserialize( groups[i], unserializedGraphicMapping ) )
{
return false;
}
}
else if ( !Q_stricmp( groups[i]->GetTypeString(), "DmeCompiledStage" ) )
{
Assert( i == 0 );
CGameStage *pStage = (CGameStage *)m_Groups[i];
if ( !pStage->Unserialize( groups[i], unserializedGraphicMapping ) )
{
return false;
}
}
else
{
Assert(0); // something is in the group list that isn't a group!
}
}
return true;
}
//-----------------------------------------------------------------------------
// Load in data from file for a layer
//-----------------------------------------------------------------------------
bool CGameUIDefinition::UnserializeLayer( CDmxElement *pLayer,
CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping )
{
// Static graphics
CDmxAttribute *pGraphics = pLayer->GetAttribute( "staticGraphics" );
// The layer may have no static graphics ( it could be only fonts! )
if ( pGraphics && pGraphics->GetType() == AT_ELEMENT_ARRAY )
{
CDmxAttribute *pGraphics = pLayer->GetAttribute( "staticGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphics->GetArray< CDmxElement * >( );
if ( graphics.Count() != 0 )
{
CGameLayer *pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_STATIC );
pGameLayer->Unserialize( pLayer, unserializedGraphicMapping );
m_Layers.AddToTail( pGameLayer );
}
}
// repeat above for dynamic graphics.
// The layer may have no dynamic graphics
if ( pGraphics && pGraphics->GetType() == AT_ELEMENT_ARRAY )
{
CDmxAttribute *pGraphics = pLayer->GetAttribute( "dynamicGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphics->GetArray< CDmxElement * >( );
if ( graphics.Count() != 0 )
{
CGameLayer *pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_DYNAMIC );
pGameLayer->Unserialize( pLayer, unserializedGraphicMapping );
m_Layers.AddToTail( pGameLayer );
}
}
// Font graphics
pGraphics = pLayer->GetAttribute( "fontGraphics" );
// The layer may have no font graphics
if ( pGraphics && pGraphics->GetType() == AT_ELEMENT_ARRAY )
{
CDmxAttribute *pGraphics = pLayer->GetAttribute( "fontGraphics" );
const CUtlVector< CDmxElement * > &graphics = pGraphics->GetArray< CDmxElement * >( );
if ( graphics.Count() != 0 )
{
CGameLayer *pGameLayer = new CGameLayer;
pGameLayer->SetLayerType( SUBLAYER_FONT );
pGameLayer->Unserialize( pLayer, unserializedGraphicMapping );
m_Layers.AddToTail( pGameLayer );
}
}
return true;
}
//-----------------------------------------------------------------------------
// Path is always vguiedit\menuname.lua
//-----------------------------------------------------------------------------
void CGameUIDefinition::InitializeScripts()
{
// First time?
if ( m_Scripts.Count() == 0 )
{
CFmtStr path[2];
path[0].sprintf( "vguiedit\\%s.lua", m_pName.Get() );
path[1].sprintf( "vguiedit\\%s\\%s.lua", m_pName.Get(), m_pName.Get() );
for ( int k = 0; k < ARRAYSIZE( path ); ++ k )
{
CFmtStr scriptPath;
scriptPath.sprintf( "scripts\\%s", path[k].Access() );
// Does this menu have a script?
if ( g_pFullFileSystem->FileExists( scriptPath, "MOD" ) )
{
CGameUIScript *pScript = new CGameUIScript();
bool bResult = pScript->SetScript( path[k], this );
if ( bResult )
{
m_Scripts.AddToTail( pScript );
DevMsg( "Loaded script %s for %s\n", scriptPath.Access(), m_pName.Get() );
break; // break as soon as the first script is loaded successfully
}
else
{
Warning( "Invalid script %s for %s\n", scriptPath.Access(), m_pName.Get() );
delete pScript;
}
}
else
{
DevMsg( "No default script %s found for %s\n", scriptPath.Access(), m_pName.Get() );
}
}
}
SetAcceptInput( false );
}
//-----------------------------------------------------------------------------
// Execute a script function
// The function to call is denoted by executionType
//-----------------------------------------------------------------------------
bool CGameUIDefinition::ExecuteScript( KeyValues *args, KeyValues **ppResult )
{
Assert( !ppResult || !*ppResult ); // storing return value, might overwrite caller's keyvalues
//////////////////////////////////////////////////////////////////////////
// TEMP: special events for unit-tests state control
char const *szEvent = args->GetName();
if ( !Q_stricmp( "AdvanceState", szEvent ) )
{
AdvanceState();
return true;
}
if ( !Q_stricmp( "StartPlaying", szEvent ) )
{
StartPlaying();
return true;
}
if ( !Q_stricmp( "StopPlaying", szEvent ) )
{
StopPlaying();
return true;
}
if ( !Q_stricmp( "ShowCursorCoords", szEvent ) )
{
g_pGameUISystemMgrImpl->ShowCursorCoords();
return true;
}
if ( !Q_stricmp( "ShowGraphicName", szEvent ) )
{
g_pGameUISystemMgrImpl->ShowGraphicName();
return true;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Graphic access
if ( !Q_stricmp( "FindGraphic", szEvent ) )
{
CGameGraphic *pGraphic = FindGraphicByName( args->GetString( "graphic" ) );
if ( pGraphic && ppResult )
{
*ppResult = new KeyValues( "" );
(*ppResult)->SetInt( "graphichandle", pGraphic->GetScriptHandle() );
}
return true;
}
if ( !Q_stricmp( "SetInput", szEvent ) )
{
SetAcceptInput( args->GetBool( "input", true ) );
return true;
}
if ( !Q_stricmp( "InitAnims", szEvent ) )
{
InitAnims();
return true;
}
if ( !Q_stricmp( "Sound", szEvent ) )
{
if ( args->GetBool( "play", true ) )
g_pGameUISystemMgrImpl->PlayMenuSound( args->GetString( "sound" ) );
else
g_pGameUISystemMgrImpl->StopMenuSound( args->GetString( "sound" ) );
}
//////////////////////////////////////////////////////////////////////////
if ( !Q_stricmp( "setdynamictexture", szEvent ) )
{
g_pGameUISystemMgrImpl->LoadImageAliasTexture( args->GetString( "aliasname", "" ), args->GetString( "texturename", "" ) );
}
bool bExecuted = false;
if ( m_Scripts.Count() != 0 && m_Scripts[ 0 ] )
{
m_Scripts[ 0 ]->SetActive( true );
bExecuted = m_Scripts[ 0 ]->Execute( args, ppResult );
m_Scripts[ 0 ]->SetActive( false );
}
if ( !bExecuted )
{
// If the menu doesn't handle its exit just hide it.
if ( !Q_stricmp( szEvent, "OnExit" ) )
{
SetVisible( false );
return true;
}
}
return bExecuted;
}
//-----------------------------------------------------------------------------
// Return the number of layers in this menu
//-----------------------------------------------------------------------------
int CGameUIDefinition::GetLayerCount()
{
return m_Layers.Count();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDefinition::InvalidateSheetSymbols()
{
int nCount = m_Layers.Count();
for ( int j = 0; j < nCount; ++j )
{
m_Layers[j]->InvalidateSheetSymbol();
}
}
//-----------------------------------------------------------------------------
// Update from front to back so input consequences go right in.
//-----------------------------------------------------------------------------
void CGameUIDefinition::UpdateGeometry()
{
m_pGameStage->UpdateGeometry();
}
//-----------------------------------------------------------------------------
// Update the render to screen matrices of all graphics
// Children use thier parent's viewport/matrix and build off that.
//-----------------------------------------------------------------------------
void CGameUIDefinition::UpdateRenderTransforms( const Rect_t &viewport )
{
m_pGameStage->UpdateRenderTransforms( viewport );
}
//-----------------------------------------------------------------------------
// Get lists of rendering data needed to draw the ui.
// Each layer has a different type, static, dynamic, and font
// a new render list is created whenever the layer type changes
// and when the texture needed to render changes.
// Layers live in sets of 3's, static, dynamic and font.
// This preserves render order from the editor.
//-----------------------------------------------------------------------------
void CGameUIDefinition::GetRenderData( CUtlVector< LayerRenderLists_t > &renderLists )
{
int nLayers = m_Layers.Count();
for ( int i = 0; i < nLayers; ++i )
{
color32 stageColor = m_pGameStage->GetStageColor();
m_Layers[i]->UpdateRenderData( *this, stageColor, renderLists );
}
}
//-----------------------------------------------------------------------------
// Given a position, return the front most graphic under it.
//-----------------------------------------------------------------------------
CGameGraphic *CGameUIDefinition::GetGraphic( int x, int y )
{
int nLayers = m_Layers.Count();
for ( int i = nLayers-1; i >= 0; --i )
{
CGameGraphic *pGraphic = ( CGameGraphic * )m_Layers[i]->GetGraphic( x, y );
if ( pGraphic )
{
return pGraphic;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Given a position, return the front most graphic that can take input under it.
//-----------------------------------------------------------------------------
CHitArea *CGameUIDefinition::GetMouseFocus( int x, int y )
{
if ( CanAcceptInput() )
{
int nLayers = m_Layers.Count();
for ( int i = nLayers-1; i >= 0; --i )
{
CHitArea *pGraphic = ( CHitArea * )m_Layers[i]->GetMouseFocus( x, y );
if ( pGraphic )
{
return pGraphic;
}
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Given a graphic, return the next graphic that can receive focus.
// Note the default focus order is just the render order.
//-----------------------------------------------------------------------------
CHitArea *CGameUIDefinition::GetNextFocus( CHitArea *pCurrentGraphic )
{
if ( !CanAcceptInput() )
return NULL;
bool bGetNext = false;
if ( pCurrentGraphic == NULL )
{
bGetNext = true;
}
int nLayers = m_Layers.Count();
for ( int i = 0; i < nLayers; ++i )
{
CHitArea *pGraphic = ( CHitArea * )m_Layers[i]->GetNextFocus( bGetNext, pCurrentGraphic );
if ( pGraphic )
{
return pGraphic;
}
}
// We found no next one, we must be at the end then, restart from the back.
bGetNext = true;
for ( int i = 0; i < nLayers; ++i )
{
CHitArea *pGraphic = ( CHitArea * )m_Layers[i]->GetNextFocus( bGetNext, pCurrentGraphic );
if ( pGraphic )
{
return pGraphic;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Start playing animations
//-----------------------------------------------------------------------------
void CGameUIDefinition::StartPlaying()
{
m_pGameStage->StartPlaying();
int nCount = m_Layers.Count();
for ( int j = 0; j < nCount; ++j )
{
m_Layers[j]->StartPlaying();
}
}
//-----------------------------------------------------------------------------
// Stop playing animations
//-----------------------------------------------------------------------------
void CGameUIDefinition::StopPlaying()
{
m_pGameStage->StopPlaying();
int nCount = m_Layers.Count();
for ( int j = 0; j < nCount; ++j )
{
m_Layers[j]->StopPlaying();
}
}
//-----------------------------------------------------------------------------
// Move to the next known animation state
//-----------------------------------------------------------------------------
void CGameUIDefinition::AdvanceState()
{
m_pGameStage->AdvanceState();
int nCount = m_Layers.Count();
for ( int j = 0; j < nCount; ++j )
{
m_Layers[j]->AdvanceState();
}
}
//-----------------------------------------------------------------------------
// Set all graphics to "default" state.
//-----------------------------------------------------------------------------
void CGameUIDefinition::InitAnims()
{
m_pGameStage->SetState( "default" );
int nCount = m_Layers.Count();
for ( int j = 0; j < nCount; ++j )
{
m_Layers[j]->InitAnims();
}
}
//-----------------------------------------------------------------------------
// Given a graphic, build its scoped name.
//-----------------------------------------------------------------------------
void CGameUIDefinition::BuildScopedGraphicName( CUtlString &name, CGameGraphic *pGraphic )
{
if ( !pGraphic->GetGroup()->IsStageGroup() )
{
BuildScopedGraphicName( name, pGraphic->GetGroup() );
}
name += pGraphic->GetName();
if ( pGraphic->IsGroup() )
{
name += ":";
}
}
//-----------------------------------------------------------------------------
// Given a scoped name of a graphic, return it if it exists in this menu
//-----------------------------------------------------------------------------
CGameGraphic *CGameUIDefinition::GraphicExists( const char *pName ) const
{
if ( m_pGameStage->IsGraphicNamed( pName ) )
return m_pGameStage;
CSplitString nameparts( pName, ":");
CGameGraphic *parent = m_pGameStage;
CGameGraphic *pGraphic = NULL;
for ( int i = 0; i < nameparts.Count(); ++i )
{
pGraphic = parent->FindGraphicByName( nameparts[i] );
if ( pGraphic )
{
parent = pGraphic;
}
else
{
return NULL; // couldn't find it.
}
}
return pGraphic;
}
//-----------------------------------------------------------------------------
// Given a scoped name of a graphic, find it in this menu.
// This function expects to find the graphic
//-----------------------------------------------------------------------------
CGameGraphic *CGameUIDefinition::FindGraphicByName( const char *pName ) const
{
CGameGraphic *pGraphic = GraphicExists( pName );
if ( pGraphic )
{
return pGraphic;
}
else
{
Warning( "FindGraphicByName: Unable to find graphic named %s\n", pName );
return NULL; // couldn't find it.
}
}
//-----------------------------------------------------------------------------
// Add a text graphic to the front most layer of a given type
//-----------------------------------------------------------------------------
bool CGameUIDefinition::AddGraphicToLayer( CGameGraphic *pGraphic, int nLayerType )
{
pGraphic->SetGroup( m_pGameStage );
m_pGameStage->AddToGroup( pGraphic );
// Find the frontmost player of this type.
int nFrontLayer = -1;
for ( int i = m_Layers.Count()-1; i >= 0; --i )
{
if ( m_Layers[i]->GetLayerType() == nLayerType )
{
nFrontLayer = i;
break;
}
}
if ( nFrontLayer != -1 )
{
AddGraphic( pGraphic, nFrontLayer );
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Add a graphic to the given layer
//-----------------------------------------------------------------------------
void CGameUIDefinition::AddGraphic( CGameGraphic *pGraphic, int layerIndex )
{
Assert( layerIndex >= 0 );
Assert (layerIndex < m_Layers.Count() );
m_Layers[layerIndex]->AddGraphic( pGraphic );
}
//-----------------------------------------------------------------------------
// Remove this graphic from the UI
//-----------------------------------------------------------------------------
bool CGameUIDefinition::RemoveGraphic( CGameGraphic *pGraphic )
{
for ( int i = 0; i < m_Layers.Count(); ++i )
{
if ( m_Layers[i]->RemoveGraphic( pGraphic ) )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Return true if this graphic is in this menu
//-----------------------------------------------------------------------------
bool CGameUIDefinition::HasGraphic( CGameGraphic *pGraphic )
{
for ( int i = 0; i < m_Layers.Count(); ++i )
{
if ( m_Layers[i]->HasGraphic( pGraphic ) )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Set visibility of the gameui.
//-----------------------------------------------------------------------------
void CGameUIDefinition::SetVisible( bool bVisible )
{
m_bVisible = bVisible;
// Visibility can cause a focus change to be needed!
g_pGameUISystemMgrImpl->ForceFocusUpdate();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDefinition::UpdateAspectRatio( const Rect_t &viewport )
{
m_pGameStage->UpdateAspectRatio( viewport );
}
//-----------------------------------------------------------------------------
// Change the size of the stage.
//-----------------------------------------------------------------------------
void CGameUIDefinition::SetStageSize( int nWide, int nTall )
{
m_pGameStage->SetStageSize( nWide, nTall );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDefinition::GetStageSize( Vector2D &stageSize )
{
m_pGameStage->GetStageSize( stageSize );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDefinition::GetMaintainAspectRatioStageSize( Vector2D &stageSize )
{
m_pGameStage->GetMaintainAspectRatioStageSize( stageSize );
}

View File

@@ -0,0 +1,126 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUIDEFINITION_H
#define GAMEUIDEFINITION_H
#ifdef _WIN32
#pragma once
#endif
#include "dmxloader/dmxelement.h"
#include "gamegraphic.h"
#include "gameuischeme.h"
#include "tier1/utlobjectreference.h"
#include "tier1/utldict.h"
#include "gamestage.h"
#include "tier1/UtlStringMap.h"
class CGameLayer;
class CGameUIScript;
enum EScriptExecution;
struct GameUIEvent_t;
struct GameGraphicMap_t
{
DmObjectId_t m_Id;
CGameGraphic *pGraphic;
};
//-----------------------------------------------------------------------------
// A template describing how a gameUI will function
// It loads CVguiCompiledDoc
//-----------------------------------------------------------------------------
class CGameUIDefinition
{
DECLARE_DMXELEMENT_UNPACK();
DECLARE_REFERENCED_CLASS( CGameUIDefinition );
public:
explicit CGameUIDefinition( IGameUISystem *pGameUISystem = NULL );
~CGameUIDefinition();
bool CreateDefault( const char *pName );
void Shutdown();
// Serialization, unserialization
bool Unserialize( CDmxElement *pElement );
void InitializeScripts();
void CallInitFunction();
// Scripts associated with the menu all live in a folder by that name.
// The main script for a menu is the same name as the menu.
const char *GetName() const { return m_pName; }
int GetLayerCount();
void InvalidateSheetSymbols();
void UpdateGeometry();
void UpdateRenderTransforms( const Rect_t &viewport );
void GetRenderData( CUtlVector< LayerRenderLists_t > &renderLists );
bool ExecuteScript( KeyValues *kvEvent, KeyValues **ppResult );
void StartPlaying();
void StopPlaying();
void AdvanceState();
void InitAnims();
IGameUISystem * GetGameUISystem() { return m_pGameUISystem; }
IGameUIScheme * GetScheme() { return m_hScheme; }
CGameGraphic *GraphicExists( const char *pName ) const;
CGameGraphic *FindGraphicByName( const char *pName ) const;
bool AddGraphicToLayer( CGameGraphic *pGraphic, int nLayerType );
bool RemoveGraphic( CGameGraphic *pGraphic );
bool HasGraphic( CGameGraphic *pGraphic );
CGameGraphic *GetGraphic( int x, int y );
CHitArea *GetMouseFocus( int x, int y );
CHitArea *GetNextFocus( CHitArea *pCurrentGraphic );
virtual void SetVisible( bool bVisible );
virtual bool GetVisible(){ return m_bVisible; }
void UpdateAspectRatio( const Rect_t &viewport );
void SetStageSize( int nWide, int nTall );
void GetStageSize( Vector2D &stageSize );
void GetMaintainAspectRatioStageSize( Vector2D &stageSize );
bool CanAcceptInput() { return m_bVisible && m_bCanAcceptInput; }
void SetAcceptInput( bool bAcceptInput ) { m_bCanAcceptInput = bAcceptInput; }
bool IsMouseFocusEqualToKeyboardFocus(){ return bMouseFocusEqualsKeyboardFocus; }
void BuildScopedGraphicName( CUtlString &name, CGameGraphic *pGraphic );
CGameUIScript * GetScript() { return m_Scripts.Count() ? m_Scripts[0] : NULL; }
private:
bool UnserializeLayer( CDmxElement *pLayer, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping );
void AddGraphic( CGameGraphic *pGraphic, int layerIndex );
CUtlString m_pName;
bool m_bVisible;
bool m_bCanAcceptInput;
CUtlVector< CGraphicGroup *> m_Groups;
CUtlVector< CGameLayer *> m_Layers;
CUtlVector< CGameUIScript * > m_Scripts;
IGameUISystem *m_pGameUISystem;
IGameUIScheme *m_hScheme;
CGameStage *m_pGameStage;
bool bMouseFocusEqualsKeyboardFocus;
};
#endif // GAMEUIDEFINITION_H

View File

@@ -0,0 +1,633 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "gameuidynamictextures.h"
#include "gamelayer.h"
#include "gamerect.h"
#include "tier1/utlstring.h"
#include "tier1/utlstringmap.h"
#include "tier1/utlbuffer.h"
#include "gameuisystemmgr.h"
#include "tier1/fmtstr.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imesh.h"
#include "rendersystem/irenderdevice.h"
#include "rendersystem/irendercontext.h"
#include "tier1/keyvalues.h"
#include "materialsystem/IMaterialProxy.h"
#include "materialsystem/imaterialproxyfactory.h"
#include "gameuisystemmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define GAMEUI_DYNAMIC_TEXTURE_SHEET_WIDTH 2048
#define GAMEUI_DYNAMIC_TEXTURE_SHEET_HEIGHT 2048
//-----------------------------------------------------------------------------
// A material proxy that resets the base texture to use the dynamic texture
//-----------------------------------------------------------------------------
class CGameControlsProxy : public IMaterialProxy
{
public:
CGameControlsProxy();
virtual ~CGameControlsProxy(){};
virtual bool Init( IMaterial *pMaterial, KeyValues *pKeyValues );
virtual void OnBind( void *pProxyData );
virtual void Release( void )
{
delete this;
}
virtual IMaterial *GetMaterial();
private:
IMaterialVar* m_BaseTextureVar;
};
CGameControlsProxy::CGameControlsProxy(): m_BaseTextureVar( NULL )
{
}
bool CGameControlsProxy::Init( IMaterial *pMaterial, KeyValues *pKeyValues )
{
bool bFoundVar;
m_BaseTextureVar = pMaterial->FindVar( "$basetexture", &bFoundVar, false );
return bFoundVar;
}
void CGameControlsProxy::OnBind( void *pProxyData )
{
const char *pBaseTextureName = ( const char * )pProxyData;
ITexture *pTexture = g_pMaterialSystem->FindTexture( pBaseTextureName, TEXTURE_GROUP_OTHER, true );
m_BaseTextureVar->SetTextureValue( pTexture );
}
IMaterial *CGameControlsProxy::GetMaterial()
{
return m_BaseTextureVar->GetOwningMaterial();
}
//-----------------------------------------------------------------------------
// Factory to create dynamic material. ( Return in this case. )
//-----------------------------------------------------------------------------
class CMaterialProxyFactory : public IMaterialProxyFactory
{
public:
IMaterialProxy *CreateProxy( const char *proxyName );
void DeleteProxy( IMaterialProxy *pProxy );
CreateInterfaceFn GetFactory();
};
static CMaterialProxyFactory s_DynamicMaterialProxyFactory;
IMaterialProxy *CMaterialProxyFactory::CreateProxy( const char *proxyName )
{
if ( Q_strcmp( proxyName, "GameControlsProxy" ) == NULL )
{
return static_cast< IMaterialProxy * >( new CGameControlsProxy );
}
return NULL;
}
void CMaterialProxyFactory::DeleteProxy( IMaterialProxy *pProxy )
{
}
CreateInterfaceFn CMaterialProxyFactory::GetFactory()
{
return Sys_GetFactoryThis();
}
//-----------------------------------------------------------------------------
// Constructor / Destructor.
//-----------------------------------------------------------------------------
CGameUIDynamicTextures::CGameUIDynamicTextures()
{
m_pDynamicTexturePacker = NULL;
m_RenderMaterial = NULL;
m_bRegenerate = false;
}
CGameUIDynamicTextures::~CGameUIDynamicTextures()
{
Shutdown();
}
//-----------------------------------------------------------------------------
// Init any render targets needed by the UI.
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::InitRenderTargets()
{
if ( !m_TexturePage.IsValid() )
{
m_TexturePage.InitRenderTarget( GAMEUI_DYNAMIC_TEXTURE_SHEET_WIDTH, GAMEUI_DYNAMIC_TEXTURE_SHEET_HEIGHT,
RT_SIZE_NO_CHANGE, IMAGE_FORMAT_ARGB8888,
MATERIAL_RT_DEPTH_NONE, false, "_rt_DynamicUI" );
}
if ( m_TexturePage.IsValid() )
{
int nSheetWidth = m_TexturePage->GetActualWidth();
int nSheetHeight = m_TexturePage->GetActualHeight();
m_pDynamicTexturePacker = new CTexturePacker( nSheetWidth, nSheetHeight, IsGameConsole() ? 0 : 1 );
KeyValues *pVMTKeyValues = new KeyValues( "GameControls" );
pVMTKeyValues->SetString( "$basetexture", "_rt_DynamicUI" );
CMaterialReference material;
// Material names must be different
CFmtStr materialName;
materialName.sprintf( "dynamictx_%s", "_rt_DynamicUI" );
material.Init( materialName, TEXTURE_GROUP_OTHER, pVMTKeyValues );
material->Refresh();
{
ImageAliasData_t imageData;
imageData.m_Width = nSheetWidth;
imageData.m_Height = nSheetHeight;
imageData.m_Material = material;
m_ImageAliasMap[ "_rt_DynamicUI" ] = imageData;
}
{
CTextureReference pErrorTexture;
pErrorTexture.Init( "error", TEXTURE_GROUP_OTHER, true );
ImageAliasData_t imageData;
imageData.m_Width = pErrorTexture->GetActualWidth();
imageData.m_Height = pErrorTexture->GetActualHeight();
imageData.m_szBaseTextureName = "error";
imageData.m_Material = NULL;
m_ImageAliasMap[ "errorImageAlias" ] = imageData;
}
pVMTKeyValues = new KeyValues( "GameControls" );
pVMTKeyValues->SetInt( "$ignorez", 1 );
KeyValues *pProxies = new KeyValues( "Proxies" );
pProxies->AddSubKey( new KeyValues( "GameControlsProxy" ) );
pVMTKeyValues->AddSubKey( pProxies );
m_RenderMaterial.Init( "dynamic_render_texture", TEXTURE_GROUP_OTHER, pVMTKeyValues );
m_RenderMaterial->Refresh();
g_pGameUISystemMgrImpl->InitImageAlias( "defaultImageAlias" );
g_pGameUISystemMgrImpl->LoadImageAliasTexture( "defaultImageAlias", "vguiedit/pixel" );
}
}
IMaterialProxy *CGameUIDynamicTextures::CreateProxy( const char *proxyName )
{
return s_DynamicMaterialProxyFactory.CreateProxy( proxyName );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::Shutdown()
{
m_RenderMaterial.Shutdown();
m_TexturePage.Shutdown();
if ( m_pDynamicTexturePacker )
{
delete m_pDynamicTexturePacker;
}
m_pDynamicTexturePacker = NULL;
m_RenderMaterial = NULL;
m_bRegenerate = false;
}
void CGameUIDynamicTextures::SetImageEntry( const char *pEntryName, ImageAliasData_t &imageData )
{
m_ImageAliasMap[ pEntryName ] = imageData;
}
//-----------------------------------------------------------------------------
// Associate this image alias name with a .vtf texture.
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::LoadImageAlias( const char *pAlias, const char *pBaseTextureName )
{
if ( !pAlias || !*pAlias )
return;
if ( !pBaseTextureName || !*pBaseTextureName )
return;
CFmtStr texturePath;
texturePath.sprintf( "materials\\%s.vtf", pBaseTextureName );
if ( !g_pFullFileSystem->FileExists( texturePath.Access(), IsGameConsole() ? "MOD" : "GAME" ) )
{
Warning( "Unable to find game ui dynamic texture \"%s\"\n", texturePath.Access() );
}
if ( Q_strcmp( pBaseTextureName, "" ) == 0 )
{
ImageAliasData_t *pImageData = GetImageAliasData( "errorImageAlias" );
ImageAliasData_t imageData;
imageData.Init();
imageData.m_XPos = pImageData->m_XPos;
imageData.m_YPos = pImageData->m_YPos;
imageData.m_Width = pImageData->m_Width;
imageData.m_Height = pImageData->m_Height;
imageData.m_szBaseTextureName = pImageData->m_szBaseTextureName;
imageData.m_Material = pImageData->m_Material;
imageData.m_bIsInSheet = pImageData->m_bIsInSheet;
imageData.m_nNodeIndex = pImageData->m_nNodeIndex;
SetImageEntry( pAlias, imageData );
return;
}
Msg( "Loading Alias %s Texture %s\n", pAlias, pBaseTextureName );
CTextureReference pTexture;
pTexture.Init( pBaseTextureName, TEXTURE_GROUP_OTHER, true );
ImageAliasData_t *pImageData = GetImageAliasData( pAlias );
int nodeIndex = -1;
if ( m_pDynamicTexturePacker )
{
if ( !IsErrorImageAliasData( pImageData ) )
{
if ( pImageData->m_nNodeIndex != -1 )
{
// We already had something packed in there for this alias.
// Remove the old alias texture
m_pDynamicTexturePacker->RemoveRect( pImageData->m_nNodeIndex );
}
// Set up new imagedata values
pImageData->m_Width = pTexture->GetActualWidth();
pImageData->m_Height = pTexture->GetActualHeight();
pImageData->m_szBaseTextureName = pBaseTextureName;
}
else
{
ImageAliasData_t imageData;
imageData.m_Width = pTexture->GetActualWidth();
imageData.m_Height = pTexture->GetActualHeight();
imageData.m_szBaseTextureName = pBaseTextureName;
imageData.m_nRefCount = pImageData->m_nRefCount;
SetImageEntry( pAlias, imageData );
pImageData = GetImageAliasData( pAlias );
Assert( !IsErrorImageAliasData( pImageData ) );
}
int nSheetWidth = 0;
int nSheetHeight = 0;
GetDynamicSheetSize( nSheetWidth, nSheetHeight );
Assert( nSheetWidth != 0 );
Assert( nSheetHeight != 0 );
// If our texture is huge in some way, don't bother putting it in the packed texture.
if ( ( pTexture->GetActualWidth() << 1 ) < nSheetWidth || ( pTexture->GetActualHeight() << 1 ) < nSheetHeight )
{
// Put this texture into the packed render target texture.
Rect_t texRect;
texRect.x = 0;
texRect.y = 0;
texRect.width = pTexture->GetActualWidth();
texRect.height = pTexture->GetActualHeight();
nodeIndex = m_pDynamicTexturePacker->InsertRect( texRect );
}
}
// For debugging this will make no packing happen. Each texture is one draw call
//nodeIndex = -1;
pImageData->m_nNodeIndex = nodeIndex;
LoadImageAliasTexture( pAlias, pBaseTextureName );
}
//-----------------------------------------------------------------------------
// Release the entry for this alias in the packer.
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::ReleaseImageAlias( const char *pAlias )
{
if ( Q_strcmp( pAlias, "_rt_DynamicUI" ) == 0 )
return;
if ( Q_strcmp( pAlias, "errorImageAlias" ) == 0 )
return;
if ( Q_strcmp( pAlias, "defaultImageAlias" ) == 0 )
return;
ImageAliasData_t *pImageData = GetImageAliasData( pAlias );
if ( pImageData )
{
Assert( pImageData->m_nRefCount > 0 );
pImageData->m_nRefCount--;
if ( pImageData->m_nRefCount == 0 )
{
if ( pImageData->m_bIsInSheet )
{
Msg( "Releasing Alias %s\n", pAlias );
m_pDynamicTexturePacker->RemoveRect( pImageData->m_nNodeIndex );
}
pImageData->Init();
}
}
}
//-----------------------------------------------------------------------------
// Associate this image alias name with a .vtf texture.
// This fxn loads the texture into the GameControls shader and makes a material
// for you
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::LoadImageAliasTexture( const char *pAlias, const char *pBaseTextureName )
{
if ( !pBaseTextureName || !*pBaseTextureName )
return;
CTextureReference pTexture;
pTexture.Init( pBaseTextureName, TEXTURE_GROUP_OTHER, true );
ImageAliasData_t *pImageData = GetImageAliasData( pAlias );
// Now set up the material for the new imagedata.
if ( pImageData->m_nNodeIndex == -1 )// it won't fit in the map, give it its own material, it is its own draw call.
{
// Material names must be different
CUtlVector<char *> words;
V_SplitString( pImageData->m_szBaseTextureName, "/", words );
CFmtStr materialName;
materialName.sprintf( "dynamictx_%s", words[words.Count()-1] );
KeyValues *pVMTKeyValues = new KeyValues( "GameControls" );
pVMTKeyValues->SetString( "$basetexture", pImageData->m_szBaseTextureName );
CMaterialReference material;
material.Init( materialName, TEXTURE_GROUP_OTHER, pVMTKeyValues );
material->Refresh();
pImageData->m_Material = material;
pImageData->m_bIsInSheet = false;
}
else // Do this if it fit in the packed texture.
{
if ( !m_RenderMaterial )
return;
pImageData->m_Material.Init( GetImageAliasMaterial( "_rt_DynamicUI" ) );
Assert( pImageData->m_Material );
pImageData->m_bIsInSheet = true;
const CTexturePacker::TreeEntry_t &newEntry = m_pDynamicTexturePacker->GetEntry( pImageData->m_nNodeIndex );
Assert( newEntry.rc.width == pImageData->m_Width );
Assert( newEntry.rc.height == pImageData->m_Height );
pImageData->m_XPos = newEntry.rc.x;
pImageData->m_YPos = newEntry.rc.y;
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
pRenderContext->PushRenderTargetAndViewport( m_TexturePage, NULL, pImageData->m_XPos, pImageData->m_YPos, pImageData->m_Width, pImageData->m_Height );
pRenderContext->MatrixMode( MATERIAL_PROJECTION );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
pRenderContext->Scale( 1, -1, 1 );
float flPixelOffsetX = 0.5f;
float flPixelOffsetY = 0.5f;
pRenderContext->Ortho( flPixelOffsetX, flPixelOffsetY, pImageData->m_Width + flPixelOffsetX, pImageData->m_Height + flPixelOffsetY, -1.0f, 1.0f );
//pRenderContext->Ortho( 0, 0, pImageData->m_Width, pImageData->m_Height, -1.0f, 1.0f );
// Clear to random color. Useful for testing.
//pRenderContext->ClearColor3ub( rand()%256, rand()%256, rand()%256 );
pRenderContext->ClearColor4ub( 0, 0, 0, 255 );
pRenderContext->ClearBuffers( true, false );
// make sure there is no translation and rotation laying around
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->PushMatrix();
pRenderContext->LoadIdentity();
pRenderContext->Bind( m_RenderMaterial, (void *)pImageData->m_szBaseTextureName.Get() );
int x = 0;
int y = 0;
int wide = pImageData->m_Width;
int tall = pImageData->m_Height;
unsigned char drawcolor[4];
drawcolor[0] = 255;
drawcolor[1] = 255;
drawcolor[2] = 255;
drawcolor[3] = 255;
IMesh *pMesh = pRenderContext->GetDynamicMesh( true );
if ( pMesh )
{
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Position3f( x, y, 0 );
meshBuilder.Color4ubv( drawcolor );
meshBuilder.TexCoord2f( 0, 0, 0 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( wide, y, 0 );
meshBuilder.Color4ubv( drawcolor );
meshBuilder.TexCoord2f( 0, 1, 0 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( wide, tall, 0 );
meshBuilder.Color4ubv( drawcolor );
meshBuilder.TexCoord2f( 0, 1, 1 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( x, tall, 0 );
meshBuilder.Color4ubv( drawcolor );
meshBuilder.TexCoord2f( 0, 0, 1 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.End();
pMesh->Draw();
}
// Restore the matrices
pRenderContext->MatrixMode( MATERIAL_PROJECTION );
pRenderContext->PopMatrix();
pRenderContext->MatrixMode( MATERIAL_MODEL );
pRenderContext->PopMatrix();
pRenderContext->MatrixMode( MATERIAL_VIEW );
pRenderContext->PopMatrix();
pRenderContext->PopRenderTargetAndViewport();
}
}
//-----------------------------------------------------------------------------
// Return the material bound to this image alias.
// If the texture was not found you will see the purple and black checkerboard
// error texture.
//-----------------------------------------------------------------------------
IMaterial *CGameUIDynamicTextures::GetImageAliasMaterial( const char *pAlias )
{
if ( m_ImageAliasMap.Defined( pAlias ) )
{
return m_ImageAliasMap[pAlias].m_Material;
}
return m_ImageAliasMap[ "errorImageAlias" ].m_Material;
}
//-----------------------------------------------------------------------------
// Return the data bound to this image alias.
// If the alias was not found you will see the purple and black checkerboard
// error texture.
//-----------------------------------------------------------------------------
ImageAliasData_t *CGameUIDynamicTextures::GetImageAliasData( const char *pAlias )
{
if ( m_ImageAliasMap.Defined( pAlias ) )
{
return &m_ImageAliasMap[pAlias];
}
return &m_ImageAliasMap[ "errorImageAlias" ];
}
//-----------------------------------------------------------------------------
// Return true if this data is the error alias
//-----------------------------------------------------------------------------
bool CGameUIDynamicTextures::IsErrorImageAliasData( ImageAliasData_t *pData )
{
return ( &m_ImageAliasMap[ "errorImageAlias" ] ) == pData;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::GetDynamicSheetSize( int &nWidth, int &nHeight )
{
nWidth = m_TexturePage->GetActualWidth();
nHeight = m_TexturePage->GetActualHeight();
}
//-----------------------------------------------------------------------------
// Draw the dynamic texture associated with this alias at x, y
// It is drawn full size. This fxn is modeled off of CGameUISystemSurface::DrawFontTexture()
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::DrawDynamicTexture( const char *pAlias, int x, int y )
{
if ( !pAlias || !*pAlias )
return;
ImageAliasData_t *pImageData = GetImageAliasData( pAlias );
int wide = 0;
int tall = 0;
if ( !pImageData->m_bIsInSheet )
{
wide = pImageData->m_Width;
tall = pImageData->m_Height;
}
else
{
GetDynamicSheetSize( wide, tall );
}
color32 drawcolor;
drawcolor.r = 255;
drawcolor.g = 255;
drawcolor.b = 255;
drawcolor.a = 255;
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
IMesh *pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, pImageData->m_Material );
if ( !pMesh )
return;
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Position3f( x, y, 0 );
meshBuilder.Color4ub( drawcolor.r, drawcolor.g, drawcolor.b, drawcolor.a );
meshBuilder.TexCoord3f( 0, 0, 0, 0 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x + wide, y, 0 );
meshBuilder.Color4ub( drawcolor.r, drawcolor.g, drawcolor.b, drawcolor.a );
meshBuilder.TexCoord3f( 0, 1, 0, 0 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x + wide, y + tall, 0 );
meshBuilder.Color4ub( drawcolor.r, drawcolor.g, drawcolor.b, drawcolor.a );
meshBuilder.TexCoord3f( 0, 1, 1, 0 );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x, y + tall, 0 );
meshBuilder.Color4ub( drawcolor.r, drawcolor.g, drawcolor.b, drawcolor.a );
meshBuilder.TexCoord3f( 0, 0, 1, 0 );
meshBuilder.AdvanceVertex();
meshBuilder.End();
pMesh->Draw();
}
//-----------------------------------------------------------------------------
// Reload all textures into the rendertarget.
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::OnRestore( int nChangeFlags )
{
m_bRegenerate = true;
}
//-----------------------------------------------------------------------------
// Reload all textures into the rendertarget.
//-----------------------------------------------------------------------------
void CGameUIDynamicTextures::RegenerateTexture( int nChangeFlags )
{
if ( !m_bRegenerate )
return;
int numEntries = m_ImageAliasMap.GetNumStrings();
for ( int i = 0; i < numEntries; ++i )
{
const char *pAlias = m_ImageAliasMap.String( i );
ImageAliasData_t *pImageData = GetImageAliasData( pAlias );
if ( IsErrorImageAliasData( pImageData ) )
continue;
if ( Q_strcmp( pAlias, "_rt_DynamicUI") == 0 )
continue;
if ( !pImageData->m_szBaseTextureName || !*pImageData->m_szBaseTextureName )
continue;
ITexture *pTexture = g_pMaterialSystem->FindTexture( pImageData->m_szBaseTextureName.Get(), TEXTURE_GROUP_OTHER, true );
Assert( pTexture );
pTexture->Download();
LoadImageAliasTexture( pAlias, pImageData->m_szBaseTextureName );
}
}

View File

@@ -0,0 +1,108 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUIDYNAMICTEXTURES_H
#define GAMEUIDYNAMICTEXTURES_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlobjectreference.h"
#include "tier1/utldict.h"
#include "tier1/utlstring.h"
#include "tier1/utlstringmap.h"
#include "materialsystem/materialsystemutil.h"
#include "materialsystem/imaterialproxy.h"
#include "bitmap/texturepacker.h"
//----------------------------------------------------------------------------
// Helper class for entries in the packer
//----------------------------------------------------------------------------
class ImageAliasData_t
{
public:
ImageAliasData_t()
{
Init();
}
void Init()
{
m_XPos = 0;
m_YPos = 0;
m_Width = 0;
m_Height = 0;
m_szBaseTextureName = "";
m_Material = NULL;
m_bIsInSheet = false;
m_nNodeIndex = -1;
m_nRefCount = 0;
}
int m_XPos;
int m_YPos;
int m_Width;
int m_Height;
CUtlString m_szBaseTextureName;
CMaterialReference m_Material;
bool m_bIsInSheet;
int m_nNodeIndex;
int m_nRefCount;
private:
ImageAliasData_t( ImageAliasData_t &ref ) { }
};
//-----------------------------------------------------------------------------
// A template describing how a gameUI will function
// It loads CVguiCompiledDoc
//-----------------------------------------------------------------------------
class CGameUIDynamicTextures
{
public:
CGameUIDynamicTextures();
~CGameUIDynamicTextures();
void InitRenderTargets();
IMaterialProxy *CreateProxy( const char *proxyName );
void Shutdown();
void SetImageEntry( const char *pEntryName, ImageAliasData_t &imageData );
void LoadImageAlias( const char *pAlias, const char *pBaseTextureName );
void ReleaseImageAlias( const char *pAlias );
IMaterial *GetImageAliasMaterial( const char *pAlias );
ImageAliasData_t *GetImageAliasData( const char *pAlias );
bool IsErrorImageAliasData( ImageAliasData_t *pData );
void GetDynamicSheetSize( int &nWidth, int &nHeight );
void DrawDynamicTexture( const char *pAlias, int x, int y );
void OnRestore( int nChangeFlags );
void RegenerateTexture( int nChangeFlags );
private:
void LoadImageAliasTexture( const char *pAlias, const char *pBaseTextureName );
// Stores the actual texture we're writing into
CTextureReference m_TexturePage;
CTexturePacker *m_pDynamicTexturePacker;
CUtlStringMap< ImageAliasData_t > m_ImageAliasMap;
CMaterialReference m_RenderMaterial; // used to render dynamic textures into the render target.
bool m_bRegenerate;
};
#endif // GAMEUIDYNAMICTEXTURES_H

View File

@@ -0,0 +1,885 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#define SUPPORT_CUSTOM_FONT_FORMAT
#ifdef SUPPORT_CUSTOM_FONT_FORMAT
#define _WIN32_WINNT 0x0500
#endif
#include "gameuischeme.h"
#include "gameuisystemsurface.h"
#include "vgui/ISystem.h"
#include "tier1/utlbuffer.h"
#include "gameuisystemmgr.h"
#include "tier1/KeyValues.h"
#include "vgui_surfacelib/fontmanager.h"
#include "vgui/isurface.h"
#include "vgui_controls/controls.h" // has system()
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
#include "xbox/xboxstubs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define FONT_ALIAS_NAME_LENGTH 64
CGameUISchemeManager g_GameUISchemeManager;
CGameUISchemeManager *g_pGameUISchemeManager = &g_GameUISchemeManager;
//-----------------------------------------------------------------------------
// Helper function for getting the language the game ui should use.
//-----------------------------------------------------------------------------
static void HelperGetLanguage( char *pLanguageBuf, int bufSize )
{
bool bValid = false;
if ( IsPC() )
{
bValid = vgui::system()->GetRegistryString( "HKEY_CURRENT_USER\\Software\\Valve\\Steam\\Language", pLanguageBuf, bufSize - 1 );
}
else
{
Q_strncpy( pLanguageBuf, XBX_GetLanguageString(), bufSize );
bValid = true;
}
if ( !bValid )
{
Q_strncpy( pLanguageBuf, "english", bufSize );
}
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameUISchemeManager::CGameUISchemeManager()
{
// 0th element is null, since that would be an invalid handle
CGameUIScheme *nullScheme = new CGameUIScheme();
m_Schemes.AddToTail(nullScheme);
Assert( g_pGameUISystemSurface );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
CGameUISchemeManager::~CGameUISchemeManager()
{
int i;
for ( i = 0; i < m_Schemes.Count(); i++ )
{
delete m_Schemes[i];
m_Schemes[i] = NULL;
}
m_Schemes.RemoveAll();
Shutdown( false );
}
//-----------------------------------------------------------------------------
// Purpose: Reloads the schemes from the files
//-----------------------------------------------------------------------------
void CGameUISchemeManager::ReloadSchemes()
{
int count = m_Schemes.Count();
Shutdown( false );
// reload the scheme
for (int i = 1; i < count; i++)
{
LoadSchemeFromFile( m_Schemes[i]->GetFileName(), m_Schemes[i]->GetName() );
}
}
//-----------------------------------------------------------------------------
// Purpose: Reload the fonts in all schemes
//-----------------------------------------------------------------------------
void CGameUISchemeManager::ReloadFonts( int inScreenTall )
{
for (int i = 1; i < m_Schemes.Count(); i++)
{
m_Schemes[i]->ReloadFontGlyphs( inScreenTall );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISchemeManager::Shutdown( bool full )
{
// Full shutdown kills the null scheme
for( int i = full ? 0 : 1; i < m_Schemes.Count(); i++ )
{
m_Schemes[i]->Shutdown( full );
}
if ( full )
{
m_Schemes.RemoveAll();
}
}
//-----------------------------------------------------------------------------
// Purpose: Find an already loaded scheme
//-----------------------------------------------------------------------------
IGameUIScheme * CGameUISchemeManager::FindLoadedScheme( const char *pFilename )
{
// Find the scheme in the list of already loaded schemes
for ( int i = 1; i < m_Schemes.Count(); i++ )
{
char const *schemeFileName = m_Schemes[i]->GetFileName();
if ( !stricmp( schemeFileName, pFilename ) )
return m_Schemes[i];
}
return NULL;
}
//-----------------------------------------------------------------------------
// First scheme loaded becomes the default scheme,
// and all subsequent loaded scheme are derivatives of that
//-----------------------------------------------------------------------------
IGameUIScheme * CGameUISchemeManager::LoadSchemeFromFileEx( const char *pFilename, const char *tag )
{
// Look to see if we've already got this scheme...
CGameUIScheme * hScheme = ( CGameUIScheme * ) FindLoadedScheme( pFilename );
if ( hScheme )
{
if ( hScheme->IsActive() )
{
if ( IsPC() )
{
hScheme->ReloadFontGlyphs();
}
return hScheme;
}
}
else
{
hScheme = new CGameUIScheme();
m_Schemes.AddToTail( hScheme );
}
KeyValues *data;
data = new KeyValues("Scheme");
data->UsesEscapeSequences( true ); // VGUI uses this
// look first in skins directory
bool result = data->LoadFromFile( g_pFullFileSystem, pFilename, "SKIN" );
if (!result)
{
result = data->LoadFromFile( g_pFullFileSystem, pFilename, "GAME" );
if ( !result )
{
// look in any directory
result = data->LoadFromFile( g_pFullFileSystem, pFilename, NULL );
}
}
if (!result)
{
data->deleteThis();
return 0;
}
if ( IsPC() )
{
ConVarRef cl_hud_minmode( "cl_hud_minmode", true );
if ( cl_hud_minmode.IsValid() && cl_hud_minmode.GetBool() )
{
data->ProcessResolutionKeys( "_minmode" );
}
}
hScheme->SetActive( true );
hScheme->LoadFromFile( pFilename, tag, data );
return hScheme;
}
//-----------------------------------------------------------------------------
// Purpose: loads a scheme from disk
//-----------------------------------------------------------------------------
IGameUIScheme * CGameUISchemeManager::LoadSchemeFromFile( const char *fileName, const char *tag )
{
return LoadSchemeFromFileEx( fileName, tag );
}
//-----------------------------------------------------------------------------
// Purpose: returns a handle to the default (first loaded) scheme
//-----------------------------------------------------------------------------
IGameUIScheme * CGameUISchemeManager::GetDefaultScheme()
{
if ( m_Schemes.Count() >= 2 )
return m_Schemes[1];
else if ( m_Schemes.Count() > 0 )
return m_Schemes[0];
else
return NULL;
}
//-----------------------------------------------------------------------------
// Purpose: returns a handle to the scheme identified by "tag"
//-----------------------------------------------------------------------------
IGameUIScheme * CGameUISchemeManager::GetScheme( const char *tag )
{
for ( int i=1; i<m_Schemes.Count(); i++ )
{
if ( !stricmp( tag, m_Schemes[i]->GetName() ) )
{
return m_Schemes[i];
}
}
return GetDefaultScheme(); // default scheme
}
//-----------------------------------------------------------------------------
// gets the proportional coordinates for doing screen-size independant panel layouts
// use these for font, image and panel size scaling (they all use the pixel height of the display for scaling)
//-----------------------------------------------------------------------------
int CGameUISchemeManager::GetProportionalScaledValueEx( CGameUIScheme *pScheme, int normalizedValue, int screenTall )
{
return GetProportionalScaledValue( normalizedValue, screenTall );
}
//-----------------------------------------------------------------------------
// Purpose: converts a value into proportional mode
//-----------------------------------------------------------------------------
int CGameUISchemeManager::GetProportionalScaledValue( int normalizedValue, int screenTall )
{
int tall;
if ( screenTall == -1 )
{
g_pGameUISystemMgrImpl->GetScreenHeightForFontLoading( tall );
}
else
{
tall = screenTall;
}
return GetProportionalScaledValue_( tall, normalizedValue );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int CGameUISchemeManager::GetProportionalScaledValue_( int screenTall, int normalizedValue )
{
int baseWide, baseTall;
g_pGameUISystemSurface->GetProportionalBase( baseWide, baseTall );
double scale = (double)screenTall / (double)baseTall;
return (int)( normalizedValue * scale );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUISchemeManager::SpewFonts( void )
{
for ( int i = 1; i < m_Schemes.Count(); i++ )
{
m_Schemes[i]->SpewFonts();
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUISchemeManager::SetLanguage( const char *pLanguage )
{
g_pGameUISystemSurface->SetLanguage( pLanguage );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
const char *CGameUISchemeManager::GetLanguage()
{
return g_pGameUISystemSurface->GetLanguage();
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameUIScheme::CGameUIScheme()
{
m_pFileName = "";
m_pTag = "";
m_pData = NULL;
SetActive( false );
}
CGameUIScheme::~CGameUIScheme()
{
}
//-----------------------------------------------------------------------------
// Purpose: loads a scheme from from disk into memory
//-----------------------------------------------------------------------------
void CGameUIScheme::LoadFromFile( const char *pFilename, const char *inTag, KeyValues *inKeys )
{
COM_TimestampedLog( "CScheme::LoadFromFile( %s )", pFilename );
m_pFileName = pFilename;
m_pData = inKeys;
// override the scheme name with the tag name
KeyValues *name = m_pData->FindKey( "Name", true );
name->SetString("Name", inTag);
if ( inTag )
{
m_pTag = inTag;
}
else
{
Error( "You need to name the scheme (%s)!", m_pFileName.Get() );
m_pTag = "default";
}
LoadFonts();
}
//-----------------------------------------------------------------------------
// Purpose: Set the range of character values this font can be used on
//-----------------------------------------------------------------------------
bool CGameUIScheme::GetFontRange( const char *fontname, int &nMin, int &nMax )
{
for ( int i = 0 ; i < m_FontRanges.Count() ; i++ )
{
if ( Q_stricmp( m_FontRanges[i]._fontName.String(), fontname ) == 0 )
{
nMin = m_FontRanges[i]._min;
nMax = m_FontRanges[i]._max;
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Get the range of character values this font can be used on
//-----------------------------------------------------------------------------
void CGameUIScheme::SetFontRange( const char *fontname, int nMin, int nMax )
{
for ( int i = 0 ; i < m_FontRanges.Count() ; i++ )
{
if ( Q_stricmp( m_FontRanges[i]._fontName.String(), fontname ) == 0 )
{
m_FontRanges[i]._min = nMin;
m_FontRanges[i]._max = nMax;
return;
}
}
// not already in our list
int iIndex = m_FontRanges.AddToTail();
m_FontRanges[iIndex]._fontName = fontname;
m_FontRanges[iIndex]._min = nMin;
m_FontRanges[iIndex]._max = nMax;
}
//-----------------------------------------------------------------------------
// Purpose: adds all the font specifications to the surface
//-----------------------------------------------------------------------------
void CGameUIScheme::LoadFonts()
{
// get our language
const char *pLanguage = g_GameUISchemeManager.GetLanguage();
// add our custom fonts
for ( KeyValues *kv = m_pData->FindKey("CustomFontFiles", true)->GetFirstSubKey(); kv != NULL; kv = kv->GetNextKey() )
{
const char *fontFile = kv->GetString();
if (fontFile && *fontFile)
{
g_pGameUISystemSurface->AddCustomFontFile( fontFile );
}
else
{
// we have a block to read
int nRangeMin = 0, nRangeMax = 0;
const char *pszName = NULL;
bool bUseRange = false;
for ( KeyValues *pData = kv->GetFirstSubKey(); pData != NULL; pData = pData->GetNextKey() )
{
const char *pszKey = pData->GetName();
if ( !Q_stricmp( pszKey, "font" ) )
{
fontFile = pData->GetString();
}
else if ( !Q_stricmp( pszKey, "name" ) )
{
pszName = pData->GetString();
}
else
{
// we must have a language
if ( Q_stricmp( pLanguage, pszKey ) == 0 ) // matches the language we're running?
{
// get the range
KeyValues *pRange = pData->FindKey( "range" );
if ( pRange )
{
bUseRange = true;
sscanf( pRange->GetString(), "%x %x", &nRangeMin, &nRangeMax );
if ( nRangeMin > nRangeMax )
{
int nTemp = nRangeMin;
nRangeMin = nRangeMax;
nRangeMax = nTemp;
}
}
}
}
}
if ( fontFile && *fontFile )
{
g_pGameUISystemSurface->AddCustomFontFile( fontFile );
if ( bUseRange )
{
SetFontRange( pszName, nRangeMin, nRangeMax );
}
}
}
}
// add bitmap fonts
for ( KeyValues *kv = m_pData->FindKey("BitmapFontFiles", true)->GetFirstSubKey(); kv != NULL; kv = kv->GetNextKey() )
{
const char *fontFile = kv->GetString();
if (fontFile && *fontFile)
{
bool bSuccess = g_pGameUISystemSurface->AddBitmapFontFile( fontFile );
if ( bSuccess )
{
// refer to the font by a user specified symbol
g_pGameUISystemSurface->SetBitmapFontName( kv->GetName(), fontFile );
}
}
}
// create the fonts
for (KeyValues *kv = m_pData->FindKey("Fonts", true)->GetFirstSubKey(); kv != NULL; kv = kv->GetNextKey())
{
for ( int i = 0; i < 2; i++ )
{
// create the base font
bool proportionalFont = i ? true : false;
const char *fontName = GetMungedFontName( kv->GetName(), m_pTag.Get(), proportionalFont ); // first time it adds a normal font, and then a proportional one
FontHandle_t font = g_pGameUISystemSurface->CreateFont();
int j = m_FontAliases.AddToTail();
m_FontAliases[j]._fontName = fontName;
m_FontAliases[j]._trueFontName = kv->GetName();
m_FontAliases[j]._font = font;
m_FontAliases[j].m_bProportional = proportionalFont;
}
}
// load in the font glyphs
ReloadFontGlyphs();
}
//-----------------------------------------------------------------------------
// Purpose: Reloads all scheme fonts
// Supply a language if you don't want to use the one in the registry.
//-----------------------------------------------------------------------------
void CGameUIScheme::ReloadFontGlyphs( int inScreenTall )
{
int screenTall;
// get our current resolution
if ( inScreenTall == -1 )
{
//int screenWide;
g_pGameUISystemMgrImpl->GetScreenHeightForFontLoading( screenTall );
}
else // this will make fonts be the correct size in the editor, where the stage size is the screen size.
{
screenTall = inScreenTall;
}
// check our language; some have minimum sizes
int minimumFontHeight = GetMinimumFontHeightForCurrentLanguage( g_GameUISchemeManager.GetLanguage() );
// add the data to all the fonts
KeyValues *fonts = m_pData->FindKey( "Fonts", true );
for (int i = 0; i < m_FontAliases.Count(); i++)
{
KeyValues *kv = fonts->FindKey( m_FontAliases[i]._trueFontName.String(), true );
// walk through creating adding the first matching glyph set to the font
for ( KeyValues *fontdata = kv->GetFirstSubKey(); fontdata != NULL; fontdata = fontdata->GetNextKey() )
{
// skip over fonts not meant for this resolution
int fontYResMin = 0, fontYResMax = 0;
sscanf( fontdata->GetString( "yres", "" ), "%d %d", &fontYResMin, &fontYResMax );
if ( fontYResMin )
{
if ( !fontYResMax )
{
fontYResMax = fontYResMin;
}
// check the range
if ( screenTall < fontYResMin || screenTall > fontYResMax )
continue;
}
int flags = 0;
if (fontdata->GetInt( "italic" ))
{
flags |= FONTFLAG_ITALIC;
}
if (fontdata->GetInt( "underline" ))
{
flags |= FONTFLAG_UNDERLINE;
}
if (fontdata->GetInt( "strikeout" ))
{
flags |= FONTFLAG_STRIKEOUT;
}
if (fontdata->GetInt( "symbol" ))
{
flags |= FONTFLAG_SYMBOL;
}
if (fontdata->GetInt( "antialias" ) && g_pGameUISystemSurface->SupportsFontFeature( FONT_FEATURE_ANTIALIASED_FONTS ) )
{
flags |= FONTFLAG_ANTIALIAS;
}
if (fontdata->GetInt( "dropshadow" ) && g_pGameUISystemSurface->SupportsFontFeature( FONT_FEATURE_DROPSHADOW_FONTS ) )
{
flags |= FONTFLAG_DROPSHADOW;
}
if (fontdata->GetInt( "outline" ) && g_pGameUISystemSurface->SupportsFontFeature( FONT_FEATURE_OUTLINE_FONTS ) )
{
flags |= FONTFLAG_OUTLINE;
}
if (fontdata->GetInt( "custom" ))
{
flags |= FONTFLAG_CUSTOM;
}
if (fontdata->GetInt( "bitmap" ))
{
flags |= FONTFLAG_BITMAP;
}
if (fontdata->GetInt( "rotary" ))
{
flags |= FONTFLAG_ROTARY;
}
if (fontdata->GetInt( "additive" ))
{
flags |= FONTFLAG_ADDITIVE;
}
int fontTall = fontdata->GetInt( "tall" );
int blur = fontdata->GetInt( "blur" );
int scanlines = fontdata->GetInt( "scanlines" );
float scalex = fontdata->GetFloat( "scalex", 1.0f );
float scaley = fontdata->GetFloat( "scaley", 1.0f );
// only grow this font if it doesn't have a resolution filter specified
if ( ( !fontYResMin && !fontYResMax ) && m_FontAliases[i].m_bProportional )
{
fontTall = g_GameUISchemeManager.GetProportionalScaledValueEx( this, fontTall, screenTall );
blur = g_GameUISchemeManager.GetProportionalScaledValueEx( this, blur );
scanlines = g_GameUISchemeManager.GetProportionalScaledValueEx( this, scanlines );
scalex = g_GameUISchemeManager.GetProportionalScaledValueEx( this, scalex * 10000.0f ) * 0.0001f;
scaley = g_GameUISchemeManager.GetProportionalScaledValueEx( this, scaley * 10000.0f ) * 0.0001f;
}
// clip the font size so that fonts can't be too big
if ( fontTall > 127 )
{
fontTall = 127;
}
// check our minimum font height
if ( fontTall < minimumFontHeight )
{
fontTall = minimumFontHeight;
}
if ( flags & FONTFLAG_BITMAP )
{
// add the new set
g_pGameUISystemSurface->SetBitmapFontGlyphSet(
m_FontAliases[i]._font,
g_pGameUISystemSurface->GetBitmapFontName( fontdata->GetString( "name" ) ),
scalex,
scaley,
flags);
}
else
{
int nRangeMin, nRangeMax;
if ( GetFontRange( fontdata->GetString( "name" ), nRangeMin, nRangeMax ) )
{
// add the new set
g_pGameUISystemSurface->SetFontGlyphSet(
m_FontAliases[i]._font, fontdata->GetString( "name" ),
fontTall, fontdata->GetInt( "weight" ), blur, scanlines, flags, nRangeMin, nRangeMax);
}
else
{
// add the new set
g_pGameUISystemSurface->SetFontGlyphSet( m_FontAliases[i]._font, fontdata->GetString( "name" ),
fontTall, fontdata->GetInt( "weight" ), blur, scanlines, flags);
}
}
// don't add any more
break;
}
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUIScheme::SpewFonts( void )
{
Msg( "Game UI Scheme: %s (%s)\n", GetName(), GetFileName() );
for ( int i = 0; i < m_FontAliases.Count(); i++ )
{
Msg( " %2d: HFont:0x%8.8x, %s, %s, font:%s, tall:%d\n",
i,
m_FontAliases[i]._font,
m_FontAliases[i]._trueFontName.String(),
m_FontAliases[i]._fontName.String(),
g_pGameUISystemSurface->GetFontName( m_FontAliases[i]._font ),
g_pGameUISystemSurface->GetFontTall( m_FontAliases[i]._font ) );
}
}
//-----------------------------------------------------------------------------
// Purpose: Kills the scheme
//-----------------------------------------------------------------------------
void CGameUIScheme::Shutdown( bool full )
{
SetActive( false );
m_FontRanges.RemoveAll();
if (m_pData)
{
m_pData->deleteThis();
m_pData = NULL;
}
if ( full )
{
delete this;
}
}
//-----------------------------------------------------------------------------
// Finds a font in the alias list
//-----------------------------------------------------------------------------
FontHandle_t CGameUIScheme::FindFontInAliasList( const char *fontName )
{
// FIXME: Slow!!!
for (int i = m_FontAliases.Count(); --i >= 0; )
{
if ( !strnicmp( fontName, m_FontAliases[i]._fontName.String(), FONT_ALIAS_NAME_LENGTH ) )
return m_FontAliases[i]._font;
}
// No dice
return 0;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : font -
// Output : char const
//-----------------------------------------------------------------------------
char const *CGameUIScheme::GetFontName( const FontHandle_t &font )
{
for (int i = m_FontAliases.Count(); --i >= 0; )
{
FontHandle_t fnt = ( FontHandle_t )m_FontAliases[i]._font;
if ( fnt == font )
return m_FontAliases[i]._trueFontName.String();
}
return "<Unknown font>";
}
//-----------------------------------------------------------------------------
// material Setting methods
//-----------------------------------------------------------------------------
FontHandle_t CGameUIScheme::GetFont( const char *fontName, bool proportional )
{
// First look in the list of aliases...
return FindFontInAliasList( GetMungedFontName( fontName, m_pTag.Get(), proportional ) );
}
//-----------------------------------------------------------------------------
// Return the vgui name of the font that is the same truefont name and one size up.
// bUp is if true you want the next size up or the next size down.
//-----------------------------------------------------------------------------
FontHandle_t CGameUIScheme::GetFontNextSize( bool bUp, const char *fontName, bool proportional )
{
FontHandle_t currentFontHandle = GetFont( fontName, proportional );
// Current font name wasn't found.
if ( currentFontHandle == 0 )
{
return currentFontHandle;
}
int currentFontTall = g_pGameUISystemSurface->GetFontTall( currentFontHandle );
const char* pCurrentFontName = g_pGameUISystemSurface->GetFontName( currentFontHandle );
// Now find the closest font with this name that is the smallest size up
int sizeDifference = INT_MAX;
FontHandle_t closestFontHandle = 0;
for (int i = m_FontAliases.Count(); --i > 0; )
{
if ( proportional != m_FontAliases[i].m_bProportional )
continue;
FontHandle_t testFontHandle = m_FontAliases[i]._font;
const char* pTestFontName = g_pGameUISystemSurface->GetFontName( testFontHandle );
if ( currentFontHandle != testFontHandle )
{
if ( !Q_stricmp( pCurrentFontName, pTestFontName ) ) // font name is the same.
{
int thisFontTall = g_pGameUISystemSurface->GetFontTall( testFontHandle );
int diff;
if ( bUp ) // get next size up
{
diff = thisFontTall - currentFontTall;
}
else // get next size down.
{
diff = currentFontTall - thisFontTall;
}
if ( diff > 0 && diff < sizeDifference )
{
sizeDifference = diff;
closestFontHandle = testFontHandle;
}
}
}
}
if ( closestFontHandle != 0 )
{
return closestFontHandle;
}
else
{
return currentFontHandle;
}
}
//-----------------------------------------------------------------------------
// Purpose: returns a char string of the munged name this font is stored as in the font manager
//-----------------------------------------------------------------------------
const char *CGameUIScheme::GetMungedFontName( const char *fontName, const char *scheme, bool proportional )
{
static char mungeBuffer[ 64 ];
if ( scheme )
{
Q_snprintf( mungeBuffer, sizeof( mungeBuffer ), "%s%s-%s", fontName, scheme, proportional ? "p" : "no" );
}
else
{
Q_snprintf( mungeBuffer, sizeof( mungeBuffer ), "%s-%s", fontName, proportional ? "p" : "no" ); // we don't want the "(null)" snprintf appends
}
return mungeBuffer;
}
//-----------------------------------------------------------------------------
// Purpose: gets the minimum font height for the current language
//-----------------------------------------------------------------------------
int CGameUIScheme::GetMinimumFontHeightForCurrentLanguage( const char *pLanguage )
{
char language[64];
bool bValid;
if ( IsPC() )
{
if ( pLanguage )
{
Q_strncpy( language, pLanguage, sizeof(language)-1 );
bValid = true;
}
else
{
bValid = vgui::system()->GetRegistryString( "HKEY_CURRENT_USER\\Software\\Valve\\Steam\\Language", language, sizeof(language)-1 );
}
}
else
{
Q_strncpy( language, XBX_GetLanguageString(), sizeof( language ) );
bValid = true;
}
if ( bValid )
{
if (!stricmp(language, "korean")
|| !stricmp(language, "koreana")
|| !stricmp(language, "tchinese")
|| !stricmp(language, "schinese")
|| !stricmp(language, "japanese"))
{
// the bitmap-based fonts for these languages simply don't work with a pt. size of less than 9 (13 pixels)
return 13;
}
if ( !stricmp(language, "thai" ) )
{
// thai has problems below 18 pts
return 18;
}
}
// no special minimum height required
return 0;
}
void CGameUIScheme::SetActive( bool bActive )
{
m_bActive = bActive;
}
bool CGameUIScheme::IsActive() const
{
return m_bActive;
}

View File

@@ -0,0 +1,160 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUISCHEME_H
#define GAMEUISCHEME_H
#ifdef _WIN32
#pragma once
#endif
#include "igameuisystemmgr.h"
#include "vgui_surfacelib/ifontsurface.h"
#include "tier1/utlstring.h"
//#include "color.h"
#include "tier1/utlsymbol.h"
class CGameUISystemSurface;
class KeyValues;
//-----------------------------------------------------------------------------
// Game UI version of a vgui scheme
//-----------------------------------------------------------------------------
class CGameUIScheme : public IGameUIScheme
{
public:
CGameUIScheme();
~CGameUIScheme();
FontHandle_t GetFont( const char *fontName, bool proportional = false );
FontHandle_t GetFontNextSize( bool bUp, const char *fontName, bool proportional = false );
//Color GetColor( const char *colorName, Color defaultColor ){ return Color( 255, 255, 255, 255 ); }
// These fxns are very similar to CScheme.
void Shutdown( bool full );
void LoadFromFile( const char *pFilename, const char *inTag, KeyValues *inKeys );
// Gets at the scheme's name
const char *GetName() { return m_pTag; }
const char *GetFileName() { return m_pFileName; }
char const *GetFontName( const FontHandle_t &font );
void ReloadFontGlyphs( int inScreenTall = -1 );
void SpewFonts();
bool GetFontRange( const char *fontname, int &nMin, int &nMax );
void SetFontRange( const char *fontname, int nMin, int nMax );
void SetActive( bool bActive );
bool IsActive() const;
private:
const char *GetMungedFontName( const char *fontName, const char *scheme, bool proportional );
void LoadFonts();
int GetMinimumFontHeightForCurrentLanguage( const char *pLanguage = NULL );
FontHandle_t FindFontInAliasList( const char *fontName );
bool m_bActive;
CUtlString m_pFileName;
CUtlString m_pTag;
KeyValues *m_pData;
#pragma pack(1)
struct fontalias_t
{
CUtlSymbol _fontName;
CUtlSymbol _trueFontName;
unsigned short _font : 15;
unsigned short m_bProportional : 1;
};
#pragma pack()
struct fontrange_t
{
CUtlSymbol _fontName;
int _min;
int _max;
};
CUtlVector< fontrange_t > m_FontRanges;
CUtlVector< fontalias_t > m_FontAliases;
};
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
class CGameUISchemeManager : public IGameUISchemeMgr
{
public:
CGameUISchemeManager();
~CGameUISchemeManager();
// loads a scheme from a file
// first scheme loaded becomes the default scheme, and all subsequent loaded scheme are derivitives of that
// tag is friendly string representing the name of the loaded scheme
IGameUIScheme * LoadSchemeFromFile( const char *fileName, const char *tag );
// reloads the schemes from the file
void ReloadSchemes();
// reloads scheme fonts
void ReloadFonts( int inScreenTall = -1 );
// returns a handle to the default (first loaded) scheme
IGameUIScheme * GetDefaultScheme();
// returns a handle to the scheme identified by "tag"
IGameUIScheme * GetScheme( const char *tag );
void Shutdown( bool full );
// gets the proportional coordinates for doing screen-size independant panel layouts
// use these for font, image and panel size scaling (they all use the pixel height of the display for scaling)
int GetProportionalScaledValue( int normalizedValue, int screenTall = -1 );
int GetProportionalNormalizedValue( int scaledValue ){ return 1; }
// first scheme loaded becomes the default scheme, and all subsequent loaded scheme are derivitives of that
IGameUIScheme * LoadSchemeFromFileEx( const char *pFilename, const char *tag );
// gets the proportional coordinates for doing screen-size independant panel layouts
// use these for font, image and panel size scaling (they all use the pixel height of the display for scaling)
int GetProportionalScaledValueEx( IGameUIScheme * scheme, int normalizedValue, int screenTall = -1 ){ return 0; }
int GetProportionalNormalizedValueEx( IGameUIScheme * scheme, int scaledValue ){ return 0; }
// gets the proportional coordinates for doing screen-size independant panel layouts
// use these for font, image and panel size scaling (they all use the pixel height of the display for scaling)
int GetProportionalScaledValueEx( CGameUIScheme *pScheme, int normalizedValue, int screenTall = -1 );
int GetProportionalNormalizedValueEx( CGameUIScheme *pScheme, int scaledValue );
void SpewFonts();
void SetLanguage( const char *pLanguage );
const char *GetLanguage();
private:
int GetProportionalScaledValue_( int screenTall, int normalizedValue );
// Search for already-loaded schemes
IGameUIScheme * FindLoadedScheme(const char *pFilename);
CUtlVector< CGameUIScheme * > m_Schemes;
};
extern CGameUISchemeManager *g_pGameUISchemeManager;
#endif // GAMEUISCHEME_H

View File

@@ -0,0 +1,225 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines scripting system.
//
//===========================================================================//
#include "tier0/dbg.h"
#include "gameuiscript.h"
#include "gameuiscriptinterface.h"
#include "gameuidefinition.h"
#include "keyvalues.h"
#include "fmtstr.h"
static ConVar ui_script_error_path( "ui_script_error_path", "", FCVAR_DEVELOPMENTONLY );
//-------------------------------------------------------------
//
//-------------------------------------------------------------
static void ScriptOutputFunc( const char *pszText )
{
Msg( "%s\n", pszText );
}
//-------------------------------------------------------------
//
//-------------------------------------------------------------
static bool ScriptErrorFunc( ScriptErrorLevel_t eLevel, const char *pszText )
{
// Attempt to parse the error for Visual Studio presentation for double-click
if ( char const *pParse1 = StringAfterPrefix( pszText, "[string \"" ) )
{
if ( char const *pQuote = strchr( pParse1, '\"' ) )
{
if ( char const *pParse2 = StringAfterPrefix( pQuote, "\"]:" ) )
{
if ( char const *pEndNum = strchr( pParse2, ':' ) )
{
char const *szType = (eLevel == SCRIPT_LEVEL_WARNING) ? "WARNING" : "ERROR";
Warning( "%s%.*s(%.*s): %s: %s\n",
ui_script_error_path.GetString(),
pQuote - pParse1, pParse1, // file name
pEndNum - pParse2, pParse2, // line number
szType,
pEndNum + 1
);
return true;
}
}
}
}
switch( eLevel )
{
case SCRIPT_LEVEL_WARNING:
Warning( "WARNING: %s\n", pszText );
break;
case SCRIPT_LEVEL_ERROR:
Warning( "ERROR: %s\n", pszText );
break;
}
return true;
}
//-------------------------------------------------------------
// Constructor
//-------------------------------------------------------------
CGameUIScript::CGameUIScript( )
{
m_pScriptVM = GameUIScriptSystemCreate();
m_pScriptVM->SetOutputCallback( ScriptOutputFunc );
m_pScriptVM->SetErrorCallback( ScriptErrorFunc );
m_IsActive = false;
m_pGameUIScriptInterface = NULL;
m_Version = -1;
m_Name = "unknown";
}
//-------------------------------------------------------------
// Destructor
//-------------------------------------------------------------
CGameUIScript::~CGameUIScript( )
{
Shutdown();
}
void CGameUIScript::Shutdown()
{
if ( m_pGameUIScriptInterface )
{
delete m_pGameUIScriptInterface;
m_pGameUIScriptInterface = NULL;
}
}
//-------------------------------------------------------------
// Assign this class a script file and a menu to run it on
//-------------------------------------------------------------
bool CGameUIScript::SetScript( const char *pszFileName, CGameUIDefinition *pDef )
{
ScriptVariant_t Value;
m_ScriptFile = pszFileName;
m_pGameUIScriptInterface = new CGameUIScriptInterface( m_pScriptVM, pDef );
if ( GameUIScriptSystemRun( m_pScriptVM, m_ScriptFile, NULL, true ) == false )
{
return false;
}
if ( !m_pScriptVM->GetValue( pDef->GetName(), &Value ) )
{
return false;
}
m_Scope = Value.m_hScript;
// we don't release Value as that would kill m_Scope.
//GetScriptName();
GetScriptVersion();
#ifndef _DEBUG
//if ( m_Version != build_number() && 0 )
//{
// Msg( "Script %s is out of date. Got %d. Expected %d.\n", pszFileName, m_Version, build_number() );
// return false;
//}
#endif
return true;
}
//-------------------------------------------------------------
//
//-------------------------------------------------------------
bool CGameUIScript::GetScriptName( )
{
HSCRIPT ExecuteFuncProc = m_pScriptVM->LookupFunction( "Name", m_Scope );
if ( ExecuteFuncProc == NULL )
{
return false;
}
ScriptVariant_t Return;
m_pScriptVM->Call( ExecuteFuncProc, m_Scope, true, &Return );
m_Name = Return.m_pszString;
m_pScriptVM->ReleaseFunction( ExecuteFuncProc );
m_pScriptVM->ReleaseValue( Return );
return true;
}
//-------------------------------------------------------------
//
//-------------------------------------------------------------
bool CGameUIScript::GetScriptVersion( )
{
HSCRIPT ExecuteFuncProc = m_pScriptVM->LookupFunction( "Version", m_Scope );
if ( ExecuteFuncProc == NULL )
{
return false;
}
ScriptVariant_t Return;
m_pScriptVM->Call( ExecuteFuncProc, m_Scope, true, &Return );
if ( Return.m_type == FIELD_FLOAT )
{
m_Version = ( int )Return.m_float;
}
else
{
m_Version = Return.m_int;
}
m_pScriptVM->ReleaseFunction( ExecuteFuncProc );
m_pScriptVM->ReleaseValue( Return );
return true;
}
//-------------------------------------------------------------
// Call a scripting function that takes an array of strings as an arg.
//-------------------------------------------------------------
bool CGameUIScript::Execute( KeyValues *pData, KeyValues **ppResult )
{
const char *eventName = pData->GetName();
HSCRIPT ExecuteFuncProc = m_pScriptVM->LookupFunction( eventName, m_Scope );
if ( ExecuteFuncProc == NULL )
{
return false;
}
// Transform the key values into script scope to execute
HSCRIPT hParams = CGameUIScriptInterface::ScriptTableFromKeyValues( m_pScriptVM, pData );
ScriptVariant_t varParams = hParams, varResult;
ScriptStatus_t ret = m_pScriptVM->ExecuteFunction( ExecuteFuncProc, &varParams, 1, &varResult, m_Scope, true );
if ( hParams )
{
m_pScriptVM->ReleaseValue( varParams );
}
if ( ret == SCRIPT_DONE && varResult.m_type == FIELD_HSCRIPT && ppResult )
{
Assert( !*ppResult ); // storing return value, might overwrite caller's keyvalues
*ppResult = CGameUIScriptInterface::ScriptVmKeyValueFromVariant( m_pScriptVM, varResult );
}
m_pScriptVM->ReleaseValue( varResult );
m_pScriptVM->ReleaseFunction( ExecuteFuncProc );
return true;
}

View File

@@ -0,0 +1,57 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines gameui scripting system.
//
//===========================================================================//
#ifndef GAMEUISCRIPT_H
#define GAMEUISCRIPT_H
#ifdef _WIN32
#pragma once
#endif
#include "gameuiscriptsystem.h"
class CGameUIScriptInterface;
class CGameUIDefinition;
class KeyValues;
class CGameUIScript
{
public:
CGameUIScript( );
~CGameUIScript( );
void Shutdown();
IScriptVM *GetVM( ) { return m_pScriptVM; }
CUtlString &GetName( ) { return m_Name; }
int GetVersion( ) { return m_Version; }
CUtlString &GetScriptFile( ) { return m_ScriptFile; }
bool IsActive( ) { return m_IsActive; }
bool SetScript( const char *pszFileName, CGameUIDefinition *pDef );
void SetActive( bool IsActive ) { m_IsActive = IsActive; }
bool Execute( KeyValues *pData, KeyValues **ppResult );
CGameUIScriptInterface * GetScriptInterface() const { return m_pGameUIScriptInterface; }
private:
bool GetScriptName( );
bool GetScriptType( );
bool GetScriptVersion( );
CGameUIScriptInterface *m_pGameUIScriptInterface;
CUtlString m_Name;
int m_Version;
bool m_IsActive;
CUtlString m_ScriptFile;
IScriptVM *m_pScriptVM;
HSCRIPT m_Scope;
};
#endif // GAMEUISCRIPT_H

View File

@@ -0,0 +1,565 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines scripting system.
//
//===========================================================================//
#include "gameuiscriptInterface.h"
#include "gameuisystemmgr.h"
#include "gameuidefinition.h"
#include "gamelayer.h"
#include "gamegraphic.h"
#include "fmtstr.h"
#include "gameuiscript.h"
#include "gameuisystem.h"
#include "gametext.h"
#include "dynamicrect.h"
#include "tier2/tier2.h"
#include "matchmaking/imatchframework.h"
BEGIN_SCRIPTDESC_ROOT_NAMED( CGameUIScriptInterface, "CGameUIScriptInterface", SCRIPT_SINGLETON "" )
// HSCRIPT table-kv functions
DEFINE_SCRIPTFUNC( LoadMenu, "LoadMenu( name, {params} ) : Load a menu." )
DEFINE_SCRIPTFUNC( CreateGraphic, "CreateGraphic( classname, {params} ) : Create a graphic." )
DEFINE_SCRIPTFUNC( CallScript, "CallScript( scripthandle, function, {params} ) : Execute other script function (scripthandle=0 will run local script)." )
DEFINE_SCRIPTFUNC( CallGraphic, "CallGraphic( graphichandle, commandname, {params} ) : Execute a graphic function." )
DEFINE_SCRIPTFUNC( Nugget, "Nugget( action, {params} ) : Interface with nuggets." )
END_SCRIPTDESC()
static ConVar ui_script_spew_level( "ui_script_spew_level", 0, FCVAR_DEVELOPMENTONLY );
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameUIScriptInterface::CGameUIScriptInterface( IScriptVM *pScriptVM, CGameUIDefinition *pDef ) :
m_Nuggets( UtlStringLessFunc ),
m_GraphicScriptInstances( UtlStringLessFunc ),
m_pScriptVM( pScriptVM ),
m_pMenu( pDef )
{
m_Scope = m_pScriptVM->RegisterInstance( this, "c" );
}
CGameUIScriptInterface::~CGameUIScriptInterface()
{
Shutdown();
}
void CGameUIScriptInterface::Shutdown()
{
// Unload all nuggets
for ( unsigned short k = m_Nuggets.FirstInorder(); k != m_Nuggets.InvalidIndex(); k = m_Nuggets.NextInorder( k ) )
{
IGameUIScreenController *pNugget = m_Nuggets.Element( k );
pNugget->OnScreenDisconnected( m_pMenu->GetGameUISystem() );
}
m_Nuggets.Purge();
}
//-----------------------------------------------------------------------------
// Show the ID menu next frame, and hide this menu next frame.
//-----------------------------------------------------------------------------
HSCRIPT CGameUIScriptInterface::LoadMenu( const char *szMenuName, HSCRIPT hParams )
{
if ( !szMenuName || !*szMenuName )
return NULL;
// Build the key values for the command and broadcast (deleted inside broadcast system)
KeyValues *kvCommand = ScriptTableToKeyValues( m_pScriptVM, szMenuName, hParams );
KeyValues::AutoDelete autodelete_kvCommand( kvCommand );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "CGameUIScriptInterface::LoadMenu\n" );
KeyValuesDumpAsDevMsg( kvCommand );
}
IGameUISystem *pUI = g_pGameUISystemMgrImpl->LoadGameUIScreen( kvCommand );
if ( !pUI )
return NULL;
KeyValues *kvResult = new KeyValues( "" );
KeyValues::AutoDelete autodelete_kvResult( kvResult );
kvResult->SetInt( "scripthandle", pUI->GetScriptHandle() );
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
HSCRIPT CGameUIScriptInterface::CreateGraphic( const char *szGraphicClassName, HSCRIPT hParams )
{
if ( !szGraphicClassName || !*szGraphicClassName )
return NULL;
if ( !m_pMenu || !m_pMenu->GetGameUISystem() )
{
DevWarning( "Scripts not connected to game UI system and cannot create graphics!\n" );
return NULL;
}
// Build the key values for the command
KeyValues *kvCommand = ScriptTableToKeyValues( m_pScriptVM, szGraphicClassName, hParams );
KeyValues::AutoDelete autodelete_kvCommand( kvCommand );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "CGameUIScriptInterface::CreateGraphic\n" );
KeyValuesDumpAsDevMsg( kvCommand );
}
const char* szGraphicName = kvCommand->GetString( "name", NULL );
// Check if this instance is already created
if ( szGraphicName == NULL )
{
DevWarning( "A must have a name!\n", szGraphicName );
return NULL;
}
// Check if an instance of this graphic already exists
CGameGraphic *pGraphic = m_pMenu->GraphicExists( szGraphicName );
if ( pGraphic )
{
DevWarning( "A graphic with this name %s is already loaded!\n", szGraphicName );
return NULL;
}
IGameUIGraphicClassFactory *pFactory = g_pGameUISystemMgrImpl->GetGraphicClassFactory( szGraphicClassName );
if ( !pFactory )
{
DevWarning( "No graphic class factory for %s!\n", szGraphicClassName );
return NULL;
}
CGameGraphic *pNewGraphic = pFactory->CreateNewGraphicClass( kvCommand, m_pMenu );
if ( !pNewGraphic )
{
DevWarning( "No graphic in factory %s!\n", szGraphicClassName );
return NULL;
}
KeyValues *kvResult = new KeyValues( "" );
KeyValues::AutoDelete autodelete_kvResult( kvResult );
kvResult->SetInt( "scripthandle", pNewGraphic->GetScriptHandle() );
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
HSCRIPT CGameUIScriptInterface::CallScript( int32 iScriptHandle, const char *szCommandName, HSCRIPT hParams )
{
if ( !szCommandName || !*szCommandName )
return NULL;
// Try to resolve other script handle specified
CGameUISystem *pOtherScript = iScriptHandle ? CGameUISystem::FromScriptHandle( iScriptHandle ) : ( CGameUISystem * ) m_pMenu->GetGameUISystem();
if ( !pOtherScript )
{
Warning( "CGameUIScriptInterface::CallScript with invalid script handle %d!\n", iScriptHandle );
return NULL;
}
// Build the key values for the command and call other script
KeyValues *kvCommand = ScriptTableToKeyValues( m_pScriptVM, szCommandName, hParams );
KeyValues::AutoDelete autodelete_kvCommand( kvCommand );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "CGameUIScriptInterface::CallScript( %d : %s )\n", iScriptHandle, pOtherScript->GetName() );
KeyValuesDumpAsDevMsg( kvCommand );
}
// Pass the command to another script
KeyValues *kvResult = NULL;
pOtherScript->ExecuteScript( kvCommand, &kvResult );
if ( ui_script_spew_level.GetInt() > 0 )
{
KeyValuesDumpAsDevMsg( kvResult );
}
KeyValues::AutoDelete autodelete_kvResult( kvResult );
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
HSCRIPT CGameUIScriptInterface::CallGraphic( int32 iGraphicHandle, const char *szCommandName, HSCRIPT hParams )
{
if ( !szCommandName || !*szCommandName || !iGraphicHandle )
return NULL;
CGameGraphic *pGraphic = CGameGraphic::FromScriptHandle( iGraphicHandle );
if ( !pGraphic )
{
Warning( "CGameUIScriptInterface::CallGraphic with invalid graphic handle %d!\n", iGraphicHandle );
return NULL;
}
// Build the key values for the command and call other script
KeyValues *kvCommand = ScriptTableToKeyValues( m_pScriptVM, szCommandName, hParams );
KeyValues::AutoDelete autodelete_kvCommand( kvCommand );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "CGameUIScriptInterface::CallGraphic( %d : %s )\n", iGraphicHandle, pGraphic->GetName() );
KeyValuesDumpAsDevMsg( kvCommand );
}
// Pass the command to graphic
KeyValues *kvResult = pGraphic->HandleScriptCommand( kvCommand);
if ( ui_script_spew_level.GetInt() > 0 )
{
KeyValuesDumpAsDevMsg( kvResult );
}
KeyValues::AutoDelete autodelete_kvResult( kvResult );
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
HSCRIPT CGameUIScriptInterface::Nugget( const char *szCommandName, HSCRIPT hParams )
{
if ( !szCommandName || !*szCommandName )
return NULL;
if ( !m_pMenu || !m_pMenu->GetGameUISystem() )
{
DevWarning( "Scripts not connected to game UI system and cannot use nuggets!\n" );
return NULL;
}
// Build the key values for the command
KeyValues *kvCommand = ScriptTableToKeyValues( m_pScriptVM, szCommandName, hParams );
KeyValues::AutoDelete autodelete_kvCommand( kvCommand );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "CGameUIScriptInterface::Nugget\n" );
KeyValuesDumpAsDevMsg( kvCommand );
}
// Parse the command
if ( char const *szUseName = StringAfterPrefix( kvCommand->GetName(), "load:" ) )
{
char const *szNuggetName = szUseName;
szUseName = kvCommand->GetString( "usename", szNuggetName );
// Check if the nugget is already loaded
if ( m_Nuggets.Find( szUseName ) != m_Nuggets.InvalidIndex() )
{
DevWarning( "Nugget factory %s is already loaded!\n", szUseName );
return NULL;
}
IGameUIScreenControllerFactory *pFactory = g_pGameUISystemMgrImpl->GetScreenControllerFactory( szNuggetName );
if ( !pFactory )
{
DevWarning( "No nugget factory for %s!\n", szNuggetName );
return NULL;
}
kvCommand->SetName( szNuggetName );
IGameUIScreenController *pNugget = pFactory->GetController( kvCommand );
if ( !pNugget )
{
DevWarning( "No nugget in factory %s!\n", szNuggetName );
return NULL;
}
// Connect the nugget with our screen
m_Nuggets.Insert( szUseName, pNugget );
pNugget->OnScreenConnected( m_pMenu->GetGameUISystem() );
KeyValues *kvResult = new KeyValues( "" );
KeyValues::AutoDelete autodelete_kvResult( kvResult );
kvResult->SetInt( "scripthandle", m_pMenu->GetGameUISystem()->GetScriptHandle() );
kvResult->SetString( "usename", szUseName );
kvResult->SetInt( "ptr", reinterpret_cast< int >( pNugget ) );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "Loaded nugget %s\n", szNuggetName );
KeyValuesDumpAsDevMsg( kvResult );
}
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
if ( char const *szUseName = StringAfterPrefix( kvCommand->GetName(), "ref:" ) )
{
int iRefScriptHandle = kvCommand->GetInt( "scripthandle" );
char const *szRefUseName = kvCommand->GetString( "usename", szUseName );
// Check if the nugget is already loaded
if ( m_Nuggets.Find( szUseName ) != m_Nuggets.InvalidIndex() )
{
DevWarning( "Nugget factory %s is already loaded!\n", szUseName );
return NULL;
}
CGameUISystem *pMenu = iRefScriptHandle ? CGameUISystem::FromScriptHandle( iRefScriptHandle ) : ( CGameUISystem * ) m_pMenu->GetGameUISystem();
if ( !pMenu )
{
DevWarning( "Nugget reference request %s with invalid script handle %d!\n", szUseName, iRefScriptHandle );
return NULL;
}
CGameUIScriptInterface *pRefInterface = NULL;
if ( CGameUIScript *pScript = pMenu->Definition().GetScript() )
pRefInterface = pScript->GetScriptInterface();
if ( !pRefInterface )
{
DevWarning( "Nugget reference request %s with script handle %d(%s) which has no scripts!\n", szUseName, iRefScriptHandle, pMenu->GetName() );
return NULL;
}
unsigned short usIdx = pRefInterface->m_Nuggets.Find( szRefUseName );
if ( usIdx == pRefInterface->m_Nuggets.InvalidIndex() )
{
DevWarning( "Nugget reference request %s with script handle %d(%s) which has no nugget %s!\n", szUseName, iRefScriptHandle, pMenu->GetName(), szRefUseName );
return NULL;
}
IGameUIScreenController *pNugget = pRefInterface->m_Nuggets.Element( usIdx );
if ( reinterpret_cast< int >( pNugget ) != kvCommand->GetInt( "ptr" ) )
{
DevWarning( "Nugget reference request %s with script handle %d(%s) for nugget %s yielding %08X instead of expected %08X!\n",
szUseName, iRefScriptHandle, pMenu->GetName(), szRefUseName, reinterpret_cast< int >( pNugget ), kvCommand->GetInt( "ptr" ) );
}
// Connect the nugget with our screen
m_Nuggets.Insert( szUseName, pNugget );
pNugget->OnScreenConnected( m_pMenu->GetGameUISystem() );
KeyValues *kvResult = new KeyValues( "" );
KeyValues::AutoDelete autodelete_kvResult( kvResult );
kvResult->SetInt( "scripthandle", m_pMenu->GetGameUISystem()->GetScriptHandle() );
kvResult->SetString( "usename", szUseName );
kvResult->SetInt( "ptr", reinterpret_cast< int >( pNugget ) );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "Referenced nugget %s from %d(%s):%s\n", szUseName, iRefScriptHandle, pMenu->GetName(), szRefUseName );
KeyValuesDumpAsDevMsg( kvResult );
}
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
if ( char const *szUseName = StringAfterPrefix( kvCommand->GetName(), "free:" ) )
{
// Check if the nugget is already loaded
unsigned short usIdx = m_Nuggets.Find( szUseName );
if ( usIdx == m_Nuggets.InvalidIndex() )
{
DevWarning( "Nugget factory %s is not loaded!\n", szUseName );
return NULL;
}
// Unload the nugget
IGameUIScreenController *pNugget = m_Nuggets.Element( usIdx );
m_Nuggets.RemoveAt( usIdx );
pNugget->OnScreenDisconnected( m_pMenu->GetGameUISystem() );
if ( ui_script_spew_level.GetInt() > 0 )
{
DevMsg( "Unloaded nugget %s\n", szUseName );
}
return NULL;
}
if ( char const *szUse = StringAfterPrefix( kvCommand->GetName(), "use:" ) )
{
char const *szUseName = szUse;
// Split off nugget name by :
if ( char const *pch = strchr( szUseName, ':' ) )
{
char *buf = ( char * ) stackalloc( pch - szUseName + 1 );
Q_strncpy( buf, szUseName, pch - szUseName + 1 );
szUseName = buf;
kvCommand->SetName( pch + 1 );
}
else
{
kvCommand->SetName( "" );
}
// Check if the nugget is already loaded
unsigned short usIdx = m_Nuggets.Find( szUseName );
if ( usIdx == m_Nuggets.InvalidIndex() )
{
DevWarning( "Nugget factory %s is not loaded!\n", szUseName );
return NULL;
}
// Nugget operation
IGameUIScreenController *pNugget = m_Nuggets.Element( usIdx );
KeyValues *kvResult = pNugget->OnScreenEvent( m_pMenu->GetGameUISystem(), kvCommand );
KeyValues::AutoDelete autodelete_kvResult( kvResult );
if ( ui_script_spew_level.GetInt() > 0 )
{
KeyValuesDumpAsDevMsg( kvResult );
}
// Push results for the script
return ScriptTableFromKeyValues( m_pScriptVM, kvResult );
}
return NULL;
}
bool CGameUIScriptInterface::ScriptVmKeyValueToVariant( IScriptVM *pVM, KeyValues *val, ScriptVariant_t &varValue, char chScratchBuffer[KV_VARIANT_SCRATCH_BUF_SIZE] )
{
switch ( val->GetDataType() )
{
case KeyValues::TYPE_STRING:
varValue = val->GetString();
return true;
case KeyValues::TYPE_INT:
varValue = val->GetInt();
return true;
case KeyValues::TYPE_FLOAT:
varValue = val->GetFloat();
return true;
case KeyValues::TYPE_UINT64:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%llu", val->GetUint64() );
varValue = chScratchBuffer;
return true;
case KeyValues::TYPE_NONE:
varValue = ScriptTableFromKeyValues( pVM, val );
return true;
default:
Warning( "ScriptVmKeyValueToVariant failed to package parameter %s (type %d)\n", val->GetName(), val->GetDataType() );
return false;
}
}
bool CGameUIScriptInterface::ScriptVmStringFromVariant( ScriptVariant_t &varValue, char chScratchBuffer[KV_VARIANT_SCRATCH_BUF_SIZE] )
{
switch ( varValue.m_type )
{
case FIELD_INTEGER:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%d", varValue.m_int );
return true;
case FIELD_FLOAT:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%f", varValue.m_float );
return true;
case FIELD_BOOLEAN:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%d", varValue.m_bool );
return true;
case FIELD_CHARACTER:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%c", varValue.m_char );
return true;
case FIELD_CSTRING:
Q_snprintf( chScratchBuffer, KV_VARIANT_SCRATCH_BUF_SIZE, "%s", varValue.m_pszString ? varValue.m_pszString : "" );
return true;
default:
Warning( "ScriptVmStringFromVariant failed to unpack parameter variant type %d\n", varValue.m_type );
return false;
}
}
KeyValues * CGameUIScriptInterface::ScriptVmKeyValueFromVariant( IScriptVM *pVM, ScriptVariant_t &varValue )
{
KeyValues *val = NULL;
switch ( varValue.m_type )
{
case FIELD_INTEGER:
val = new KeyValues( "" );
val->SetInt( NULL, varValue.m_int );
return val;
case FIELD_FLOAT:
val = new KeyValues( "" );
val->SetFloat( NULL, varValue.m_float );
return val;
case FIELD_BOOLEAN:
val = new KeyValues( "" );
val->SetInt( NULL, varValue.m_bool ? 1 : 0 );
return val;
case FIELD_CHARACTER:
val = new KeyValues( "" );
val->SetString( NULL, CFmtStr( "%c", varValue.m_char ) );
return val;
case FIELD_CSTRING:
val = new KeyValues( "" );
val->SetString( NULL, varValue.m_pszString ? varValue.m_pszString : "" );
return val;
case FIELD_HSCRIPT:
return ScriptTableToKeyValues( pVM, "", varValue.m_hScript );
default:
Warning( "ScriptVmKeyValueFromVariant failed to unpack parameter variant type %d\n", varValue.m_type );
return NULL;
}
}
KeyValues * CGameUIScriptInterface::ScriptTableToKeyValues( IScriptVM *pVM, char const *szName, HSCRIPT hTable )
{
if ( !szName )
szName = "";
KeyValues *kv = new KeyValues( szName );
if ( hTable && pVM )
{
int numKeys = pVM->GetNumTableEntries( hTable );
for ( int k = 0; k < numKeys; ++ k )
{
ScriptVariant_t varKey, varValue;
pVM->GetKeyValue( hTable, k, &varKey, &varValue );
char chScratchBuffer[ KV_VARIANT_SCRATCH_BUF_SIZE ];
if ( !ScriptVmStringFromVariant( varKey, chScratchBuffer ) )
{
Assert( 0 );
continue;
}
KeyValues *sub = ScriptVmKeyValueFromVariant( pVM, varValue );
if ( !sub )
{
Assert( 0 );
// sub->deleteThis();
// continue;
// still proceed - it will be a key with no data
sub = new KeyValues( "" );
}
sub->SetName( chScratchBuffer );
kv->AddSubKey( sub );
}
}
return kv;
}
HSCRIPT CGameUIScriptInterface::ScriptTableFromKeyValues( IScriptVM *pVM, KeyValues *kv )
{
if ( !kv || !pVM )
return NULL;
ScriptVariant_t varTable;
pVM->CreateTable( varTable );
for ( KeyValues *val = kv->GetFirstSubKey(); val; val = val->GetNextKey() )
{
ScriptVariant_t varValue;
char chScratchBuffer[ KV_VARIANT_SCRATCH_BUF_SIZE ];
if ( !ScriptVmKeyValueToVariant( pVM, val, varValue, chScratchBuffer ) )
continue;
#ifdef GAMEUI_SCRIPT_LOWERCASE_ALL_TABLE_KEYS
char chNameBuffer[ KV_VARIANT_SCRATCH_BUF_SIZE ];
Q_strncpy( chNameBuffer, val->GetName(), KV_VARIANT_SCRATCH_BUF_SIZE );
Q_strlower( chNameBuffer );
#else
char const *chNameBuffer = val->GetName();
#endif
pVM->SetValue( varTable.m_hScript, chNameBuffer, varValue );
}
return varTable.m_hScript;
}

View File

@@ -0,0 +1,71 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines scripting system.
//
//===========================================================================//
#ifndef GAMEUISCRIPTINTERFACE_H
#define GAMEUISCRIPTINTERFACE_H
#ifdef _WIN32
#pragma once
#endif
#include "game_controls/igameuisystemmgr.h"
#include "gameuiscriptsystem.h"
#include "tier1/utlntree.h"
#include "utlmap.h"
class CGameUIDefinition;
class CGameGraphic;
//-----------------------------------------------------------------------------
// These are functions that can be called from lua that do things in the gameui.
//-----------------------------------------------------------------------------
class CGameUIScriptInterface
{
public:
explicit CGameUIScriptInterface( IScriptVM *pScriptVM, CGameUIDefinition *pDef );
~CGameUIScriptInterface();
int GetGraphicID( CGameGraphic *pGraphic );
public:
void Shutdown();
// Load a new menu to show now.
HSCRIPT LoadMenu( const char *szMenuName, HSCRIPT hParams );
// Create a graphic by classname
HSCRIPT CreateGraphic( const char *szGraphicClassName, HSCRIPT hParams );
// Execute a script command from menus
HSCRIPT CallScript( int32 iScriptHandle, const char *szCommandName, HSCRIPT hParams );
// Call a function inside a graphic
HSCRIPT CallGraphic( int32 iGraphicHandle, const char *szCommandName, HSCRIPT hParams );
// Interface with nuggets
HSCRIPT Nugget( const char *szCommandName, HSCRIPT hParams );
public:
enum { KV_VARIANT_SCRATCH_BUF_SIZE = 128 };
static bool ScriptVmKeyValueToVariant( IScriptVM *pVM, KeyValues *val, ScriptVariant_t &varValue, char chScratchBuffer[KV_VARIANT_SCRATCH_BUF_SIZE] );
static bool ScriptVmStringFromVariant( ScriptVariant_t &varValue, char chScratchBuffer[KV_VARIANT_SCRATCH_BUF_SIZE] );
static KeyValues * ScriptVmKeyValueFromVariant( IScriptVM *pVM, ScriptVariant_t &varValue );
static KeyValues * ScriptTableToKeyValues( IScriptVM *pVM, char const *szName, HSCRIPT hTable );
static HSCRIPT ScriptTableFromKeyValues( IScriptVM *pVM, KeyValues *kv );
private:
HSCRIPT m_Scope;
IScriptVM *m_pScriptVM;
CGameUIDefinition *m_pMenu;
CUtlMap< CUtlString, IGameUIScreenController * > m_Nuggets;
CUtlMap< CUtlString, CGameGraphic * > m_GraphicScriptInstances; // graphics created from scripting.
};
#endif // GAMEUISCRIPTINTERFACE_H

View File

@@ -0,0 +1,134 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines scripting system.
//
//===========================================================================//
#include "gameuiscriptsystem.h"
#include "tier1/utlbuffer.h"
#include "tier1/fmtstr.h"
#include "filesystem.h"
#include "gameuisystemmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
IScriptVM *GameUIScriptSystemCreate( )
{
IScriptVM *pScriptVM = NULL;
ScriptLanguage_t scriptLanguage = SL_LUA;
if( scriptLanguage != SL_NONE )
{
pScriptVM = g_pScriptManager->CreateVM( scriptLanguage );
if( pScriptVM )
{
DevMsg("VSCRIPT: Started VScript virtual machine using script language '%s'\n", pScriptVM->GetLanguageName() );
char SZFullPath[ MAX_PATH ];
g_pFullFileSystem->RelativePathToFullPath( "scripts/vguiedit/modules", "GAME", SZFullPath, sizeof( SZFullPath ) );
pScriptVM->AddSearchPath( SZFullPath );
}
}
return pScriptVM;
}
HSCRIPT GameUIScriptSystemCompile( IScriptVM *pScriptVM, const char *pszScriptName, bool bWarnMissing )
{
if ( !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[ pScriptVM->GetLanguage() ];
const char *pszIncomingExtension = V_strrchr( pszScriptName , '.' );
if ( pszIncomingExtension && V_stricmp( pszIncomingExtension, pszVMExtension ) != 0 )
{
Msg( "Script file type does not match VM type\n" );
return NULL;
}
CFmtStr scriptPath;
if ( pszIncomingExtension )
{
scriptPath.sprintf( "scripts/%s", pszScriptName );
}
else
{
scriptPath.sprintf( "scripts/%s%s", pszScriptName, pszVMExtension );
}
const char *pBase;
CUtlBuffer bufferScript;
if ( pScriptVM->GetLanguage() == SL_PYTHON )
{
// python auto-loads raw or precompiled modules - don't load data here
pBase = NULL;
}
else
{
bool bResult = g_pFullFileSystem->ReadFile( scriptPath, "GAME", bufferScript );
if( !bResult )
{
Warning( "Script not found (%s) \n", scriptPath.operator const char *() );
}
pBase = (const char *) bufferScript.Base();
if ( !pBase || !*pBase )
{
return NULL;
}
}
const char *pszFilename = V_strrchr( scriptPath, '/' );
pszFilename++;
HSCRIPT hScript = pScriptVM->CompileScript( pBase, pszFilename );
if ( hScript == INVALID_HSCRIPT )
{
DevMsg( "FAILED to compile and execute script file named %s\n", scriptPath.operator const char *() );
}
return hScript;
}
bool GameUIScriptSystemRun( IScriptVM *pScriptVM, const char *pszScriptName, HSCRIPT hScope, bool bWarnMissing )
{
HSCRIPT hScript = GameUIScriptSystemCompile( pScriptVM, pszScriptName, bWarnMissing );
bool bSuccess = false;
if ( hScript != INVALID_HSCRIPT )
{
// if ( gpGlobals->maxClients == 1 )
//{
//CBaseEntity *pPlayer = UTIL_GetLocalPlayer();
//if ( pPlayer )
//{
//g_pScriptVM->SetValue( "player", pPlayer->GetScriptInstance() );
//}
//}
bSuccess = ( pScriptVM->Run( hScript, hScope ) != SCRIPT_ERROR );
if ( !bSuccess )
{
DevMsg( "Error running script named %s\n", pszScriptName );
}
pScriptVM->ReleaseScript( hScript );
}
return bSuccess;
}
#include <tier0/memdbgoff.h>

View File

@@ -0,0 +1,21 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: Defines scripting system.
//
//===========================================================================//
#ifndef GAMEUISCRIPTSYSTEM_H
#define GAMEUISCRIPTSYSTEM_H
#ifdef _WIN32
#pragma once
#endif
#include "vscript/ivscript.h"
IScriptVM *GameUIScriptSystemCreate();
HSCRIPT GameUIScriptSystemCompile( IScriptVM *pScriptVM, const char *pszScriptName, bool bWarnMissing );
bool GameUIScriptSystemRun( IScriptVM *pScriptVM, const char *pszScriptName, HSCRIPT hScope, bool bWarnMissing );
#endif // GAMEUISCRIPTSYSTEM_H

View File

@@ -0,0 +1,80 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#ifndef GAMEUISYSTEM_H
#define GAMEUISYSTEM_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/timeutils.h"
#include "materialsystem/imaterialsystem.h"
#include "gameuidefinition.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class IGameUIScreenController;
class CUtlBuffer;
class IRenderContext;
class IRenderDevice;
class KeyValues;
struct RenderViewport_t;
//-----------------------------------------------------------------------------
// Class to render a zillion ui elements
//-----------------------------------------------------------------------------
class CGameUISystem : public IGameUISystem
{
public:
CGameUISystem();
virtual ~CGameUISystem();
virtual char const * GetName();
virtual bool Init( KeyValues *kvLoadSettings );
virtual void Release();
virtual void Render( const Rect_t &viewport );
virtual void Render( IRenderContext *pRenderContext, const Rect_t &viewport );
virtual void LoadEmptyGameUI( const char *pName );
virtual bool LoadGameUIDefinition( CUtlBuffer &buf, const char *pFileName );
CGameUIDefinition &Definition() { return m_GameUIDef; }
virtual bool ExecuteScript( KeyValues *kvEvent, KeyValues **ppResult = NULL );
virtual void SetStageSize( int nWide, int nTall );
virtual void GetStageSize( Vector2D &stageSize );
virtual int32 GetScriptHandle() { return m_iScriptHandle; }
static CGameUISystem * FromScriptHandle( int32 iScriptHandle );
private:
void GenerateUIMesh( IMatRenderContext *pRenderContext, IMesh* pMesh, CUtlVector< CRenderGeometry > &renderGeometry, CSheet *pSheet );
void RenderStaticLayer( LayerRenderLists_t &renderList, int geometryIndex );
void RenderStaticLayer( IRenderContext *pRenderContext, LayerRenderLists_t &renderList, int geometryIndex );
void RenderDynamicLayer( LayerRenderLists_t &renderList, int geometryIndex );
void RenderTextLayer( CUtlVector< CRenderGeometry > &renderGeometry );
void RenderTextLayer( IRenderContext *pRenderContext, CUtlVector< CRenderGeometry > &renderGeometry );
CGameUIDefinition m_GameUIDef;
int32 m_iScriptHandle;
bool m_bDrawReport;
};
#endif // GAMEUISYSTEM_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,216 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef GAMEUISYSTEMMANAGER_H
#define GAMEUISYSTEMMANAGER_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/utlvector.h"
#include "tier1/timeutils.h"
#include "rendersystem/vertexdata.h"
#include "rendersystem/indexdata.h"
#include "inputsystem/buttoncode.h"
#include "gameuischeme.h"
#include "igameuisystemmgr.h"
#include "appframework/iappsystem.h"
#include "tier3/tier3dm.h"
#include "tier1/utlstring.h"
#include "tier1/utlmap.h"
#include "gameuidynamictextures.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class IGameUIScreenController;
class IRenderContext;
class CGameUISystem;
class CGameGraphic;
class CHitArea;
class CGameText;
class CGameUIDefinition;
FORWARD_DECLARE_HANDLE( InputContextHandle_t );
//-----------------------------------------------------------------------------
// Global interfaces...
//-----------------------------------------------------------------------------
class IScriptManager;
extern IScriptManager *g_pScriptManager;
abstract_class IGameUIGraphicClassFactory
{
public:
// Returns an instance of a graphic interface (keyvalues owned by caller)
virtual CGameGraphic * CreateNewGraphicClass( KeyValues *kvRequest, CGameUIDefinition *pMenu ) = 0;
};
//-----------------------------------------------------------------------------
//
// Game UI system manager
//
//-----------------------------------------------------------------------------
class CGameUISystemMgr : public CTier3AppSystem< IGameUISystemMgr >
{
typedef CTier3AppSystem< IGameUISystemMgr > BaseClass;
public:
// Constructor, destructor
CGameUISystemMgr();
virtual ~CGameUISystemMgr();
virtual bool Connect( CreateInterfaceFn factory );
virtual void Disconnect();
virtual const AppSystemInfo_t* GetDependencies();
virtual void *QueryInterface( const char *pInterfaceName );
virtual InitReturnVal_t Init( );
virtual void Shutdown();
virtual void SetGameUIVisible( bool bVisible );
virtual bool GetGameUIVisible(){ return IsMenuVisible(); }
// Load the game UI menu screen
// key values are owned and released by caller
virtual IGameUISystem * LoadGameUIScreen( KeyValues *kvScreenLoadSettings );
virtual void ReleaseAllGameUIScreens();
virtual void RunFrame();
virtual void RegisterScreenControllerFactory( char const *szControllerName, IGameUIScreenControllerFactory *pFactory );
virtual IGameUIScreenControllerFactory * GetScreenControllerFactory( char const *szControllerName );
virtual IGameUISystemSurface * GetSurface();
virtual IGameUISchemeMgr * GetSchemeMgr();
virtual IGameUIMiscUtils * GetMiscUtils();
virtual void Render( const Rect_t &viewport, DmeTime_t flCurrentTime );
virtual void Render( IRenderContext *pRenderContext, PlatWindow_t hWnd, const Rect_t &viewport, DmeTime_t flCurrentTime );
virtual void UseGameInputSystemEventQueue( bool bEnable );
virtual void RegisterInputEvent( const InputEvent_t &iEvent );
virtual void SendEventToAllScreens( KeyValues *kvGlobalEvent );
virtual void PostEventToAllScreens( KeyValues *kvGlobalEvent );
virtual void SetSoundPlayback( IGameUISoundPlayback *pPlayback );
virtual bool IsMenuVisible() const;
virtual void SetInputContext( InputContextHandle_t hInputContext );
CHitArea *GetMouseFocus();
CHitArea *GetMouseFocus( int x, int y );
CHitArea *GetKeyFocus();
CHitArea *GetRequestedKeyFocus();
void RequestKeyFocus( CHitArea *pGraphic, KeyValues *args = NULL );
void GetScreenHeightForFontLoading( int &nTall );
void SetScheme( IGameUIScheme * scheme );
IGameUIScheme * GetCurrentScheme();
DmeTime_t GetTime();
// Render system stuff
RenderInputLayout_t m_hInputLayout;
RenderShaderHandle_t m_hVertexShader;
RenderShaderHandle_t m_hPixelShader;
ConstantBufferHandle_t m_hConstBuffer;
void OnMouseFocusGained( CHitArea *mouseFocus );
void OnMouseFocusLost( CHitArea *mouseFocus );
bool OnKeyCodeTyped( const ButtonCode_t &code );
bool OnKeyTyped( const wchar_t &unichar );
bool OnGameGraphicScriptEvent( CGameGraphic *pGraphic, KeyValues *kvEvent );
// Force focus to update on the next frame
void ForceFocusUpdate(){ m_bForceFocusUpdate = true; }
void PlayMenuSound( const char *pSoundFileName );
void StopMenuSound( const char *pSoundFileName );
void SetWindowSize( int nWidth, int nHeight );
void GetWindowSize( int &nWidth, int &nHeight );
void SetViewportSize( int nWidth, int nHeight );
void GetViewportSize( int &nWidth, int &nHeight );
// Returns the input context to use to control the cursor
InputContextHandle_t GetInputContext( ) const;
void OnScreenReleased( CGameUISystem *pScreen );
// Dynamic texture management.
void InitImageAlias( const char *pAlias );
void LoadImageAliasTexture( const char *pAlias, const char *pBaseTextureName );
void ReleaseImageAlias( const char *pAlias);
IMaterial *GetImageAliasMaterial( const char *pAlias );
ImageAliasData_t *GetImageAliasData( const char *pAlias );
void TexCoordsToSheetTexCoords( const char *pAlias, Vector2D texCoords, Vector2D &sheetTexCoords );
void DrawDynamicTexture( const char *pAlias, int x, int y );
void ShowCursorCoords();
void ShowGraphicName();
virtual void RegisterGraphicClassFactory( char const *szGraphicClassName, IGameUIGraphicClassFactory *pFactory );
virtual IGameUIGraphicClassFactory *GetGraphicClassFactory( char const *szGraphicClassName );
virtual void InitRenderTargets();
virtual IMaterialProxy *CreateProxy( const char *proxyName );
private:
void GetScreenSize( int &nWide, int &nTall );
Vector2D CursorToStage( Vector2D cursorPos );
// We may wind up with multiple viewports and multiple lists?
Rect_t m_Viewport;
int m_nWindowWidth, m_nWindowHeight;
CUtlVector< CGameUISystem * > m_ActiveMenuList;
CUtlVector< CGameUISystem * > m_ReleasedMenuList;
DmeTime_t m_flCurrentTime;
IGameUIScheme *m_Scheme;
CHitArea *m_RequestedKeyFocus;
bool m_bForceFocusUpdate;
bool m_bUseGameInputQueue;
InputContextHandle_t m_hInputContext;
IGameUISoundPlayback *m_pSoundPlayback;
CUtlVector< InputEvent_t > m_InputQueue;
CUtlVector< KeyValues * > m_GameUIEventMainQueue;
CUtlVector< CUtlString > m_MenuFileNames;
CUtlMap< CUtlString, void * > m_MenuSoundMap;
typedef CUtlMap< CUtlString, IGameUIScreenControllerFactory * > ScreenControllerFactoryMap;
ScreenControllerFactoryMap m_ScreenControllerMap;
typedef CUtlMap< CUtlString, IGameUIGraphicClassFactory * > GameUIGraphicClassFactoryMap;
GameUIGraphicClassFactoryMap m_GraphicClassMap;
bool m_bVisible;
bool m_bSetReleaseTimer;
DmeTime_t m_ReleaseStartTime;
DmeTime_t m_ReleaseTime;
CGameText *m_pCursorText;
};
extern CGameUISystemMgr *g_pGameUISystemMgrImpl;
bool UtlStringLessFunc( const CUtlString &lhs, const CUtlString &rhs );
#endif // GAMEUISYSTEMMANAGER_H

View File

@@ -0,0 +1,763 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#define SUPPORT_CUSTOM_FONT_FORMAT
#ifdef SUPPORT_CUSTOM_FONT_FORMAT
#define _WIN32_WINNT 0x0500
#endif
#include "gameuisystemsurface.h"
#include "gameuisystemmgr.h"
#include "vgui_surfacelib/fontmanager.h"
#include "vgui_surfacelib/texturedictionary.h"
#include "vgui_surfacelib/fonttexturecache.h"
#include "vgui/isystem.h"
#include "tier1/utlbuffer.h"
#include "tier1/keyvalues.h"
#include "materialsystem/imesh.h"
#include "gameuischeme.h"
#include "vgui_controls/Controls.h"
#include "rendersystem/irendercontext.h"
#include "rendersystem/vertexdata.h"
#include "rendersystem/indexdata.h"
#include "GameLayer.h"
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
#include "xbox/xboxstubs.h"
#include "valvefont.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Helper function for getting the language the game ui should use.
//-----------------------------------------------------------------------------
static void HelperGetLanguage( char *pLanguageBuf, int bufSize )
{
bool bValid = false;
if ( IsPC() )
{
bValid = vgui::system()->GetRegistryString( "HKEY_CURRENT_USER\\Software\\Valve\\Steam\\Language", pLanguageBuf, bufSize - 1 );
}
else
{
Q_strncpy( pLanguageBuf, XBX_GetLanguageString(), bufSize );
bValid = true;
}
if ( !bValid )
{
Q_strncpy( pLanguageBuf, "english", bufSize );
}
}
//-----------------------------------------------------------------------------
// Globals...
//-----------------------------------------------------------------------------
static CFontTextureCache g_FontTextureCache;
//-----------------------------------------------------------------------------
// Singleton instance
//-----------------------------------------------------------------------------
CGameUISystemSurface g_GameUISystemSurface;
CGameUISystemSurface *g_pGameUISystemSurface = &g_GameUISystemSurface;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameUISystemSurface::CGameUISystemSurface()
{
m_bIsInitialized = false;
g_FontTextureCache.SetPrefix( "ingameui" );
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGameUISystemSurface::~CGameUISystemSurface()
{
m_CustomFontFileNames.RemoveAll();
m_BitmapFontFileNames.RemoveAll();
m_BitmapFontFileMapping.RemoveAll();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
InitReturnVal_t CGameUISystemSurface::Init()
{
if ( m_bIsInitialized )
return INIT_OK;
// fonts initialization
char language[64];
HelperGetLanguage( language, 64 );
FontManager().SetLanguage( language );
m_bIsInitialized = true;
return INIT_OK;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISystemSurface::Shutdown( void )
{
// Release all textures
TextureDictionary()->DestroyAllTextures();
#if !defined( _GAMECONSOLE )
HMODULE gdiModule = NULL;
#ifdef SUPPORT_CUSTOM_FONT_FORMAT
; // on custom font format Windows takes care of cleaning up the font when the process quits
#else
// release any custom font files
// use newer function if possible
gdiModule = ::LoadLibrary( "gdi32.dll" );
typedef int (WINAPI *RemoveFontResourceExProc)(LPCTSTR, DWORD, PVOID);
RemoveFontResourceExProc pRemoveFontResourceEx = NULL;
if ( gdiModule )
{
pRemoveFontResourceEx = (RemoveFontResourceExProc)::GetProcAddress(gdiModule, "RemoveFontResourceExA");
}
for (int i = 0; i < m_CustomFontFileNames.Count(); i++)
{
if ( pRemoveFontResourceEx )
{
// dvs: Keep removing the font until we get an error back. After consulting with Microsoft, it appears
// that RemoveFontResourceEx must sometimes be called multiple times to work. Doing this insures that
// when we load the font next time we get the real font instead of Ariel.
int nRetries = 0;
while ( (*pRemoveFontResourceEx)(m_CustomFontFileNames[i].String(), 0x10, NULL) && ( nRetries < 10 ) )
{
nRetries++;
Msg( "Removed font resource %s on attempt %d.\n", m_CustomFontFileNames[i].String(), nRetries );
}
}
else
{
// dvs: Keep removing the font until we get an error back. After consulting with Microsoft, it appears
// that RemoveFontResourceEx must sometimes be called multiple times to work. Doing this insures that
// when we load the font next time we get the real font instead of Ariel.
int nRetries = 0;
while ( ::RemoveFontResource(m_CustomFontFileNames[i].String()) && ( nRetries < 10 ) )
{
nRetries++;
Msg( "Removed font resource %s on attempt %d.\n", m_CustomFontFileNames[i].String(), nRetries );
}
}
}
#endif // SUPPORT_CUSTOM_FONT_FORMAT
#endif
m_CustomFontFileNames.RemoveAll();
m_BitmapFontFileNames.RemoveAll();
m_BitmapFontFileMapping.RemoveAll();
#if !defined( _GAMECONSOLE )
if ( gdiModule )
{
::FreeLibrary(gdiModule);
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: adds a custom font file (supports valve .vfont files)
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::AddCustomFontFile( const char *fontFileName )
{
if ( IsGameConsole() )
{
// custom fonts are not supported (not needed) on xbox, all .vfonts are offline converted to ttfs
// ttfs are mounted/handled elsewhere
return true;
}
char fullPath[MAX_PATH];
bool bFound = false;
// windows needs an absolute path for ttf
bFound = g_pFullFileSystem->GetLocalPath( fontFileName, fullPath, sizeof( fullPath ) ) ? true : false;
if ( !bFound )
{
Warning( "Couldn't find custom font file '%s'\n", fontFileName );
return false;
}
// only add if it's not already in the list
Q_strlower( fullPath );
CUtlSymbol sym( fullPath );
int i;
for ( i = 0; i < m_CustomFontFileNames.Count(); i++ )
{
if ( m_CustomFontFileNames[i] == sym )
break;
}
if ( !m_CustomFontFileNames.IsValidIndex( i ) )
{
m_CustomFontFileNames.AddToTail( fullPath );
if ( IsPC() )
{
#ifdef SUPPORT_CUSTOM_FONT_FORMAT
// We don't need the actual file on disk
#else
// make sure it's on disk
// only do this once for each font since in steam it will overwrite the
// registered font file, causing windows to invalidate the font
g_pFullFileSystem->GetLocalCopy( fullPath );
#endif
}
}
#if !defined( _GAMECONSOLE )
#ifdef SUPPORT_CUSTOM_FONT_FORMAT
// Just load the font data, decrypt in memory and register for this process
CUtlBuffer buf;
if ( !g_pFullFileSystem->ReadFile( fontFileName, NULL, buf ) )
{
Msg( "Failed to load custom font file '%s'\n", fontFileName );
return false;
}
if ( !ValveFont::DecodeFont( buf ) )
{
Msg( "Failed to parse custom font file '%s'\n", fontFileName );
return false;
}
DWORD dwNumFontsRegistered = 0;
HANDLE hRegistered = NULL;
hRegistered = ::AddFontMemResourceEx( buf.Base(), buf.TellPut(), NULL, &dwNumFontsRegistered );
if ( !hRegistered )
{
Msg( "Failed to register custom font file '%s'\n", fontFileName );
return false;
}
return hRegistered != NULL;
#else
// try and use the optimal custom font loader, will makes sure fonts are unloaded properly
// this function is in a newer version of the gdi library (win2k+), so need to try get it directly
bool successfullyAdded = false;
HMODULE gdiModule = ::LoadLibrary( "gdi32.dll" );
if (gdiModule)
{
typedef int (WINAPI *AddFontResourceExProc)(LPCTSTR, DWORD, PVOID);
AddFontResourceExProc pAddFontResourceEx = (AddFontResourceExProc)::GetProcAddress( gdiModule, "AddFontResourceExA" );
if (pAddFontResourceEx)
{
int result = (*pAddFontResourceEx)(fullPath, 0x10, NULL);
if (result > 0)
{
successfullyAdded = true;
}
}
::FreeLibrary(gdiModule);
}
// add to windows
bool success = successfullyAdded || (::AddFontResource(fullPath) > 0);
if ( !success )
{
Msg( "Failed to load custom font file '%s'\n", fullPath );
}
Assert( success );
return success;
#endif // SUPPORT_CUSTOM_FONT_FORMAT
#else
return true;
#endif
}
//-----------------------------------------------------------------------------
// Purpose: adds a bitmap font file
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::AddBitmapFontFile( const char *fontFileName )
{
bool bFound = false;
bFound = ( ( g_pFullFileSystem->GetDVDMode() == DVDMODE_STRICT ) || g_pFullFileSystem->FileExists( fontFileName, IsGameConsole() ? "GAME" : NULL ) );
if ( !bFound )
{
Msg( "Couldn't find bitmap font file '%s'\n", fontFileName );
return false;
}
char path[MAX_PATH];
Q_strncpy( path, fontFileName, MAX_PATH );
// only add if it's not already in the list
Q_strlower( path );
CUtlSymbol sym( path );
int i;
for ( i = 0; i < m_BitmapFontFileNames.Count(); i++ )
{
if ( m_BitmapFontFileNames[i] == sym )
break;
}
if ( !m_BitmapFontFileNames.IsValidIndex( i ) )
{
m_BitmapFontFileNames.AddToTail( path );
if ( IsPC() )
{
// make sure it's on disk
// only do this once for each font since in steam it will overwrite the
// registered font file, causing windows to invalidate the font
g_pFullFileSystem->GetLocalCopy( path );
}
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISystemSurface::SetBitmapFontName( const char *pName, const char *pFontFilename )
{
char fontPath[MAX_PATH];
Q_strncpy( fontPath, pFontFilename, MAX_PATH );
Q_strlower( fontPath );
CUtlSymbol sym( fontPath );
for ( int i = 0; i < m_BitmapFontFileNames.Count(); i++ )
{
if ( m_BitmapFontFileNames[i] == sym )
{
// found it, update the mapping
int index = m_BitmapFontFileMapping.Find( pName );
if ( !m_BitmapFontFileMapping.IsValidIndex( index ) )
{
index = m_BitmapFontFileMapping.Insert( pName );
}
m_BitmapFontFileMapping.Element( index ) = i;
break;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CGameUISystemSurface::GetBitmapFontName( const char *pName )
{
// find it in the mapping symbol table
int index = m_BitmapFontFileMapping.Find( pName );
if ( index == m_BitmapFontFileMapping.InvalidIndex() )
{
return "";
}
return m_BitmapFontFileNames[m_BitmapFontFileMapping.Element( index )].String();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISystemSurface::ClearTemporaryFontCache( void )
{
FontManager().ClearTemporaryFontCache();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
const char *CGameUISystemSurface::GetFontName( FontHandle_t font )
{
return FontManager().GetFontName( font );
}
//-----------------------------------------------------------------------------
// Causes fonts to get reloaded, etc.
//-----------------------------------------------------------------------------
void CGameUISystemSurface::ResetFontCaches()
{
// Don't do this on x360!!!
if ( IsGameConsole() )
return;
// clear font texture cache
g_FontTextureCache.Clear();
g_pGameUISchemeManager->ReloadFonts();
}
//-----------------------------------------------------------------------------
// Purpose: cap bits
// Warning: if you change this, make sure the SurfaceV28 wrapper above reports
// the correct capabilities.
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::SupportsFontFeature( FontFeature_t feature )
{
switch ( feature )
{
case FONT_FEATURE_ANTIALIASED_FONTS:
case FONT_FEATURE_DROPSHADOW_FONTS:
return true;
case FONT_FEATURE_OUTLINE_FONTS:
if ( IsGameConsole() )
return false;
return true;
default:
return false;
};
}
//-----------------------------------------------------------------------------
// Purpose: Force a set of characters to be rendered into the font page.
//-----------------------------------------------------------------------------
void CGameUISystemSurface::PrecacheFontCharacters( FontHandle_t font, wchar_t *pCharacterString )
{
wchar_t *pCommonChars = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.!:-/%";
if ( !pCharacterString || !pCharacterString[0] )
{
// use the common chars, alternate languages are not handled
pCharacterString = pCommonChars;
}
int numChars = 0;
while( pCharacterString[ numChars ] )
{
numChars++;
}
int *pTextureIDs_ignored = (int *)_alloca( numChars*sizeof( int ) );
float **pTexCoords_ignored = (float **)_alloca( numChars*sizeof( float * ) );
g_FontTextureCache.GetTextureForChars( font, FONT_DRAW_DEFAULT, pCharacterString, pTextureIDs_ignored, pTexCoords_ignored, numChars );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISystemSurface::DrawFontTexture( int textureId, int xPos, int yPos )
{
Assert( g_pMaterialSystem );
IMaterial *pMaterial = GetMaterial( textureId );
if (!pMaterial)
{
return;
}
CMatRenderContextPtr pRenderContext( g_pMaterialSystem );
IMesh *pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, pMaterial );
if ( !pMesh )
return;
unsigned char textColor[4];
textColor[0] = 255;
textColor[1] = 255;
textColor[2] = 255;
textColor[3] = 255;
int x = xPos;
int y = yPos;
int wide;
int tall;
TextureDictionary()->GetTextureSize( textureId, wide, tall );
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Position3f( x, y, 0 );
meshBuilder.Color4ubv( textColor );
meshBuilder.TexCoord2f( 0, 0, 0 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( x + wide, y, 0 );
meshBuilder.Color4ubv( textColor );
meshBuilder.TexCoord2f( 0, 1, 0 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( x + wide, y + tall, 0 );
meshBuilder.Color4ubv( textColor );
meshBuilder.TexCoord2f( 0, 1, 1 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.Position3f( x, y + tall, 0 );
meshBuilder.Color4ubv( textColor );
meshBuilder.TexCoord2f( 0, 0, 1 );
meshBuilder.AdvanceVertexF<VTX_HAVEPOS | VTX_HAVECOLOR, 1>();
meshBuilder.End();
pMesh->Draw();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CGameUISystemSurface::DrawFontTexture( IRenderContext *pRenderContext, int textureId, int xPos, int yPos )
{
HRenderTexture fontTextureHandle = g_pGameUISystemSurface->GetTextureHandle( textureId );
pRenderContext->BindTexture( 0, fontTextureHandle );
VertexColor_t textColor( 255, 255, 255, 255);
int x = xPos;
int y = yPos;
int wide;
int tall;
TextureDictionary()->GetTextureSize( textureId, wide, tall );
CDynamicVertexData< GameUIVertex_t > vb( pRenderContext, 4, "gamelayer2", "game_controls2" );
vb.Lock();
vb->m_vecPosition.Init( x, y, 0.0f );
vb->m_color = textColor;
vb->m_vecTexCoord.Init( 0, 0 );
vb.AdvanceVertex();
vb->m_vecPosition.Init( x + wide, y, 0.0f );
vb->m_color = textColor;
vb->m_vecTexCoord.Init( 1, 0 );
vb.AdvanceVertex();
vb->m_vecPosition.Init( x+ wide, y + tall, 0.0f );
vb->m_color = textColor;
vb->m_vecTexCoord.Init( 1, 1 );
vb.AdvanceVertex();
vb->m_vecPosition.Init( x, y + tall, 0.0f );
vb->m_color = textColor;
vb->m_vecTexCoord.Init( 0, 1 );
vb.AdvanceVertex();
vb.Unlock();
vb.Bind( 0, 0 );
CDynamicIndexData< uint16 > ib( pRenderContext, 6, "gamelayer", "game_controls" );
ib.Lock();
ib.Index( 0 );
ib.Index( 1 );
ib.Index( 2 );
ib.Index( 0);
ib.Index( 2 );
ib.Index( 3 );
ib.Unlock();
ib.Bind( 0 );
pRenderContext->DrawIndexed( RENDER_PRIM_TRIANGLES, 0, 6 );
}
//-----------------------------------------------------------------------------
// Purpose: Gets the material and texture coords for this char.
// Set up info.drawtype and set the font first.
//-----------------------------------------------------------------------------
IMaterial *CGameUISystemSurface::GetTextureForChar( FontCharRenderInfo &info, float **texCoords )
{
bool bSuccess = g_FontTextureCache.GetTextureForChar( info.currentFont, info.drawType, info.ch, &info.textureId, texCoords );
if ( !bSuccess )
{
return NULL;
}
return TextureDictionary()->GetTextureMaterial( info.textureId );
}
//-----------------------------------------------------------------------------
// Purpose: Gets the material and texture coords for this char.
// Set up info.drawtype and set the font first.
// This call doesnt use the static in the font cache to store the texcoords.
//-----------------------------------------------------------------------------
IMaterial *CGameUISystemSurface::GetTextureAndCoordsForChar( FontCharRenderInfo &info, float *texCoords )
{
bool bSuccess = g_FontTextureCache.GetTextureAndCoordsForChar( info.currentFont, info.drawType, info.ch, &info.textureId, texCoords );
if ( !bSuccess )
{
return NULL;
}
return TextureDictionary()->GetTextureMaterial( info.textureId );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::GetUnicodeCharRenderPositions( FontCharRenderInfo& info, Vector2D *pPositions )
{
info.valid = false;
if ( !info.currentFont )
{
return info.valid;
}
info.valid = true;
info.fontTall = GetFontTall( info.currentFont );
GetCharABCwide( info.currentFont, info.ch, info.abcA, info.abcB, info.abcC );
bool bUnderlined = FontManager().GetFontUnderlined( info.currentFont );
// Do prestep before generating texture coordinates, etc.
if ( !bUnderlined )
{
info.x += info.abcA;
}
// get the character texture from the cache
info.textureId = 0;
float *texCoords = NULL;
if ( !g_FontTextureCache.GetTextureForChar( info.currentFont, info.drawType, info.ch, &info.textureId, &texCoords ) )
{
info.valid = false;
return info.valid;
}
int fontWide = info.abcB;
if ( bUnderlined )
{
fontWide += ( info.abcA + info.abcC );
info.x-= info.abcA;
}
pPositions[0].x = info.x;
pPositions[0].y = info.y;
pPositions[1].x = info.x + fontWide;
pPositions[1].y = info.y;
pPositions[2].x = info.x + fontWide;
pPositions[2].y = info.y + info.fontTall;
pPositions[3].x = info.x;
pPositions[3].y = info.y + info.fontTall;
return info.valid;
}
//-----------------------------------------------------------------------------
// Purpose: adds glyphs to a font created by CreateFont()
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::SetBitmapFontGlyphSet( FontHandle_t font, const char *windowsFontName, float scalex, float scaley, int flags)
{
return FontManager().SetBitmapFontGlyphSet( font, windowsFontName, scalex, scaley, flags );
}
//-----------------------------------------------------------------------------
// Purpose: creates a new empty font
//-----------------------------------------------------------------------------
FontHandle_t CGameUISystemSurface::CreateFont()
{
return FontManager().CreateFont();
}
//-----------------------------------------------------------------------------
// Purpose: adds glyphs to a font created by CreateFont()
//-----------------------------------------------------------------------------
bool CGameUISystemSurface::SetFontGlyphSet( FontHandle_t font, const char *windowsFontName, int tall, int weight, int blur, int scanlines, int flags, int nRangeMin, int nRangeMax)
{
return FontManager().SetFontGlyphSet( font, windowsFontName, tall, weight, blur, scanlines,
flags, nRangeMin, nRangeMax );
}
//-----------------------------------------------------------------------------
// Purpose: returns the max height of a font
//-----------------------------------------------------------------------------
int CGameUISystemSurface::GetFontTall( FontHandle_t font )
{
return FontManager().GetFontTall( font );
}
//-----------------------------------------------------------------------------
// Purpose: returns the abc widths of a single character
// This is used by text classes to handle kerning.
//-----------------------------------------------------------------------------
void CGameUISystemSurface::GetCharABCwide( FontHandle_t font, int ch, int &a, int &b, int &c )
{
FontManager().GetCharABCwide( font, ch, a, b, c );
}
//-----------------------------------------------------------------------------
// Purpose: returns the pixel width of a single character
//-----------------------------------------------------------------------------
int CGameUISystemSurface::GetCharacterWidth( FontHandle_t font, int ch )
{
return FontManager().GetCharacterWidth( font, ch );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
IMaterial *CGameUISystemSurface::GetMaterial( int textureId )
{
return TextureDictionary()->GetTextureMaterial( textureId );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
HRenderTexture CGameUISystemSurface::GetTextureHandle( int textureId )
{
return TextureDictionary()->GetTextureHandle( textureId );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGameUISystemSurface::SetLanguage( const char *pLanguage )
{
FontManager().SetLanguage( pLanguage );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
const char *CGameUISystemSurface::GetLanguage()
{
return FontManager().GetLanguage();
}

View File

@@ -0,0 +1,100 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GAMEUISYSTEMSURFACE_H
#define GAMEUISYSTEMSURFACE_H
#ifdef _WIN32
#pragma once
#endif
#include "igameuisystemmgr.h"
#include "materialsystem/imaterialsystem.h"
#include "vgui_surfacelib/ifontsurface.h"
#include "tier1/utldict.h"
#include "rendersystem/irenderdevice.h"
class CFontTextureCache;
class KeyValues;
//-----------------------------------------------------------------------------
// This class is the interface to the font and font texture, systems.
// Load fonts given by schemes into the systems using this class.
//-----------------------------------------------------------------------------
class CGameUISystemSurface : public IGameUISystemSurface
{
public:
CGameUISystemSurface();
~CGameUISystemSurface();
InitReturnVal_t Init();
void Shutdown();
void PrecacheFontCharacters( FontHandle_t font, wchar_t *pCharacterString = NULL );
FontHandle_t CreateFont();
bool SetFontGlyphSet( FontHandle_t font, const char *windowsFontName, int tall, int weight, int blur, int scanlines, int flags, int nRangeMin = 0, int nRangeMax = 0 );
int GetFontTall( FontHandle_t font );
void GetCharABCwide( FontHandle_t font, int ch, int &a, int &b, int &c );
int GetCharacterWidth( FontHandle_t font, int ch );
const char *GetFontName( FontHandle_t font );
bool AddCustomFontFile( const char *fontFileName );
// Helper fxns for loading bitmap fonts
bool AddBitmapFontFile( const char *fontFileName );
void SetBitmapFontName( const char *pName, const char *pFontFilename );
const char *GetBitmapFontName( const char *pName );
bool SetBitmapFontGlyphSet( FontHandle_t font, const char *windowsFontName, float scalex, float scaley, int flags);
void ClearTemporaryFontCache( void );
// Causes fonts to get reloaded, etc.
void ResetFontCaches();
bool SupportsFontFeature( FontFeature_t feature );
void DrawSetTextureRGBA( int id, const unsigned char* rgba, int wide, int tall ){}
void DrawSetTextureRGBAEx( int id, const unsigned char* rgba, int wide, int tall, ImageFormat format ){}
bool GetUnicodeCharRenderPositions( FontCharRenderInfo& info, Vector2D *pPositions );
IMaterial *GetTextureForChar( FontCharRenderInfo &info, float **texCoords );
IMaterial *GetTextureAndCoordsForChar( FontCharRenderInfo &info, float *texCoords );
// Used for debugging.
void DrawFontTexture( int textureId, int xPos, int yPos );
void DrawFontTexture( IRenderContext *pRenderContext, int textureId, int xPos, int yPos );
IMaterial *GetMaterial( int textureId );
HRenderTexture GetTextureHandle( int textureId );
void GetProportionalBase( int &width, int &height ) { width = BASE_WIDTH; height = BASE_HEIGHT; }
void SetLanguage( const char *pLanguage );
const char *GetLanguage();
private:
enum { BASE_HEIGHT = 480, BASE_WIDTH = 640 };
bool m_bIsInitialized;
CUtlVector< CUtlSymbol > m_CustomFontFileNames;
CUtlVector< CUtlSymbol > m_BitmapFontFileNames;
CUtlDict< int, int > m_BitmapFontFileMapping;
};
extern CGameUISystemSurface *g_pGameUISystemSurface;
#endif // GAMEUISYSTEMSURFACE_H

View File

@@ -0,0 +1,396 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "graphicgroup.h"
#include "gamegraphic.h"
#include "gameuidefinition.h"
#include "animdata.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DMXELEMENT_UNPACK ( CGraphicGroup )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
DMXELEMENT_UNPACK_FIELD( "center", "0 0", Vector2D, m_Geometry.m_Center )
DMXELEMENT_UNPACK_FIELD( "scale", "1 1", Vector2D, m_Geometry.m_Scale )
DMXELEMENT_UNPACK_FIELD( "rotation", "0", float, m_Geometry.m_Rotation )
DMXELEMENT_UNPACK_FIELD( "maintainaspectratio", "0", bool, m_Geometry.m_bMaintainAspectRatio )
DMXELEMENT_UNPACK_FIELD( "sublayertype", "0", int, m_Geometry.m_Sublayer )
DMXELEMENT_UNPACK_FIELD( "visible", "1", bool, m_Geometry.m_bVisible )
DMXELEMENT_UNPACK_FIELD( "initialstate", "-1", int, m_CurrentState )
DMXELEMENT_UNPACK_FIELD( "horizgradient", "0", bool, m_Geometry.m_bHorizontalGradient )
DMXELEMENT_UNPACK_FIELD( "color", "255 255 255 255", Color, m_Geometry.m_Color )
DMXELEMENT_UNPACK_FIELD( "topcolor", "255 255 255 255", Color, m_Geometry.m_TopColor )
DMXELEMENT_UNPACK_FIELD( "bottomcolor", "255 255 255 255", Color, m_Geometry.m_BottomColor )
END_DMXELEMENT_UNPACK( CGraphicGroup, s_GraphicGroupUnpack )
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CGraphicGroup::CGraphicGroup()
{
m_ResultantColor.r = 0;
m_ResultantColor.g = 0;
m_ResultantColor.b = 0;
m_ResultantColor.a = 0;
}
CGraphicGroup::~CGraphicGroup()
{
}
//-----------------------------------------------------------------------------
// Load data from file.
//-----------------------------------------------------------------------------
bool CGraphicGroup::Unserialize( CDmxElement *pElement, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping )
{
pElement->UnpackIntoStructure( this, s_GraphicGroupUnpack );
CDmxAttribute *pGroupElements = pElement->GetAttribute( "groupElements" );
if ( !pGroupElements || pGroupElements->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &elements = pGroupElements->GetArray< CDmxElement * >( );
int nCount = elements.Count();
for ( int i = 0; i < nCount; ++i )
{
// Find the element in the map.
char pBuf[255];
UniqueIdToString( elements[i]->GetId(), pBuf, 255 );
int index = unserializedGraphicMapping.Find( pBuf );
Assert( unserializedGraphicMapping.IsValidIndex( index ) );
CGameGraphic *pGraphic = unserializedGraphicMapping.Element(index);
pGraphic->SetGroup( this );
m_MemberList.AddToTail( pGraphic );
}
// ANIMSTATES
CDmxAttribute *pImageAnims = pElement->GetAttribute( "imageanims" );
if ( !pImageAnims || pImageAnims->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &imageanims = pImageAnims->GetArray< CDmxElement * >( );
nCount = imageanims.Count();
for ( int i = 0; i < nCount; ++i )
{
CAnimData *pAnimData = new CAnimData;
if ( !pAnimData->Unserialize( imageanims[i] ) )
{
delete pAnimData;
return false;
}
m_Anims.AddToTail( pAnimData );
}
char pBuf[255];
UniqueIdToString( pElement->GetId(), pBuf, 255 );
unserializedGraphicMapping.Insert( pBuf, this );
// Ok the initial state is 0, which is (usually ) default.
// default could be aliased to another state though so if it is fix the initial state here.
// default might also not be the state that is 0 so this sets the graphic's initial
// state to be the default one.
SetState( "default" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGraphicGroup::UpdateGeometry()
{
if ( m_CurrentState == -1 )
return;
DmeTime_t flAnimTime = GetAnimationTimePassed();
// Update color
m_Anims[ m_CurrentState ]->m_ColorAnim.GetValue( flAnimTime, &m_Geometry.m_Color );
// Update center location
m_Anims[ m_CurrentState ]->m_CenterPosAnim.GetValue( flAnimTime, &m_Geometry.m_Center );
// Update scale
m_Anims[ m_CurrentState ]->m_ScaleAnim.GetValue( flAnimTime, &m_Geometry.m_Scale );
// Update rotation
m_Anims[ m_CurrentState ]->m_RotationAnim.GetValue( flAnimTime, &m_Geometry.m_Rotation );
for ( int i = 0; i < m_MemberList.Count(); ++i )
{
m_MemberList[i]->UpdateGeometry();
}
}
//-----------------------------------------------------------------------------
// Store the resultant color for groups so kids can just get that.
//-----------------------------------------------------------------------------
void CGraphicGroup::UpdateRenderData( color32 parentColor )
{
if ( !m_Geometry.m_bVisible )
return;
m_ResultantColor.r = (int)( (float)m_Geometry.m_Color.r * (float)(parentColor.r/255.0) );
m_ResultantColor.g = (int)( (float)m_Geometry.m_Color.g * (float)(parentColor.g/255.0) );
m_ResultantColor.b = (int)( (float)m_Geometry.m_Color.b * (float)(parentColor.b/255.0) );
m_ResultantColor.a = (int)( (float)m_Geometry.m_Color.a * (float)(parentColor.a/255.0) );
// Update any children that are groups
// Graphic members are not done because the colors are calculated when we get the render data out.
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
if ( m_MemberList[i]->IsGroup() )
{
CGraphicGroup *pGroup = (CGraphicGroup *)m_MemberList[i];
pGroup->UpdateRenderData( parentColor );
}
}
}
//-----------------------------------------------------------------------------
// Populate lists for rendering
//-----------------------------------------------------------------------------
void CGraphicGroup::UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo )
{
m_Geometry.UpdateRenderTransforms( stageRenderInfo, GetGroup() );
// Create a matrix that ensures no aspect ratio changes.
// Update positions relative to the center, texture coords, and vertex colors
// If the group maintains aspect ratio it will already have handled this in its transform update.
Vector2D center;
// If this is the case we transform the center to screen coords first.
// Then take into account any size scaling in the scalemat
matrix3x4_t screenScalemat;
SetScaleMatrix( stageRenderInfo.parentScale.x, stageRenderInfo.parentScale.y, 1, screenScalemat );
Vector centerVec( m_Geometry.m_Center.x, m_Geometry.m_Center.y, 0 );
Vector centerInScreen;
VectorTransform( centerVec, screenScalemat, centerInScreen );
center.x = centerInScreen.x;
center.y = centerInScreen.y;
matrix3x4_t transmat;
Vector position( center.x, center.y, 0 );
SetIdentityMatrix( transmat );
PositionMatrix( position, transmat );
matrix3x4_t scalemat;
SetScaleMatrix( m_Geometry.m_Scale.x, m_Geometry.m_Scale.y, 1, scalemat );
matrix3x4_t rotmat;
Vector axis( 0, 0, 1 );
MatrixBuildRotationAboutAxis( axis, m_Geometry.m_Rotation, rotmat );
matrix3x4_t temp;
MatrixMultiply( rotmat, scalemat, temp );
matrix3x4_t rawToLocal;
MatrixMultiply( transmat, temp, rawToLocal );
matrix3x4_t groupToScreen;
// Use the matrix that doesn't contain any scale changes if we should
m_pGroup->GetRenderTransform( groupToScreen, true );
MatrixMultiply( groupToScreen, rawToLocal, m_RelToScreenHoldAspectRatio );
// Update all children
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->UpdateRenderTransforms( stageRenderInfo );
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGraphicGroup::AddToGroup( CGameGraphic *pGraphic )
{
m_MemberList.AddToTail( pGraphic );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CGraphicGroup::RemoveFromGroup( CGameGraphic *pGraphic )
{
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
// TODO, what if the graphic is a group?
if ( m_MemberList[i] == pGraphic )
{
m_MemberList.Remove( i );
return;
}
}
}
//-----------------------------------------------------------------------------
// Returns true if any graphic in this group has the state.
//-----------------------------------------------------------------------------
bool CGraphicGroup::HasState( const char *pStateName )
{
if ( CGameGraphic::HasState( pStateName ) )
return true;
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
if ( m_MemberList[i]->HasState( pStateName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Set the state of all members to this state
//-----------------------------------------------------------------------------
void CGraphicGroup::SetState( const char *pStateName )
{
CGameGraphic::SetState( pStateName );
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->SetState( pStateName );
}
}
//-----------------------------------------------------------------------------
// Start playing animations
//-----------------------------------------------------------------------------
void CGraphicGroup::StartPlaying()
{
CGameGraphic::StartPlaying();
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->StartPlaying();
}
}
//-----------------------------------------------------------------------------
// Stop playing animations
//-----------------------------------------------------------------------------
void CGraphicGroup::StopPlaying()
{
CGameGraphic::StopPlaying();
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->StopPlaying();
}
}
//-----------------------------------------------------------------------------
// Move all members to the next available state
// Note this could put all of them into different states
//-----------------------------------------------------------------------------
void CGraphicGroup::AdvanceState()
{
CGameGraphic::AdvanceState();
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
m_MemberList[i]->AdvanceState();
}
}
//-----------------------------------------------------------------------------
// Return the first member of this group that can have keyfocus.
//-----------------------------------------------------------------------------
CHitArea *CGraphicGroup::GetKeyFocusRequestGraphic()
{
for ( int i = 0; i < m_MemberList.Count(); i++ )
{
if ( m_MemberList[i]->CanAcceptInput() )
{
return ( CHitArea * )m_MemberList[i];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Does this graphic own a graphic with this name?
//-----------------------------------------------------------------------------
CGameGraphic *CGraphicGroup::FindGraphicByName( const char *pName ) const
{
int nGraphicCount = m_MemberList.Count();
for ( int i = 0; i < nGraphicCount; ++i )
{
CGameGraphic *pMember = m_MemberList[i];
if ( pMember->IsGraphicNamed( pName ) )
{
// Match.
return pMember;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Group visibility affects all children.
//-----------------------------------------------------------------------------
void CGraphicGroup::SetVisible( bool bVisible )
{
CGameGraphic::SetVisible( bVisible );
int nGraphicCount = m_MemberList.Count();
for ( int i = 0; i < nGraphicCount; ++i )
{
CGameGraphic *pMember = m_MemberList[i];
pMember->SetVisible( bVisible );
}
}
//-----------------------------------------------------------------------------
// Return the appropriate render transform.
// m_RelToScreenHoldAspectRatio is calculated for a stage aspect ratio that has not changed.
//-----------------------------------------------------------------------------
void CGraphicGroup::GetRenderTransform( matrix3x4_t &relToScreen, bool bMaintainAspectRatio ) const
{
if ( bMaintainAspectRatio )
{
relToScreen = m_RelToScreenHoldAspectRatio;
}
else
{
relToScreen = m_Geometry.m_RenderToScreen;
}
}
//-----------------------------------------------------------------------------
// If any parent of this group should maintain aspect ratio, this group should.
//-----------------------------------------------------------------------------
bool CGraphicGroup::MaintainAspectRatio() const
{
if ( m_pGroup && !m_Geometry.m_bMaintainAspectRatio )
{
return m_pGroup->MaintainAspectRatio();
}
return m_Geometry.m_bMaintainAspectRatio;
}

View File

@@ -0,0 +1,79 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef GRAPHICGROUP_H
#define GRAPHICGROUP_H
#ifdef _WIN32
#pragma once
#endif
#include "dmxloader/dmxelement.h"
#include "tier1/utlvector.h"
#include "tier1/utldict.h"
#include "gamegraphic.h"
#include "hitarea.h"
//-----------------------------------------------------------------------------
// A class that holds a group of graphics.
//-----------------------------------------------------------------------------
class CGraphicGroup : public CGameGraphic
{
DECLARE_DMXELEMENT_UNPACK()
public:
CGraphicGroup();
virtual ~CGraphicGroup();
bool Unserialize( CDmxElement *pElement, CUtlDict< CGameGraphic *, int > &unserializedGraphicMapping );
virtual void UpdateGeometry();
void UpdateRenderData( color32 parentColor );
virtual void UpdateRenderTransforms( const StageRenderInfo_t &stageRenderInfo );
color32 GetResultantColor() const { return m_ResultantColor; } // needed by group children.
virtual void GetRenderTransform( matrix3x4_t &relToScreen, bool bMaintainAspectRatio ) const; // needed by group children.
void AddToGroup( CGameGraphic *pGraphic );
void RemoveFromGroup( CGameGraphic *pGraphic );
// From GameGraphic
virtual bool HasState( const char *pStateName );
virtual void SetState( const char *pStateName );
virtual void StartPlaying();
virtual void StopPlaying();
virtual void AdvanceState();
virtual bool IsGroup() const { return true; }
virtual bool IsStageGroup()const { return false; }
CHitArea *GetKeyFocusRequestGraphic();
virtual CGameGraphic *FindGraphicByName( const char *pName ) const;
virtual void SetVisible( bool bVisible );
bool MaintainAspectRatio() const;
protected:
CUtlVector< CGameGraphic * > m_MemberList;
color32 m_ResultantColor;
private:
matrix3x4_t m_RelToScreenHoldAspectRatio;
};
#endif // GRAPHICGROUP_H

View File

@@ -0,0 +1,55 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "graphicscriptinterface.h"
#include "gamegraphic.h"
#include "gameuisystemmgr.h"
BEGIN_SCRIPTDESC_ROOT_NAMED( CGraphicScriptInterface, "CGraphicScriptInterface", SCRIPT_SINGLETON "" )
DEFINE_SCRIPTFUNC( PlayAnim, "Play an animation by name" )
END_SCRIPTDESC()
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CGraphicScriptInterface::CGraphicScriptInterface( IScriptVM *pScriptVM )
{
m_pScriptVM = pScriptVM;
m_pGraphic = NULL;
HSCRIPT Scope = m_pScriptVM->RegisterInstance( this, "Graphic" );
SetScope( Scope );
}
//-----------------------------------------------------------------------------
// Tell this script what graphic it belongs to.
//-----------------------------------------------------------------------------
void CGraphicScriptInterface::InstallGraphic( CGameGraphic *pGraphic )
{
m_pGraphic = pGraphic;
}
//-----------------------------------------------------------------------------
// Play an animation on the graphic.
//-----------------------------------------------------------------------------
void CGraphicScriptInterface::PlayAnim( const char *pAnimName )
{
Assert( m_pGraphic );
if ( !m_pGraphic->HasState( pAnimName ) )
{
Warning( "Unable to find state %s for graphic %s\n", pAnimName, m_pGraphic->GetName() );
return;
}
m_pGraphic->SetState( pAnimName );
}

View File

@@ -0,0 +1,47 @@
//===== Copyright © Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
//===========================================================================//
#ifndef GRAPHICSCRIPTINTERFACE_H
#define GRAPHICSCRIPTINTERFACE_H
#ifdef _WIN32
#pragma once
#endif
#include "gameuiscriptsystem.h"
class CGameGraphic;
//-----------------------------------------------------------------------------
// These are functions that can be called from lua that do things to graphic classes.
//-----------------------------------------------------------------------------
class CGraphicScriptInterface
{
public:
CGraphicScriptInterface( IScriptVM *pScriptVM );
void InstallGraphic( CGameGraphic *pGraphic );
HSCRIPT GetScope( ) { return m_Scope; }
private:
// private functions to support scripting
//CGameGraphic *FindGraphic( int nID );
public:
// exposed functions to scripting
void PlayAnim( const char *pAnimName );
private:
void SetScope( HSCRIPT Scope ) { m_Scope = Scope; }
CGameGraphic *m_pGraphic;
HSCRIPT m_Scope;
IScriptVM *m_pScriptVM;
};
#endif // GRAPHICSCRIPTINTERFACE_H

View File

@@ -0,0 +1,730 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "hitarea.h"
// To handle scaling
#include "materialsystem/imaterialsystem.h"
#include "animdata.h"
#include "inputsystem/inputenums.h"
#include "inputsystem/analogcode.h"
#include "inputsystem/buttoncode.h"
#include "gameuisystemmgr.h"
#include "graphicgroup.h"
#include "inputgameui.h"
#include "graphicscriptinterface.h"
#include "inputgameui.h"
#include "gameuisystemmgr.h"
#include "gameuiscript.h"
#include "gameuisystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define DEBUG_INPUT_EVENTS 0
// Class factory for scripting.
class CHitAreaClassFactory : IGameUIGraphicClassFactory
{
public:
CHitAreaClassFactory()
{
Assert( g_pGameUISystemMgrImpl );
g_pGameUISystemMgrImpl->RegisterGraphicClassFactory( "hitarea", this );
}
// Returns an instance of a graphic interface (keyvalues owned by caller)
virtual CGameGraphic *CreateNewGraphicClass( KeyValues *kvRequest, CGameUIDefinition *pMenu )
{
Assert( pMenu );
CHitArea *pNewGraphic = NULL;
const char *pName = kvRequest->GetString( "name", NULL );
if ( pName )
{
pNewGraphic = new CHitArea( pName );
// Rects are normally 0,0, doing this so we can see script created rects.
pNewGraphic->SetScale( 100, 100 );
pMenu->AddGraphicToLayer( pNewGraphic, SUBLAYER_STATIC );
// Now set the attributes.
for ( KeyValues *arg = kvRequest->GetFirstSubKey(); arg != NULL; arg = arg->GetNextKey() )
{
pNewGraphic->HandleScriptCommand( arg );
}
}
return pNewGraphic;
}
};
static CHitAreaClassFactory g_CDynamicRectClassFactory;
BEGIN_DMXELEMENT_UNPACK ( CHitArea )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "name", "", m_pName )
DMXELEMENT_UNPACK_FIELD( "center", "0 0", Vector2D, m_Geometry.m_Center )
DMXELEMENT_UNPACK_FIELD( "scale", "0 0", Vector2D, m_Geometry.m_Scale )
DMXELEMENT_UNPACK_FIELD( "rotation", "0", float, m_Geometry.m_Rotation )
DMXELEMENT_UNPACK_FIELD( "maintainaspectratio", "0", bool, m_Geometry.m_bMaintainAspectRatio )
DMXELEMENT_UNPACK_FIELD( "sublayertype", "0", int, m_Geometry.m_Sublayer )
DMXELEMENT_UNPACK_FIELD( "visible", "1", bool, m_Geometry.m_bVisible )
DMXELEMENT_UNPACK_FIELD( "initialstate", "-1", int, m_CurrentState )
DMXELEMENT_UNPACK_FIELD( "dragenabled", "0", bool, m_bDragEnabled )
DMXELEMENT_UNPACK_FIELD_UTLSTRING( "on_mouse_left_clicked_cmd", "", m_OnMouseLeftClickedScriptCommand )
END_DMXELEMENT_UNPACK( CHitArea, s_HitAreaUnpack )
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CHitArea::CHitArea( const char *pName )
{
m_bCanAcceptInput = true;
m_bCanStartDragging = false;
m_IsDragging = false;
m_DragStartCursorPos[0] = 0;
m_DragStartCursorPos[1] = 0;
m_DragCurrentCursorPos[0] = 0;
m_DragCurrentCursorPos[1] = 0;
// DME default values.
m_pName = pName;
m_Geometry.m_Center.x = 0;
m_Geometry.m_Center.y = 0;
m_Geometry.m_Scale.x = 0;
m_Geometry.m_Scale.y = 0;
m_Geometry.m_Rotation = 0;
m_Geometry.m_bMaintainAspectRatio = 0;
m_Geometry.m_Sublayer = 0;
m_Geometry.m_bVisible = true;
m_CurrentState = -1;
m_bDragEnabled = false;
m_OnMouseLeftClickedScriptCommand = NULL;
m_Geometry.m_RelativePositions.AddToTail( Vector2D( -.5, -.5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( .5, -.5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( .5, .5 ) );
m_Geometry.m_RelativePositions.AddToTail( Vector2D( -.5, .5 ) );
CTriangle triangle;
triangle.m_PointIndex[0] = 0;
triangle.m_PointIndex[1] = 1;
triangle.m_PointIndex[2] = 2;
m_Geometry.m_Triangles.AddToTail( triangle );
triangle.m_PointIndex[0] = 0;
triangle.m_PointIndex[1] = 2;
triangle.m_PointIndex[2] = 3;
m_Geometry.m_Triangles.AddToTail( triangle );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CHitArea::~CHitArea()
{
// TODO: move to manager?/ as it should control allocations and deallocations.
g_pInputGameUI->PanelDeleted( this );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
bool CHitArea::Unserialize( CDmxElement *pGraphic )
{
pGraphic->UnpackIntoStructure( this, s_HitAreaUnpack );
// GEOMETRY
CDmxAttribute *pRelativePositions = pGraphic->GetAttribute( "relativepositions" );
if ( !pRelativePositions || pRelativePositions->GetType() != AT_VECTOR2_ARRAY )
{
return false;
}
const CUtlVector< Vector2D > &relpositions = pRelativePositions->GetArray< Vector2D >( );
int nCount = relpositions.Count();
m_Geometry.m_RelativePositions.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
m_Geometry.m_RelativePositions.AddToTail( Vector2D( relpositions[i].x, relpositions[i].y ) );
}
CDmxAttribute *pTriangles = pGraphic->GetAttribute( "triangles" );
if ( !pTriangles || pTriangles->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &triangles = pTriangles->GetArray< CDmxElement * >( );
nCount = triangles.Count();
m_Geometry.m_Triangles.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
CDmxAttribute *pPoints = triangles[i]->GetAttribute( "positionindexes" );
const CUtlVector< int > &points = pPoints->GetArray< int >( );
CTriangle triangle;
triangle.m_PointIndex[0] = points[0];
triangle.m_PointIndex[1] = points[1];
triangle.m_PointIndex[2] = points[2];
m_Geometry.m_Triangles.AddToTail( triangle );
}
// ANIMSTATES
CDmxAttribute *pImageAnims = pGraphic->GetAttribute( "imageanims" );
if ( !pImageAnims || pImageAnims->GetType() != AT_ELEMENT_ARRAY )
{
return false;
}
const CUtlVector< CDmxElement * > &imageanims = pImageAnims->GetArray< CDmxElement * >( );
nCount = imageanims.Count();
for ( int i = 0; i < nCount; ++i )
{
CAnimData *pAnimData = new CAnimData;
if ( !pAnimData->Unserialize( imageanims[i] ) )
{
delete pAnimData;
return false;
}
m_Anims.AddToTail( pAnimData );
}
SetState( "default" );
return true;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHitArea::UpdateGeometry()
{
if ( m_CurrentState == -1 )
return;
DmeTime_t flAnimTime = GetAnimationTimePassed();
// Update center location
m_Anims[ m_CurrentState ]->m_CenterPosAnim.GetValue( flAnimTime, &m_Geometry.m_Center );
// Update scale
m_Anims[ m_CurrentState ]->m_ScaleAnim.GetValue( flAnimTime, &m_Geometry.m_Scale );
// Update rotation
m_Anims[ m_CurrentState ]->m_RotationAnim.GetValue( flAnimTime, &m_Geometry.m_Rotation );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHitArea::UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex )
{
m_Geometry.CalculateExtents();
bool bDrawHitAreas = false;
if ( !m_Geometry.m_bVisible )
return;
if ( bDrawHitAreas )
{
// Time to invent some render data to draw this thing.
int i = renderGeometryLists[firstListIndex].AddToTail();
CRenderGeometry &renderGeometry = renderGeometryLists[firstListIndex][i];
int nCount = m_Geometry.m_RelativePositions.Count();
for ( int i = 0; i < nCount; ++i )
{
// Position
Vector relativePosition( m_Geometry.m_RelativePositions[i].x, m_Geometry.m_RelativePositions[i].y, 0 );
Vector screenpos;
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenpos );
renderGeometry.m_Positions.AddToTail( Vector2D( screenpos.x, screenpos.y ) );;
// Vertex Color
color32 hitAreaColor;
hitAreaColor.r = 255;
hitAreaColor.g = 100;
hitAreaColor.b = 100;
hitAreaColor.a = 255;
renderGeometry.m_VertexColors.AddToTail( hitAreaColor );
}
// TexCoords
renderGeometry.m_TextureCoords.AddToTail( Vector2D( 0 , 0) );
renderGeometry.m_TextureCoords.AddToTail( Vector2D( 1 , 0) );
renderGeometry.m_TextureCoords.AddToTail( Vector2D( 1 , 1) );
renderGeometry.m_TextureCoords.AddToTail( Vector2D( 0 , 1) );
// Triangles
nCount = m_Geometry.m_Triangles.Count();
for ( int i = 0; i < nCount; ++i )
{
renderGeometry.m_Triangles.AddToTail( m_Geometry.m_Triangles[i] );
}
// Anim Info
renderGeometry.m_SheetSequenceNumber = 0;
renderGeometry.m_AnimationRate = 1;
renderGeometry.m_bAnimate = 0;
renderGeometry.m_pImageAlias = NULL;
}
// Now transform our array of positions into local graphic coord system.
int nCount = m_Geometry.m_RelativePositions.Count();
m_ScreenPositions.RemoveAll();
for ( int i = 0; i < nCount; ++i )
{
// Position
Vector relativePosition( m_Geometry.m_RelativePositions[i].x, m_Geometry.m_RelativePositions[i].y, 0 );
Vector screenpos;
VectorTransform( relativePosition, m_Geometry.m_RenderToScreen, screenpos );
m_ScreenPositions.AddToTail( Vector2D( screenpos.x, screenpos.y ) );
}
}
//-----------------------------------------------------------------------------
// Determine if x,y is inside the graphic.
//-----------------------------------------------------------------------------
bool CHitArea::HitTest( int x, int y )
{
if ( !m_bCanAcceptInput ) // note if graphic is invisible, this is false
return false;
if ( m_ScreenPositions.Count() == 0 )
return false;
for ( int i = 0; i < m_Geometry.GetTriangleCount(); ++i )
{
if ( PointTriangleHitTest(
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[0] ],
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[1] ],
m_ScreenPositions[ m_Geometry.m_Triangles[i].m_PointIndex[2] ],
Vector2D( x, y ) ) )
{
//Msg( "%d, %d hit\n", x, y );
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Event that occurs when cursor enters the geometry area
//-----------------------------------------------------------------------------
void CHitArea::OnCursorEnter()
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnCursorEnter\n" );
#endif
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_GAINMOUSEFOCUS" );
}
KeyValues *kvEvent = new KeyValues( "OnMouseFocusGained" );
KeyValues::AutoDelete autodelete( kvEvent );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
g_pGameUISystemMgrImpl->OnMouseFocusGained( this );
}
//-----------------------------------------------------------------------------
// Event that occurs when cursor leaves the geometry area
//-----------------------------------------------------------------------------
void CHitArea::OnCursorExit()
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnCursorExit\n" );
#endif
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_LOSEMOUSEFOCUS" );
}
KeyValues *kvEvent = new KeyValues( "OnMouseFocusLost" );
KeyValues::AutoDelete autodelete( kvEvent );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
g_pGameUISystemMgrImpl->OnMouseFocusLost( this );
}
#define DRAG_THRESHOLD_SQUARED 16
//-----------------------------------------------------------------------------
// Event that occurs when cursor moved inside the geometry area
//-----------------------------------------------------------------------------
void CHitArea::OnCursorMove( const int &cursorX, const int &cursorY )
{
//Msg( "CHitArea::OnCursorMove\n" );
if ( m_bCanStartDragging )
{
m_DragCurrentCursorPos[0] = cursorX;
m_DragCurrentCursorPos[1] = cursorY;
float dx = m_DragCurrentCursorPos[0] - m_DragStartCursorPos[0];
float dy = m_DragCurrentCursorPos[1] - m_DragStartCursorPos[1];
float distance = dx * dx + dy * dy;
if ( distance > DRAG_THRESHOLD_SQUARED )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::Starting dragging\n" );
#endif
OnDragStartCallScriptEvent( cursorX, cursorY );
m_bCanStartDragging = false;
m_IsDragging = true;
}
}
else if ( m_IsDragging )
{
m_DragCurrentCursorPos[0] = cursorX;
m_DragCurrentCursorPos[1] = cursorY;
OnDragCallScriptEvent( cursorX, cursorY );
}
}
//-----------------------------------------------------------------------------
// Event that occurs when left mouse button is pressed
//-----------------------------------------------------------------------------
void CHitArea::OnMouseDown( const ButtonCode_t &code )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnMouseDown\n" );
#endif
// Drag and drop supported for left mouse button only.
// This hit area must be drag enabled to support dragging.
if ( code == MOUSE_LEFT && m_bDragEnabled )
{
m_bCanStartDragging = true;
g_pInputGameUI->GetCursorPos( m_DragStartCursorPos[0], m_DragStartCursorPos[1] );
}
if ( m_pGroup )
{
if ( code == MOUSE_LEFT )
{
m_pGroup->SetState( "AUTO_MOUSELEFTDOWN" );
}
else if ( code == MOUSE_RIGHT )
{
m_pGroup->SetState( "AUTO_MOUSERIGHTDOWN" );
}
else if ( code == MOUSE_MIDDLE )
{
m_pGroup->SetState( "AUTO_MOUSEMIDDLEDOWN" );
}
}
// Check for scripting for this control first.
KeyValues *kvEvent = new KeyValues( "OnMouseDown" );
KeyValues::AutoDelete autodelete( kvEvent );
kvEvent->SetInt( "code", code );
// Always call generic click handler to allow host-overrides
kvEvent->SetName( "OnMouseClicked" );
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
// Call assigned handlers
if ( code == MOUSE_LEFT && !m_OnMouseLeftClickedScriptCommand.IsEmpty() )
{
kvEvent->SetName( m_OnMouseLeftClickedScriptCommand );
bool bExecuted = g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
if ( !bExecuted )
{
Warning( "Unable to find script function %s (assigned to OnMouseLeftClicked)\n", kvEvent->GetName() );
}
}
}
//-----------------------------------------------------------------------------
// Event that occurs when mouse button is released
// Script events should be tied to mouse release events only, not mouse down.
// Scripts should only fire if this graphic has mousefocus.
//-----------------------------------------------------------------------------
void CHitArea::OnMouseUp( const ButtonCode_t &code, bool bFireScripts )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnMouseUp\n" );
#endif
m_bCanStartDragging = false;
if ( m_pGroup )
{
if ( code == MOUSE_LEFT )
{
m_pGroup->SetState( "AUTO_MOUSELEFTUP" );
}
else if ( code == MOUSE_RIGHT )
{
m_pGroup->SetState( "AUTO_MOUSERIGHTUP" );
}
else if ( code == MOUSE_MIDDLE )
{
m_pGroup->SetState( "AUTO_MOUSEMIDDLEUP" );
}
}
if ( m_IsDragging )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::Stopped dragging\n" );
#endif
OnDragStopCallScriptEvent( m_DragCurrentCursorPos[0], m_DragCurrentCursorPos[1] );
}
else if ( bFireScripts )
{
KeyValues *kvEvent = new KeyValues( "OnMouseUp" );
KeyValues::AutoDelete autodelete( kvEvent );
kvEvent->SetInt( "code", code );
// Always call generic click handler to allow host-overrides
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
m_IsDragging = false;
}
//-----------------------------------------------------------------------------
// Event that occurs when mouse button is double clicked
//-----------------------------------------------------------------------------
void CHitArea::OnMouseDoubleClick( const ButtonCode_t &code )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnMouseDoubleClick\n" );
#endif
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_MOUSEDOUBLECLICK" );
}
}
//-----------------------------------------------------------------------------
// Event that occurs when a key is pressed
//-----------------------------------------------------------------------------
void CHitArea::OnKeyDown( const ButtonCode_t &code )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnKeyDown\n" );
#endif
// Pad input gives you pressed and released messages only for buttons
if ( IsJoystickCode( code ) )
{
KeyValues *kvEvent = new KeyValues( "OnButtonPressed" );
KeyValues::AutoDelete autodelete( kvEvent );
kvEvent->SetInt( "code", code );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnKeyCodeTyped( code );
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
else
{
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_KEYDOWN" );
}
}
}
//-----------------------------------------------------------------------------
// Event that occurs when a key is released
//-----------------------------------------------------------------------------
void CHitArea::OnKeyUp( const ButtonCode_t &code )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnKeyUp\n" );
#endif
// Pad input gives you pressed and released messages only for buttons
if ( IsJoystickCode( code ) )
{
KeyValues *kvEvent = new KeyValues( "OnButtonReleased" );
KeyValues::AutoDelete autodelete( kvEvent );
kvEvent->SetInt( "code", code );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnKeyCodeTyped( code );
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
else
{
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_KEYUP" );
}
}
}
//-----------------------------------------------------------------------------
// Event that occurs when a key code is typed
//-----------------------------------------------------------------------------
void CHitArea::OnKeyCodeTyped( const ButtonCode_t &code )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnKeyCodeTyped\n" );
#endif
Assert( g_pInputGameUI->GetKeyFocus() == this );
KeyValues *kvEvent = new KeyValues( "OnKeyTyped" );
KeyValues::AutoDelete autodelete( kvEvent );
kvEvent->SetInt( "code", code );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnKeyCodeTyped( code );
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
//-----------------------------------------------------------------------------
// Event that occurs when a key is typed
//-----------------------------------------------------------------------------
void CHitArea::OnKeyTyped( const wchar_t &unichar )
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnKeyTyped\n" );
#endif
Assert( g_pInputGameUI->GetKeyFocus() == this );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnKeyTyped( unichar );
}
//-----------------------------------------------------------------------------
// Event that occurs when key focus is lost
//-----------------------------------------------------------------------------
void CHitArea::OnLoseKeyFocus()
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnLoseKeyFocus\n" );
#endif
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_LOSEKEYFOCUS" );
}
KeyValues *kvEvent = new KeyValues( "OnKeyFocusLost" );
KeyValues::AutoDelete autodelete( kvEvent );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
//-----------------------------------------------------------------------------
// Event that occurs when key focus is gained
//-----------------------------------------------------------------------------
void CHitArea::OnGainKeyFocus()
{
#if ( DEBUG_INPUT_EVENTS )
Msg( "CHitArea::OnGainKeyFocus\n" );
#endif
if ( m_pGroup )
{
m_pGroup->SetState( "AUTO_GAINKEYFOCUS" );
}
KeyValues *kvEvent = new KeyValues( "OnKeyFocusGained" );
KeyValues::AutoDelete autodelete( kvEvent );
// chain to main system if this graphic doesn't handle it.
g_pGameUISystemMgrImpl->OnGameGraphicScriptEvent( this, kvEvent );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHitArea::OnDragStartCallScriptEvent( const int &cursorX, const int &cursorY )
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHitArea::OnDragCallScriptEvent( const int &cursorX, const int &cursorY )
{
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CHitArea::OnDragStopCallScriptEvent( const int &cursorX, const int &cursorY )
{
}
//-----------------------------------------------------------------------------
// Handle focus updating on visibility change.
//-----------------------------------------------------------------------------
void CHitArea::SetVisible( bool bVisible )
{
m_Geometry.m_bVisible = bVisible;
m_bCanAcceptInput = bVisible;
m_bCanStartDragging = false;
if ( bVisible )
{
g_pGameUISystemMgrImpl->ForceFocusUpdate();
}
else
{
// Untested
g_pInputGameUI->GraphicHidden( this );
}
}
//-----------------------------------------------------------------------------
// Handle commands from scripting
//-----------------------------------------------------------------------------
KeyValues * CHitArea::HandleScriptCommand( KeyValues *args )
{
char const *szCommand = args->GetName();
if ( !Q_stricmp( "SetDragEnabled", szCommand ) )
{
m_bDragEnabled = args->GetBool( "dragenabled", 0 );
return NULL;
}
else if ( !Q_stricmp( "SetMouseLeftClickedCommand", szCommand ) )
{
m_OnMouseLeftClickedScriptCommand = args->GetString( "command", "" );
return NULL;
}
if ( !Q_stricmp( "RequestFocus", szCommand ) )
{
g_pGameUISystemMgrImpl->RequestKeyFocus( this, args );
return NULL;
}
return CGameGraphic::HandleScriptCommand( args );
}

View File

@@ -0,0 +1,103 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef HITAREA_H
#define HITAREA_H
#ifdef _WIN32
#pragma once
#endif
#include "gamegraphic.h"
#include "dmxloader/dmxelement.h"
#include "tier1/utlvector.h"
#include "vstdlib/ieventsystem.h"
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CHitArea : public CGameGraphic
{
DECLARE_DMXELEMENT_UNPACK()
public:
CHitArea( const char *pName );
virtual ~CHitArea();
bool Unserialize( CDmxElement *pGraphic );
// Update geometry and execute scripting.
virtual void UpdateGeometry();
virtual void UpdateRenderData( color32 parentColor, CUtlVector< RenderGeometryList_t > &renderGeometryLists, int firstListIndex );
virtual bool HitTest( int x, int y );
// Cursor events
// AUTO_GAINMOUSEFOCUS
void OnCursorEnter();
// AUTO_LOSEMOUSEFOCUS
void OnCursorExit();
void OnCursorMove( const int &cursorX, const int &cursorY );
// Mouse events
// AUTO_MOUSELEFTDOWN
// AUTO_MOUSERIGHTDOWN
// AUTO_MOUSEMIDDLEDOWN
void OnMouseDown( const ButtonCode_t &code );
// AUTO_MOUSELEFTUP
// AUTO_MOUSERIGHTUP
// AUTO_MOUSEMIDDLEUP
void OnMouseUp( const ButtonCode_t &code, bool bFireScripts = true );
// AUTO_MOUSEDOUBLECLICK
void OnMouseDoubleClick( const ButtonCode_t &code );
void OnMouseWheel( const int &delta ){}
// Keyboard events
// AUTO_KEYDOWN
void OnKeyDown( const ButtonCode_t &code );
// AUTO_KEYUP
void OnKeyUp( const ButtonCode_t &code );
void OnKeyCodeTyped( const ButtonCode_t &code );
void OnKeyTyped( const wchar_t &unichar );
// AUTO_GAINKEYFOCUS
void OnGainKeyFocus();
// AUTO_LOSEKEYFOCUS
void OnLoseKeyFocus();
// Calls to scripting.
void OnDragStartCallScriptEvent( const int &cursorX, const int &cursorY );
void OnDragCallScriptEvent( const int &cursorX, const int &cursorY );
void OnDragStopCallScriptEvent( const int &cursorX, const int &cursorY );
virtual void SetVisible( bool bVisible );
virtual bool IsHitArea() const { return true; }
virtual KeyValues *HandleScriptCommand( KeyValues *args );
private:
CHitArea();
CUtlVector< Vector2D > m_ScreenPositions;
bool m_bDragEnabled;
bool m_bCanStartDragging;
bool m_IsDragging;
int m_DragStartCursorPos[2];
int m_DragCurrentCursorPos[2];
CUtlString m_OnMouseLeftClickedScriptCommand;
};
#endif // HITAREA_H

Some files were not shown because too many files have changed in this diff Show More