VGUI2: Creating a panel: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
mNo edit summary
No edit summary
Line 1: Line 1:
[[Category:Tutorials]][[Category:VGUI|C]]
[[Category:Tutorials]][[Category:VGUI|C]]


==Requirements==
==Requerimientos==
Have read and understood (or understand):<br>
Haber leido y comprendido (o comprender):<br>
*[[VGUI Documentation]]
*[[VGUI Documentation]]
*[[HUD Elements]]
*[[HUD Elements]]
Can code:
Codigos:
*C++ (!!!!)
*C++ (!!!!)
*Script
*Script
This tutorial is about creating a simple interactive interface
Este tutorial es sobre crear una interfaz simple e interactiva:


==Understanding how VGUI2 works==
==Entendiendo como funciona VGUI2==
Every VGUI2 dialog that you see while using source based games is basically called a Panel.
Cada dialogo VGUI2 que ves mientras usas juegos basados en source es llamado, básicamente, Panel.


Every Panel consists of three components:
Cada Panel consiste en tres componentes:


* Scheme
* Scheme (Esquema)
* Control Settings
* Control Settings (Propiedades de control)
* Code
* Code (Código)


===The Scheme===
===The Scheme - El Esquema===


The scheme is a general configuration file which stores information about the colors of certain elements such as buttons, combo boxes, labels, etc. A typical scheme file is SourceScheme.res, for example. If you plan to create a panel which looks like the other panels in the menu you should use the same scheme file as they do.
El esquema es un archivo de configuración general que almacena información sobre el color de ciertos elementos como botones, comboboxes, labels, etc. Un archivo de esquema típico es SourceScheme.res, por ejemplo. Si planeas crear un panel semejante a los otros paneles en el menu, deberías usar el mismo archivo de esquema que ellos usan.


===Control Settings===
===Control Settings - Propiedades de Control===


The control settings file stores information about the relative position of your panel and its elements.  
El archivo de las propiedades de control almacena información sobre la posición relativa de tu panel y de sus elementos.


Every panel has a very own resource file. To create a resource file, there are two ways: Either you create one on your own using an editor like notepad, or you use Valves InGame Resource Editor.
Cada panel tiene su propio archivo de recuersos. Para crearlos, hay dos maneras: Puedes crear uno por tu cuenta usando un editor como notepad, o puedes usar Valves InGame Resource Editor.


===Code===
===Código===


The code is the most important part of a panel, since the code decides what to do if the user clicks a button. To create and destroy the panel, you use the code. Fortunately you can set a lot more things than in the resource file(s). Code is the most important thing in this tutorial.
El código es la parte más importante de un panel, desde el código se decide que hacer si el usuario clickea un botón. Para crear y destruir un panel, se usa código. Afortunadamente puedes establecer muchas más cosas que en el(los)archivo(s) de recursos. El códido es la cosa más importante de este tutorial.


==Creating a panel==
==Creando un panel==


Ok, let us assume we want to create a door, for real this time. Since we are not able to create a door from scratch, the first thing we do is to step by at the building centre. What we ask for, is a basic door. It works, but we have still plans to customize it.  
Ok, let us assume we want to create a door, for real this time. Since we are not able to create a door from scratch, the first thing we do is to step by at the building centre. What we ask for, is a basic door. It works, but we have still plans to customize it.  
Line 39: Line 39:
===Starting Off===
===Starting Off===


The panel class is the base class of all VGUI2 elements. To get a rough overview about all the VGUI2  
La clase panel es la clase base de todos los elementos VGUI2. Para obtener una visión general acerca de todos los elementos VGUI2, demos un vistazo dentro de la carpeta vgui_elements. Por supuesto, no solo compramos un poco de madera en nuestro centro local de construcción.
elements, have a look into the vgui_elements folder. Of course, we don't just buy some wood in our local building centre.  


The important class is the EditablePanel class that inherits from the Panel class. Our panel will be a new class which inherits from the EditablePanel class. This results in several advantages: We can code methods related to the content of the panel, we can overwrite the methods of the base classes and do much more useful stuff.
La clase importante es la clase EditablePanel que hereda desde la clase Panel. Nuestro panel será una nueva clase que hereda desde la clase EditablePanel. Esto resulta en diversas ventajas: podemos codificar metodos relativos al contenido del panel, podemos sobreescribir métodos de la clase base y muchas más cosas útiles.


You can create a new file ''MyPanel.cpp'' underneath the Source Files inside the '''client''' project.
Puedes crear un nuevo archivo ''MyPanel.cpp'' debajo de Source Files dentro del proyecto '''client'''.


===MyPanel.cpp===
===MyPanel.cpp===


  //The following include files are necessary to allow your MyPanel.cpp to compile.
  // //Los siguientes archivos include son necesarios para compilar tu MyPanel.cpp.
  #include "cbase.h"
  #include "cbase.h"
  #include "IMyPanel.h"
  #include "IMyPanel.h"
Line 74: Line 73:
  };
  };


The constructor:
El constructor:
The argument is vgui::VPANEL parent. After reading the [[VGUI Documentation]], you should know that every panel has a parent and why it has a parent.  
El argumento es vgui::VPANEL parent. Después de leer la [[VGUI Documentation]], deberias saber que todo panel tiene un padre y porque lo tiene.


Underneath the above code, add:
Bajo el codigo de arriba, añade:
<pre>
<pre>
// Constuctor: Initializes the Panel
// Constuctor: Initializes the Panel
Line 108: Line 107:
</pre>
</pre>


The first lines are pretty easy to understand. SetScheme is used to set the source scheme, which is the standard scheme for Half-Life 2. We get a pointer to the scheme by calling LoadSchemeFromFile(...). The LoadControlSettings function is used to load the control settings resolution file. The last line is explained in the VGUI2 documentation.
Las primeras lineas son bastante sencillas de entender. SetScheme es usada para establecer el la fuente del esquema, que es el esquema estándart para Half-Life 2. Conseguimos un puntero al esquema llamando a LoadSchemeFromFile(...). La función LoadControlSettings es usada para cargar el archivo de configuraciones de control de resolución. La última línea esta explicada en la codumentación VGUI2.


Underneath the above code, add:
Siguiendo al codigo expuesto arriba, añade:
<pre>
<pre>
//Class: CMyPanelInterface Class. Used for construction.
//Class: CMyPanelInterface Class. Used for construction.
Line 140: Line 139:
</pre>
</pre>


Next you can create ''IMyPanel.h'' in the same folder.
A continuación puedes crear ''IMyPanel.h'' en el mismo directorio.


===IMyPanel.h===
===IMyPanel.h===
Line 158: Line 157:
==Calling the panel==
==Calling the panel==


To call the panel, we add a few lines to the '''vgui_int.cpp''' file. Vgui_int.cpp includes functions which call all the panels. The VGui_CreateGlobalPanels() function is where the addition takes place.
Para llamar al panel, añadimos unas pocas lineas en el archivo '''vgui_int.cpp'''. Vgui_int.cpp incluye funciones que llaman a todos los paneles. La función VGui_CreateGlobalPanels() es donde la adición de los paneles tiene lugar.


This is the point, where you have to decide when the panel should show up. Either you create a panel that can be accessed during the game, or you create a panel for the main menu.
This is the point, where you have to decide when the panel should show up. Either you create a panel that can be accessed during the game, or you create a panel for the main menu.

Revision as of 09:44, 16 November 2008


Requerimientos

Haber leido y comprendido (o comprender):

Codigos:

  • C++ (!!!!)
  • Script

Este tutorial es sobre crear una interfaz simple e interactiva:

Entendiendo como funciona VGUI2

Cada dialogo VGUI2 que ves mientras usas juegos basados en source es llamado, básicamente, Panel.

Cada Panel consiste en tres componentes:

  • Scheme (Esquema)
  • Control Settings (Propiedades de control)
  • Code (Código)

The Scheme - El Esquema

El esquema es un archivo de configuración general que almacena información sobre el color de ciertos elementos como botones, comboboxes, labels, etc. Un archivo de esquema típico es SourceScheme.res, por ejemplo. Si planeas crear un panel semejante a los otros paneles en el menu, deberías usar el mismo archivo de esquema que ellos usan.

Control Settings - Propiedades de Control

El archivo de las propiedades de control almacena información sobre la posición relativa de tu panel y de sus elementos.

Cada panel tiene su propio archivo de recuersos. Para crearlos, hay dos maneras: Puedes crear uno por tu cuenta usando un editor como notepad, o puedes usar Valves InGame Resource Editor.

Código

El código es la parte más importante de un panel, desde el código se decide que hacer si el usuario clickea un botón. Para crear y destruir un panel, se usa código. Afortunadamente puedes establecer muchas más cosas que en el(los)archivo(s) de recursos. El códido es la cosa más importante de este tutorial.

Creando un panel

Ok, let us assume we want to create a door, for real this time. Since we are not able to create a door from scratch, the first thing we do is to step by at the building centre. What we ask for, is a basic door. It works, but we have still plans to customize it.

Starting Off

La clase panel es la clase base de todos los elementos VGUI2. Para obtener una visión general acerca de todos los elementos VGUI2, demos un vistazo dentro de la carpeta vgui_elements. Por supuesto, no solo compramos un poco de madera en nuestro centro local de construcción.

La clase importante es la clase EditablePanel que hereda desde la clase Panel. Nuestro panel será una nueva clase que hereda desde la clase EditablePanel. Esto resulta en diversas ventajas: podemos codificar metodos relativos al contenido del panel, podemos sobreescribir métodos de la clase base y muchas más cosas útiles.

Puedes crear un nuevo archivo MyPanel.cpp debajo de Source Files dentro del proyecto client.

MyPanel.cpp

// //Los siguientes archivos include son necesarios para compilar tu MyPanel.cpp.
#include "cbase.h"
#include "IMyPanel.h"
using namespace vgui;
#include <vgui/IVGui.h>
#include <vgui_controls/Frame.h>

//CMyPanel class: Tutorial example class
class CMyPanel : public vgui::Frame
{
	DECLARE_CLASS_SIMPLE(CMyPanel, vgui::Frame); 
	//CMyPanel : This Class / vgui::Frame : BaseClass

	CMyPanel(vgui::VPANEL parent); 	// Constructor
	~CMyPanel(){};				// Destructor

protected:
	//VGUI overrides:
	virtual void OnTick();
	virtual void OnCommand(const char* pcCommand);

private:
	//Other used VGUI control Elements:

};

El constructor: El argumento es vgui::VPANEL parent. Después de leer la VGUI Documentation, deberias saber que todo panel tiene un padre y porque lo tiene.

Bajo el codigo de arriba, añade:

// Constuctor: Initializes the Panel
CMyPanel::CMyPanel(vgui::VPANEL parent)
: BaseClass(NULL, "MyPanel")
{
	SetParent( parent );
	
	SetKeyBoardInputEnabled( true );
	SetMouseInputEnabled( true );
	
	SetProportional( true );
	SetTitleBarVisible( true );
	SetMinimizeButtonVisible( false );
	SetMaximizeButtonVisible( false );
	SetCloseButtonVisible( false );
	SetSizeable( false );
	SetMoveable( false );
	SetVisible( true );


	SetScheme(vgui::scheme()->LoadSchemeFromFile("resource/SourceScheme.res", "SourceScheme"));

	LoadControlSettings("resource/UI/MyPanel.res");

	vgui::ivgui()->AddTickSignal( GetVPanel(), 100 );
	
	DevMsg("MyPanel has been constructed\n");
}

Las primeras lineas son bastante sencillas de entender. SetScheme es usada para establecer el la fuente del esquema, que es el esquema estándart para Half-Life 2. Conseguimos un puntero al esquema llamando a LoadSchemeFromFile(...). La función LoadControlSettings es usada para cargar el archivo de configuraciones de control de resolución. La última línea esta explicada en la codumentación VGUI2.

Siguiendo al codigo expuesto arriba, añade:

//Class: CMyPanelInterface Class. Used for construction.
class CMyPanelInterface : public IMyPanel
{
private:
	CMyPanel *MyPanel;
public:
	CMyPanelInterface()
	{
		MyPanel = NULL;
	}
	void Create(vgui::VPANEL parent)
	{
		MyPanel = new CMyPanel(parent);
	}
	void Destroy()
	{
		if (MyPanel)
		{
			MyPanel->SetParent( (vgui::Panel *)NULL);
			delete MyPanel;
		}
	}
};
static CMyPanelInterface g_MyPanel;
IMyPanel* mypanel = (IMyPanel*)&g_MyPanel;

A continuación puedes crear IMyPanel.h en el mismo directorio.

IMyPanel.h


// IMyPanel.h
class IMyPanel
{
public:
	virtual void		Create( vgui::VPANEL parent ) = 0;
	virtual void		Destroy( void ) = 0;
};

extern IMyPanel* mypanel;

Calling the panel

Para llamar al panel, añadimos unas pocas lineas en el archivo vgui_int.cpp. Vgui_int.cpp incluye funciones que llaman a todos los paneles. La función VGui_CreateGlobalPanels() es donde la adición de los paneles tiene lugar.

This is the point, where you have to decide when the panel should show up. Either you create a panel that can be accessed during the game, or you create a panel for the main menu.

I assume that you want to create a panel for the game.

So, after including the panel, you should add

mypanel->Create(gameParent);

and check to see if gameParent has been declared at the top of the function, if it hasn't then add

VPANEL gameParent = enginevgui->GetPanel( PANEL_CLIENTDLL );

Note: To have your screen appear in-game like the Counter-Strike buy menus or team selection menus, change PANEL_CLIENTDLL to PANEL_INGAMESCREENS , otherwise it will be visible only when you press Escape to go to the game menu.

Then add

mypanel->Destroy();


to the VGui_Shutdown() function.

If you plan to create a panel for the main menu, you need to put this into the construction function (VGui_CreateGlobalPanels()):

VPANEL GameUiDll = enginevgui->GetPanel( PANEL_GAMEUIDLL);
mypanel->Create(GameUiDll);

This will cause the panel to appear when you start your mod.

The control settings

Everything is working, so start the game, and check if you see your panel. Now you have the chance to press CTRL+ALT+SHIFT+B in order to use the VGUI2 Builder. You can drag around the panel and set some properties as well as adding some elements. Do not forget to save your work afterwards.

Adding elements

There are two ways to add new elements. The one way is to use the VGUI2 Builder. Since the VGUI2 Builder doesn’t come with all the essential elements, you should add elements in your code. Therefore, you have the choice in-between 50 elements, individually stored in the vgui_controls folder. Indeed, even this is pretty easy. You add a pointer into the class declaration. Here is an example:

vgui::TextEntry* m_pTime; // Panel class declaration, private section

Add this to the panels constructor:

m_pTime = new vgui::TextEntry(this, "MyTextEntry");
m_pTime->SetPos(15, 310);
m_pTime->SetSize(50, 20);

You'll also have to add the following include to get the constructors for TextEntry:

#include <vgui_controls/TextEntry.h>

Other stuff

Let's do some console stuff. For example, we could need a variable which allows us to set the state of our panel.
Here is an example:

MyPanel.cpp

Underneath all of the other code, add:

ConVar cl_showmypanel("cl_showmypanel", "1", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

This code doesn’t need some explanation, so we continue by adding a method to our class:

void CMyPanel::OnTick()
{
	BaseClass::OnTick();
	SetVisible(cl_showmypanel.GetBool()); //CL_SHOWMYPANEL / 1 BY DEFAULT
}

A command to toggle the panel on or off:

CON_COMMAND(ToggleMyPanel, "Toggles myPanel on or off")
{
	cl_showmypanel.SetValue(!cl_showmypanel.GetBool());
};

Interactive Elements

In the last part of this tutorial we will add some functionality to a button.

void CMyPanel::OnCommand(const char* pcCommand)
{
	if(!Q_stricmp(pcCommand, "turnoff"))
		cl_showmypanel.SetValue(0);
}

You can add a button (using the built-in editor) and set the command value of the button to "turnoff". If the player clicks this button, well, the panel disappers.

Main Menu

To link to your new panel from the main menu, open up GameMenu.res in your /resource/ folder. Add:

	"5"
	{
		"label" "My Panel"
		"command" "engine ToggleMyPanel"
		"notmulti" "1"
	}

And change ConVar cl_showmypanel("cl_showmypanel", "1", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

To: ConVar cl_showmypanel("cl_showmypanel", "0", FCVAR_CLIENTDLL, "Sets the state of myPanel <state>");

So that it won't pop up before the user clicks it.

You may also want to add mypanel->Activate(); underneath cl_showmypanel.SetValue(!cl_showmypanel.GetBool());. This will focus on your panel. To be able to use the Activate() command, you will need to add:

	void Activate( void )
	{
		if ( MyPanel )
		{
			MyPanel->Activate();
		}
	}

Underneath:

	void Destroy( void )
	{
		if ( MyPanel )
		{
			MyPanel->SetParent( (vgui::Panel *)NULL );
			delete MyPanel;
		}
	}

In MyPanel.cpp.

And add:

virtual void		Activate( void ) = 0;

Underneath:

virtual void		Destroy( void ) = 0;

In IMyPanel.h.

If you want the user to be able to close your panel without having to click the My Panel menu option, add a Button with the command "turnoff" to your panel.

See also