Ru/Understanding VGUI2 Resource Files: Difference between revisions

From Valve Developer Community
< Ru
Jump to navigation Jump to search
(Created page with "{{otherlang2 |title=Устройство файлов ресурсов в VGUI2 |en=Understanding_VGUI2_Resource_Files }} = Введение = Я стал свидетелем...")
 
No edit summary
Line 25: Line 25:


=== Изменение элементов управления, сгенерированных файлом ресурсов, в коде ===
=== Изменение элементов управления, сгенерированных файлом ресурсов, в коде ===
Let's say you've made your own panel and put some ImagePanels in the resource file. If you wish to modify an automatically generated control, you only need to do a few things:
Допустим, вы создали свою собственную панель и поместили несколько ImagePanels в файл ресурсов. Если вы хотите изменить автоматически созданный элемент управления, вам нужно сделать только несколько вещей:
* Create a pointer for the control in your header file:
* Создайте указатель для элемента управления в файле заголовка:
<source lang="cpp">
<source lang="cpp">
vgui::ImagePanel* m_pTestImage;
vgui::ImagePanel* m_pTestImage;
</source>
</source>
* Populate the control in your constructor:
* Заполните элемент управления в своем конструкторе:
<source lang="cpp">
<source lang="cpp">
m_pTestImage = dynamic_cast<ImagePanel*>( FindChildByName( "NameOfPanelInResourceFile", true ) );
m_pTestImage = dynamic_cast<ImagePanel*>( FindChildByName( "NameOfPanelInResourceFile", true ) );
</source>
</source>
If you're using Source SDK 2013, you can use the shorter template method instead:
Если вы используете Source SDK 2013, вы можете вместо этого использовать более короткий метод шаблона.:
<source lang="cpp">
<source lang="cpp">
m_pTestImage = FindControl<ImagePanel>( "NameOfPanelInResourceFile", true );
m_pTestImage = FindControl<ImagePanel>( "NameOfPanelInResourceFile", true );
</source>
</source>
{{Warning|Make sure you call this line '''after''' you've loaded the resource file, or you'll always get a NULL pointer back!}}
{{Warning|Убедитесь, что вы вызываете эту строку '''после''' загрузки файла ресурсов, иначе вы всегда получите обратно NULL-указатель!}}
* Done! You can now access the ImagePanel (don't forget to check for null pointers!)
* Готово! Теперь вы можете получить доступ к ImagePanel (не забудьте проверить нулевые указатели!)


Don't worry about having to clean up the auto-generated panels; they do that themselves.
Не беспокойтесь о необходимости очистки автоматически созданных панелей; они делают это сами.


== When creating a new type of control ==
== При создании нового типа контроля ==
=== Factory ===
=== Завод (с утра на него) ===
The system needs to know which controls can be built using a factory method. This is necessary to automatically create controls when reading a resource file. It uses the following macro for this:
Системе необходимо знать, какие элементы управления можно создать с использованием заводского метода. Это необходимо для автоматического создания элементов управления при чтении файла ресурсов. Для этого используется следующий макрос:
<source lang="cpp">
<source lang="cpp">
DECLARE_BUILD_FACTORY( Label );
DECLARE_BUILD_FACTORY( Label );
Line 60: Line 60:
</source>
</source>


If you want to pass other parameters, or you have non-nullable parameters that require a default value, you can use '''DECLARE_BUILD_FACTORY_CUSTOM''':
Если вы хотите передать другие параметры или у вас есть параметры, не допускающие значения NULL, для которых требуется значение по умолчанию, вы можете использовать '''DECLARE_BUILD_FACTORY_CUSTOM''':


<source lang="cpp">
<source lang="cpp">
Line 71: Line 71:
}
}


// Takes the class name and the method name. Ensure that the method is defined before this line!
// Принимает имя класса и имя метода. Убедитесь, что метод определен перед этой строкой!
DECLARE_BUILD_FACTORY_CUSTOM( ComboBoxNew, ComboBoxNew_Factory );
DECLARE_BUILD_FACTORY_CUSTOM( ComboBoxNew, ComboBoxNew_Factory );
</source>
</source>


=== Applying Settings ===
=== Применение настроек ===
The method '''ApplySettings( KeyValues* inResourceData )''' is what does the heavy lifting when laying out your control. Because of the hierarchical structure of the controls (A inherits from B, B inherits from C, etc), it is very easy to create a new control whose particular settings can be data-driven (that is, initialized from the resource file). Here is an example:
Метод '''ApplySettings( KeyValues* inResourceData )''' это то, что делает тяжелый подъем при выкладывании вашего контроля. Из-за иерархической структуры элементов управления (A наследуется от B, B наследуется от C и т. Д.) Очень легко создать новый элемент управления, конкретные настройки которого могут управляться данными (то есть инициализироваться из файла ресурсов). Вот пример:


Say your control, '''ImagePanelBetter''', inherits from '''ImagePanel'''. You would then override the virtual '''ApplySettings()''' function and read things for your control:
Скажите, что ваш элемент управления, '' 'ImagePanelBetter' '', наследуется от '' 'ImagePanel' ''. Затем вы переопределите виртуальную функцию '' 'ApplySettings ()' '' и прочтите что-нибудь для своего контроля:
<source lang="cpp">
<source lang="cpp">
void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
Line 104: Line 104:
</source>
</source>


Pretty simple, no?
Довольно просто, не так ли?


Because resource files are simply KeyValues, you can also nest items:
Поскольку файлы ресурсов представляют собой просто KeyValues, вы также можете вкладывать элементы:
<source lang="cpp">
<source lang="cpp">
void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
Line 120: Line 120:
</source>
</source>


= Hierarchical overview of keys in resource files =
= Иерархический обзор ключей в файлах ресурсов =
This is an overview of which keys are defined where in code and what their function is.
Это обзор того, какие ключи определены в коде и каковы их функции.
== Panel ==
== Панель ==
'''Description:''' A simple control that is the basis for all other VGUI controls. Contains many overrideable functions.
'''Description:''' Простой элемент управления, который является основой для всех других элементов управления VGUI. Содержит множество переопределяемых функций.


'''Inherits from:''' ''None''
'''Inherits from:''' ''None''


* '''fieldName:''' Determines the name of the control.
* '''fieldName:''' Определяет имя элемента управления.
* '''xpos:''' Determines the horizontal offset from the top left (by default) of the parent panel.
* '''xpos:''' Определяет горизонтальное смещение от верхнего левого угла (по умолчанию) родительской панели.
* '''ypos;''' Determines the vertical offset from the top left (by default) of the parent panel.
* '''ypos;''' Определяет вертикальное смещение от верхнего левого угла (по умолчанию) родительской панели.
* '''wide:''' Determines the width of the control.
* '''wide:''' Определяет ширину элемента управления.
* '''tall:''' Determines the height of the control.
* '''tall:''' Определяет высоту элемента управления.
{{Tip|You can [[VGUI_Position_and_Size_Flags|apply an offset to these four position/size variables by using a position or size flag.]]}}
{{Tip|Вы можете [[VGUI_Position_and_Size_Flags|применить смещение к этим четырем переменным положения / размера с помощью флага положения или размера.]]}}
* '''zpos:''' Determines the depth of the panel. Deeper panels are drawn first. Lower numbers = deeper.
* '''zpos:''' Определяет глубину панели. Сначала рисуются более глубокие панели. Меньшие числа = глубже.
* '''visible:''' Determines if the control will be drawn.
* '''visible:''' Определяет, будет ли отображаться элемент управления.
{{Tip|Any controls that have this control as a parent will also be hidden/shown.}}
{{Tip|Любые элементы управления, у которых этот элемент управления является родительским, также будут скрыты / показаны.}}
* '''enabled:''' Determines if the control is enabled. Used by controls higher up the chain (like Buttons).
* '''enabled:''' Определяет, включен ли элемент управления. Используется элементами управления выше по цепочке (например, кнопками).
* '''tabPosition:''' Determines the tab order of the control.
* '''tabPosition:''' Определяет порядок табуляции элемента управления.
* '''tooltiptext:''' Determines the tooltip text to show when you hover over this control.
* '''tooltiptext:''' Определяет текст всплывающей подсказки, отображаемый при наведении курсора на этот элемент управления.
* '''paintbackground:''' Paint the background color of this control?
* '''paintbackground:''' Нарисуйте цвет фона этого элемента управления?
* '''paintborder:''' Paint the border of this control?


There are also a number of '''overridable colors''' defined in several controls. '''Panel''' checks the ones of itself and its children and has the following defined:
Есть также ряд '''переопределяемых цветов''', определенных в нескольких элементах управления. '''Panel''' проверяет себя и своих дочерних элементов и имеет следующие определения:
* '''fgcolor_override:''' Overrides the color of the foreground (for Labels, this is the text color).
* '''fgcolor_override:''' Переопределяет цвет переднего плана (для надписей это цвет текста).
* '''bgcolor_override:''' Overrides the color of the background.
* '''bgcolor_override:''' Переопределяет цвет фона.
{{Tip|Write color values as follows: "R G B A" or "ColorNameInScheme". Example: "fgcolor_override" "255 0 0 255" or "fgcolor_override" "My.Custom.Color"}}
{{Tip|Запишите значения цвета следующим образом: "R G B A" or "ColorNameInScheme". Пример: "fgcolor_override" "255 0 0 255" or "fgcolor_override" "My.Custom.Color"}}


== Label ==
== Label ==
'''Description:''' A control that can display (wrapped) text.
'''Описание:''' Элемент управления, который может отображать (переносить) текст.


'''Inherits from:''' ''Panel''
'''Наследуется от:''' ''Panel''


* '''labelText:''' Determines the text that the label will display.
* '''labelText:''' Определяет текст, который будет отображаться на метке.
{{Tip|Putting text between a percentage sign will make it a localized variable. For example, the string '''%test%''' will create a localized string '''#var_test'''. See [[VGUI_Documentation#Localization|VGUI Localization]] for more info on localized strings.}}
{{Tip|Putting text between a percentage sign will make it a localized variable. For example, the string '''%test%''' will create a localized string '''#var_test'''. See [[VGUI_Documentation#Localization|VGUI Localization]] for more info on localized strings.}}
{{Tip|You can also just assign a non-changing localized string by adding the control sign, '''#''', in front of a string: '''#test''' will get looked up in the list of tokens, and the localized text will be displayed in its place.}}
{{Tip|You can also just assign a non-changing localized string by adding the control sign, '''#''', in front of a string: '''#test''' will get looked up in the list of tokens, and the localized text will be displayed in its place.}}

Revision as of 15:38, 18 August 2020

Template:Otherlang2

Введение

Я стал свидетелем большого замешательства, когда спросил других программистов, как система VGUI2 взаимодействует с файлами ресурсов, и я не нашел полной справки по их использованию, так что вот.

Что они делают

Файлы ресурсов используются для автоматического создания элементов управления (= панелей), которые можно поместить в родительский элемент управления. Таким образом, сделать макет панели намного проще. Следовательно, файлы ресурсов очень удобны, когда вы создаете собственную внутриигровую панель и хотите, чтобы тяжелый подъем макета выполнялся автоматически.

Note.pngПримечание:Файлы ресурсов не имеют ничего общего с (автоматическим) созданием новых «типов» элементов управления: они просто дайджест того, какие элементы управления размещаются, где и как они инициализируются.

Дизайн

Файлы ресурсов представляют собой простые KeyValues, которые анализируются сверху вниз: каждый элемент управления, указанный в файле, создается с помощью фабрики элементов управления, и его настройки применяются в иерархическом порядке..

При создании новой внутриигровой панели

Загрузка .res файла

Чтобы загрузить файл ресурсов для панели, просто добавьте в конструктор следующее:

LoadControlSettings( "Path/To/Resource/File.res" );

Настройка управления в игре

Смотрите The VGUI Build Mode чтобы получить больше информации.

Изменение элементов управления, сгенерированных файлом ресурсов, в коде

Допустим, вы создали свою собственную панель и поместили несколько ImagePanels в файл ресурсов. Если вы хотите изменить автоматически созданный элемент управления, вам нужно сделать только несколько вещей:

  • Создайте указатель для элемента управления в файле заголовка:
vgui::ImagePanel* m_pTestImage;
  • Заполните элемент управления в своем конструкторе:
m_pTestImage = dynamic_cast<ImagePanel*>( FindChildByName( "NameOfPanelInResourceFile", true ) );

Если вы используете Source SDK 2013, вы можете вместо этого использовать более короткий метод шаблона.:

m_pTestImage = FindControl<ImagePanel>( "NameOfPanelInResourceFile", true );
Warning.pngПредупреждение:Убедитесь, что вы вызываете эту строку после загрузки файла ресурсов, иначе вы всегда получите обратно NULL-указатель!
  • Готово! Теперь вы можете получить доступ к ImagePanel (не забудьте проверить нулевые указатели!)

Не беспокойтесь о необходимости очистки автоматически созданных панелей; они делают это сами.

При создании нового типа контроля

Завод (с утра на него)

Системе необходимо знать, какие элементы управления можно создать с использованием заводского метода. Это необходимо для автоматического создания элементов управления при чтении файла ресурсов. Для этого используется следующий макрос:

DECLARE_BUILD_FACTORY( Label );

This method will attempt to create an instance of the control with a constructor with two parameters, which are both NULL:

#define DECLARE_BUILD_FACTORY( className )										\
	static vgui::Panel *Create_##className##( void )							\
		{																		\
			return new className( NULL, NULL );									\
		};																		\
		static vgui::CBuildFactoryHelper g_##className##_Helper( #className, Create_##className## );\
	className *g_##className##LinkerHack = NULL;

Если вы хотите передать другие параметры или у вас есть параметры, не допускающие значения NULL, для которых требуется значение по умолчанию, вы можете использовать DECLARE_BUILD_FACTORY_CUSTOM:

// Example: ComboBoxNew inherits from ComboBox

// Custom ComboBoxNew method
vgui::Panel *ComboBoxNew_Factory()
{
	return new ComboBoxNew( NULL, NULL, 5, true );
}

// Принимает имя класса и имя метода. Убедитесь, что метод определен перед этой строкой!
DECLARE_BUILD_FACTORY_CUSTOM( ComboBoxNew, ComboBoxNew_Factory );

Применение настроек

Метод ApplySettings( KeyValues* inResourceData ) это то, что делает тяжелый подъем при выкладывании вашего контроля. Из-за иерархической структуры элементов управления (A наследуется от B, B наследуется от C и т. Д.) Очень легко создать новый элемент управления, конкретные настройки которого могут управляться данными (то есть инициализироваться из файла ресурсов). Вот пример:

Скажите, что ваш элемент управления, 'ImagePanelBetter' , наследуется от 'ImagePanel' . Затем вы переопределите виртуальную функцию 'ApplySettings ()' и прочтите что-нибудь для своего контроля:

void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
{
	// VERY IMPORTANT: ALWAYS CALL THE BASE CLASS!
	BaseClass::ApplySettings( inResourceData );

	const char *value = NULL;
	value = inResourceData->GetString("normalImage", "");
	if (*value)
		UpdateNormalImage( value );

	value = inResourceData->GetString("mouseoverImage", "");
	if (*value)
		UpdateMouseOverImage( value );

	value = inResourceData->GetString("mouseclickImage", "");
	if (*value)
		UpdateMouseClickImage( value );

	value = inResourceData->GetString("command", "");
	if (*value)
		UpdateCommand( value );
}

Довольно просто, не так ли?

Поскольку файлы ресурсов представляют собой просто KeyValues, вы также можете вкладывать элементы:

void ImagePanelBetter::ApplySettings(KeyValues *inResourceData)
{
	// VERY IMPORTANT: ALWAYS CALL THE BASE CLASS!
	BaseClass::ApplySettings( inResourceData );

	KeyValues* nestedItem;
	nestedItem = inResourceData->FindKey( "NameOfNestedItemInResourceFile" );
	if (nestedItem )
		DoStuff( nestedItem );
}

Иерархический обзор ключей в файлах ресурсов

Это обзор того, какие ключи определены в коде и каковы их функции.

Панель

Description: Простой элемент управления, который является основой для всех других элементов управления VGUI. Содержит множество переопределяемых функций.

Inherits from: None

  • fieldName: Определяет имя элемента управления.
  • xpos: Определяет горизонтальное смещение от верхнего левого угла (по умолчанию) родительской панели.
  • ypos; Определяет вертикальное смещение от верхнего левого угла (по умолчанию) родительской панели.
  • wide: Определяет ширину элемента управления.
  • tall: Определяет высоту элемента управления.
Tip.pngСовет:Вы можете применить смещение к этим четырем переменным положения / размера с помощью флага положения или размера.
  • zpos: Определяет глубину панели. Сначала рисуются более глубокие панели. Меньшие числа = глубже.
  • visible: Определяет, будет ли отображаться элемент управления.
Tip.pngСовет:Любые элементы управления, у которых этот элемент управления является родительским, также будут скрыты / показаны.
  • enabled: Определяет, включен ли элемент управления. Используется элементами управления выше по цепочке (например, кнопками).
  • tabPosition: Определяет порядок табуляции элемента управления.
  • tooltiptext: Определяет текст всплывающей подсказки, отображаемый при наведении курсора на этот элемент управления.
  • paintbackground: Нарисуйте цвет фона этого элемента управления?

Есть также ряд переопределяемых цветов, определенных в нескольких элементах управления. Panel проверяет себя и своих дочерних элементов и имеет следующие определения:

  • fgcolor_override: Переопределяет цвет переднего плана (для надписей это цвет текста).
  • bgcolor_override: Переопределяет цвет фона.
Tip.pngСовет:Запишите значения цвета следующим образом: "R G B A" or "ColorNameInScheme". Пример: "fgcolor_override" "255 0 0 255" or "fgcolor_override" "My.Custom.Color"

Label

Описание: Элемент управления, который может отображать (переносить) текст.

Наследуется от: Panel

  • labelText: Определяет текст, который будет отображаться на метке.
Tip.pngСовет:Putting text between a percentage sign will make it a localized variable. For example, the string %test% will create a localized string #var_test. See VGUI Localization for more info on localized strings.
Tip.pngСовет:You can also just assign a non-changing localized string by adding the control sign, #, in front of a string: #test will get looked up in the list of tokens, and the localized text will be displayed in its place.
  • textAlignment: Determines the alignment of the label.
Tip.pngСовет:Valid values are north-west, north, north-east, west, center, east, south-west, south and south-east.
  • associate: Allows the label to be associated with another control.
    Нужно сделать: See what uses this has.
  • dulltext: A boolean that determines if text should be displayed in a dull manner.
  • brighttext: A boolean that determines if text should be displayed in a bright manner.
Tip.pngСовет:You can only have one of these two active. The one that is defined first is chosen.
  • font: Determines the font used by the label. Use the font name as defined in the SourceScheme.res file.
  • wrap: Determines if your label wraps around the available space.
  • centerwrap: Same as above, except it also works for centered text.
  • textinsetx: Additional horizontal offset space from whichever side it is aligned.
  • textinsety: Additional vertical offset space from whichever side it is aligned.

Button

Description: A control that can display (wrapped) text and act as a button.

Inherits from: Label

  • command: Determines which command to fire to the OnCommand handler when pressed.
  • default: A boolean that determines if this button is to be activated when the user presses the enter or space bar keys. Only one such button can exist.
  • selected: A boolean that determines if this button appears to have been selected.
  • sound_armed: Determines what sound the button makes when hovered over.
  • sound_depressed: Determines what sound the button makes when pressed upon.
  • sound_released: Determines what sound the button makes when released.

ImagePanel

Description: Essentially an image.

Inherits from: Panel

  • scaleImage: A boolean that determines whether to scale the image to its specified width and height.
  • scaleAmount: A float that determines how much the image should scale.
  • tileImage: A boolean that determines whether to tile the image.
  • tileHorizontally: A boolean that determines whether to tile the image horizontally.
  • tileVertically: A boolean that determines whether to tile the image vertically.
  • image: The actual image. Expects a path to a .VMT file in the /materials/vgui folder.
Tip.pngСовет:Example: Say that your .VMT file is called example1.vmt and is located in /materials/vgui/examples, then the path you should put here would be examples/example1.
Tip.pngСовет:Confirmed on Windows machine - You can go up a folder by including ../ in your file path. For example, to access example.vmt in /materials/images, use ../images/example as your path.
  • fillcolor: Determines the background color behind the image. Only painted if the alpha is higher than 0 (duh)
Tip.pngСовет:You can specify a color in both RGBA format or refer to a color in the scheme files by just putting its name as the value.
  • border: Determines the border around the image. You can only refer to colors defined in the scheme files here using the names of the colors!

EditablePanel

Description: A window-like control that can house other controls, which can be edited using the VGUI Build Mode.

Inherits from: Panel

Frame

Description: A dynamically resizeable control that can be dragged around. Has a title bar, close and minimization buttons, etc.

Inherits from: EditablePanel

Note.pngПримечание:the Frame control overrides the "visible" key defined in Panel.
  • title: Determines the title of the frame.
  • title_font: Determines what font the title of the frame will use.
  • clientinsetx_override: Overrides the default horizontal offset from the left side of the panel.

Color overrides:

  • infocus_bgcolor_override: Override for the background color of the panel when it is in focus.
  • outoffocus_bgcolor_override: Override for the background color of the panel when it is out of focus.
  • titlebarbgcolor_override: Override for the background color of the title bar when it is in focus.
  • titlebardisabledbgcolor_override: Override for the background color of the title bar when it is out of focus.
  • titlebarfgcolor_override: Override for the foreground color of the title bar when it is in focus.
  • titlebardisabledfgcolor_override: Override for the foreground color of the title bar when it is out of focus.
Нужно сделать: Not done yet!