Es/Server plugins: Difference between revisions

From Valve Developer Community
< Es
Jump to navigation Jump to search
No edit summary
 
m (obsolete language category)
 
(22 intermediate revisions by 9 users not shown)
Line 1: Line 1:
The Source engine comes with a built in 3rd party plugin API similar to the API provided by MetaMod under the HL1 engine. This document provides a brief description of the interfaces provided and how to best use them.
{{LanguageBar}}


=Needed includes for a compile=


In order to compile your plugin you need to set up your compiler to include the following directories:
{{finishtranslation}}
El Source Engine implementa un 3rd party plugin API similar a la API proporcionada por MetaMod bajo el motor del HL1. Este documento proporciona una breve descripción del interfaz proporcionado y como usarlo de la mejor manera.
 
=Includes necesarios para compilar=
 
De cara a compilar tu plugin necesitarás configurar tu compilador para incluir los siguientes directorios:
<pre>
<pre>
  * public
  * public
Line 13: Line 17:
  * tier1  
  * tier1  
</pre>
</pre>
In order to do this you must get the SDK's files by creating a mod in Source SDK.
Para hacer esto debes conseguir los archivos SDK creando un MOD en el Source SDK.


=Compiling the Sample=
=Compilando el Sample=


The SDK contains a sample plugin that exercises the various capabilities available in a plugin. You can find the sample in <code>src/utils/serverplugin_sample</code>. Under Windows load the <code>serverplugin_empty.vcproj</code> project, under linux you can type:
El SDK contiene un plugin de muestra que ejerce varias de las capacidades disponibles en un plugin. Puedes encontrar una muestra en <code>src/utils/serverplugin_sample</code>. Bajo Windows carga el proyecto <code>serverplugin_empty.vcproj</code>, bajo Linux, puedes typear:
<pre>
<pre>
make plugin
make plugin
</pre>
</pre>


from the <code>linux_sdk</code> directory.
desde el directorio <code>linux_sdk</code>.


=Running a Plugin=
=Ejecutando el Plugin=


The engine will load plugins based upon specially formatted key value files put in the <code><mod dir>/addons/</code> folder (you may have to create this directory, a default server install doesn't come with one). To load your plugin place a file in this folder with the extension vdf and with the following format:
El motor cargará los plugins basados en archivos de valores clave en formato especial localizado en la carpeta <code><mod dir>/addons/</code> (debes crear este directorio, un servidor, por defecto, no viene con el). Para cargar tu plugin coloca un archivo en esta carpeta con la extensión *.vdf y con el siguiente formato:
<pre>
<pre>
"Plugin"
"Plugin"
Line 33: Line 37:
}
}
</pre>
</pre>
The <code>"file"</code> parameter should point to the file to load. In this example the binary created after you compiled the code should be copied to the <code>bin/</code> folder of the server install. The file extension (.dll for Windows) is added automatically to the filename when it is loaded. The file name should be relative to the base bin/ folder on the server (i.e you would use <code>../cstrike/addons/serverplugin_empty</code> to specify a file in the cstrike addons folder).
El parámetro <code>"file"</code> debería apuntar al archivo a cargar. En este ejemplo, el binario creado después de compilar el código debería ser copiado a la carpeta <code>bin/</code> del servidor instalado. La extensión del archivo (.dll para Windows) es añadida automaticamente al nombre de archivo cuando es cargado. El nombre del archivo debería ser relativo a la carpeta base bin/ en el servidor (i.e usarías <code>../cstrike/addons/serverplugin_empty</code> para especificar un archivo en la carpeta de addons del cstrike).


{{note|For the TF2 Linux server the file extension (.so) needs to be added.}}
{{note|Para servidores TF2 Linux el la extension de archivo (.so) necesita ser añadida.}}


{{note|"file" defines the type of plugin to load, i.e. it tells the [[Source Engine]] it is a file; "serverplugin_empty" is the path to the file.}}
{{note|"file" define el tipo de plugin a cargar, i.e. le dice al {{L|Source Engine}} que es un archivo; "serverplugin_empty" es la ruta al archivo.}}
'''Example:'''
'''Ejemplo:'''


  "Plugin"
  "Plugin"
Line 45: Line 49:
  }
  }


==Simplified Version==
==Versión Simplificada==
*Put the compiled file inside of your <game dir>/bin folder (.dll file for windows)
*Coloca el archivo compilado dentro de tu directorio <game dir>/bin (archivo .dll para Windows)
*make a file exactly like the top example, and change "serverplugin_empty" to your file's name (keeping the quotes)
*crea el archivo exactamente como en el ejemplo de arriba, y cambia "serverplugin_empty" por tu nombre de archivo (mantén las comillas)
{{note|To make a .vdf file, just make a text file, right click it and change .txt to .vdf}}
{{note|Para crear un archivo .vdf, solo crea un archivo de texto, botón derecho y cambia la extensión de .txt a .vdf}}


=The IServerPlugin interface=
=La interfaz IServerPlugin=


Plugins work by exposing an <code>IServerPluginCallbacks</code> interface to the engine. The engine calls back into this interface when various events happen. The definition of this interface can be found in <code>public/engine/iserverplugin.h</code>. The <code>PLUGIN_RESULT</code> return type of some of the functions allows the plugin to control whether this call is passed onto the underlying mod or not, see the header file for details.
Los plugins trabajan exponiendo una interfaz <code>IServerPluginCallbacks</code> al motor. El motor devuelve la llamada a esta interfaz cuando suceden varios eventos. La definición de esta interfaz puede ser encontrada en <code>public/engine/iserverplugin.h</code>. El tipo de retorno <code> PLUGIN_RESULT </code> de algunas de las funciones permite que el plugin controle si es pasada esta llamada al mod subyacente o no, vea la cabecera para más detalles.


=IServerPluginCallbacks explained=
=Explicación de IServerPluginCallbacks=
{|
{| class=standard-table
| <code>Load</code> || This function is called when the plugin is loaded by the engine. This can happen either on initialization or when being re-loaded after being unloaded. The two parameters provide the interface factories that the plugin needs to operate.
| <code>Load</code> || Esta función es llamada cuando el plugin es cargado por el motor. Esto puede suceder en la inicialización o cuando se recarga después de ser descargado. Los dos parametros proporcionan la factoria de interfaz que el plugin necesita para operar.
|-
|-
| <code>UnLoad</code> || Called when a plugin is unloaded, use this to disable any asynchronous tasks and remove any callbacks you have registered with the engine (for example a game events listener).
| <code>UnLoad</code> || Llamada cuando un plugin es descargado, usa esto para desactivar cualquier tarea asincrónica y eliminar cualquier callbacks que hayas registrado con el motor (Por ejemplo un listener de eventos de juego).{{Note|Entiendo por listener una "función" o proceso subyacente que permanece a la espera de cualquier evento para capturarlo NdT.}}
|-
|-
| <code>Pause</code> || Called when the operation of the plugin is paused (i.e it will stop receiving callbacks but should not be unloaded).
| <code>Pause</code> || Called when the operation of the plugin is paused (i.e it will stop receiving callbacks but should not be unloaded).
Line 100: Line 104:
* <code><mod dir>/resource/ModEvents.res</code>
* <code><mod dir>/resource/ModEvents.res</code>


=Creating [[ConVar]]s and [[Command]]s=
=Creating {{L|ConVar}}s and {{L|Command}}s=


[[ConVar]]s let you specify variables that users can use to configure the behavior of your plugin. [[ConCommand]]s allow the creation of commands that your plugin provides. Creating both is easy and self contained, the code snippet below creates a new command <code>empty_version</code> and a new variable <code>plugin_empty</code>. These commands can be run from the server or client, you should use the index provided by <code>SetCommandClient</code> to determine the source of the command.
{{L|ConVar}}s let you specify variables that users can use to configure the behavior of your plugin. {{L|ConCommand}}s allow the creation of commands that your plugin provides. Creating both is easy and self contained, the code snippet below creates a new command <code>empty_version</code> and a new variable <code>plugin_empty</code>. These commands can be run from the server or client, you should use the index provided by <code>SetCommandClient</code> to determine the source of the command.
<pre>
<pre>
CON_COMMAND( empty_version, "prints the version of the empty plugin" )
CON_COMMAND( empty_version, "prints the version of the empty plugin" )
Line 145: Line 149:
</pre>
</pre>


{{otherlang:es}}
{{ACategory|Programming}}
{{otherlang:es:en|Server Plugins}}
 
[[Category:Programming]]

Latest revision as of 03:29, 22 August 2024

English (en)Deutsch (de)Español (es)Русский (ru)Translate (Translate)


Info content.png
This page has not been fully translated.
You can help by finishing the translation.
If this page cannot be translated for some reason, or is left untranslated for an extended period of time after this notice is posted, the page should be requested to be deleted.
Also, please make sure the article complies with the alternate languages guide.(en)

El Source Engine implementa un 3rd party plugin API similar a la API proporcionada por MetaMod bajo el motor del HL1. Este documento proporciona una breve descripción del interfaz proporcionado y como usarlo de la mejor manera.

Includes necesarios para compilar

De cara a compilar tu plugin necesitarás configurar tu compilador para incluir los siguientes directorios:

 * public
 * public/dlls
 * public/engine
 * public/tier0
 * public/tier1
 * public/vstdlib
 * tier1 

Para hacer esto debes conseguir los archivos SDK creando un MOD en el Source SDK.

Compilando el Sample

El SDK contiene un plugin de muestra que ejerce varias de las capacidades disponibles en un plugin. Puedes encontrar una muestra en src/utils/serverplugin_sample. Bajo Windows carga el proyecto serverplugin_empty.vcproj, bajo Linux, puedes typear:

make plugin

desde el directorio linux_sdk.

Ejecutando el Plugin

El motor cargará los plugins basados en archivos de valores clave en formato especial localizado en la carpeta <mod dir>/addons/ (debes crear este directorio, un servidor, por defecto, no viene con el). Para cargar tu plugin coloca un archivo en esta carpeta con la extensión *.vdf y con el siguiente formato:

"Plugin"
{
        "file"  "serverplugin_empty"
}

El parámetro "file" debería apuntar al archivo a cargar. En este ejemplo, el binario creado después de compilar el código debería ser copiado a la carpeta bin/ del servidor instalado. La extensión del archivo (.dll para Windows) es añadida automaticamente al nombre de archivo cuando es cargado. El nombre del archivo debería ser relativo a la carpeta base bin/ en el servidor (i.e usarías ../cstrike/addons/serverplugin_empty para especificar un archivo en la carpeta de addons del cstrike).

Note.pngNota:Para servidores TF2 Linux el la extension de archivo (.so) necesita ser añadida.
Note.pngNota:"file" define el tipo de plugin a cargar, i.e. le dice al Source Engine(en) que es un archivo; "serverplugin_empty" es la ruta al archivo.

Ejemplo:

"Plugin"
{
        "file"  "../cstrike/addons/serverplugin_empty"
}

Versión Simplificada

  • Coloca el archivo compilado dentro de tu directorio <game dir>/bin (archivo .dll para Windows)
  • crea el archivo exactamente como en el ejemplo de arriba, y cambia "serverplugin_empty" por tu nombre de archivo (mantén las comillas)
Note.pngNota:Para crear un archivo .vdf, solo crea un archivo de texto, botón derecho y cambia la extensión de .txt a .vdf

La interfaz IServerPlugin

Los plugins trabajan exponiendo una interfaz IServerPluginCallbacks al motor. El motor devuelve la llamada a esta interfaz cuando suceden varios eventos. La definición de esta interfaz puede ser encontrada en public/engine/iserverplugin.h. El tipo de retorno PLUGIN_RESULT de algunas de las funciones permite que el plugin controle si es pasada esta llamada al mod subyacente o no, vea la cabecera para más detalles.

Explicación de IServerPluginCallbacks

Load Esta función es llamada cuando el plugin es cargado por el motor. Esto puede suceder en la inicialización o cuando se recarga después de ser descargado. Los dos parametros proporcionan la factoria de interfaz que el plugin necesita para operar.
UnLoad Llamada cuando un plugin es descargado, usa esto para desactivar cualquier tarea asincrónica y eliminar cualquier callbacks que hayas registrado con el motor (Por ejemplo un listener de eventos de juego).
Note.pngNota:Entiendo por listener una "función" o proceso subyacente que permanece a la espera de cualquier evento para capturarlo NdT.
Pause Called when the operation of the plugin is paused (i.e it will stop receiving callbacks but should not be unloaded).
UnPause Called when a plugin is brought out of the paused state. You should re-enable any asynchronous events your plugin uses in this call
GetPluginDescription This function should return a friendly string describing your plugin. Typically this would be its name and the author.
LevelInit Called on level (map) startup, it is the first function called as a server enters a new level.
ServerActivate This is called when the server successfully enters a new level, this will happen after the LevelInit call. This call provides pointers to the list of edicts created on the server and the maxplayer count of the server.
GameFrame Called once per server frame (typically 60 times a second). Server performance is very sensitive to the execution time of this function so keep anything you do in this function to a minimum.
LevelShutdown Called when a server is changing to a new level or is being shutdown. Remove any map specific allocations in this call. This can be called multiple times during a map change.
ClientConnect Called when a client initially connects to a server. Set bAllowConnect to false to stop this user from connecting.
ClientPutInServer Called when a client spawns into a server. This is called before the server spawn function.
ClientActive Called after a client is fully spawned and configured by the Mod. Use this call to change any player specific settings.
ClientDisconnect Called when a client disconnects from the server.
SetCommandClient Called by the ConVar code to let you keep track of which client is entering a ConCommand. Use this index in ConCommands if you want to see who is running the command. As ConVar commands don't have an edict associated with them when they run you can use this index to look up the entity that is running the command. The index is one less than the entity index.
ClientSettingsChanged

Called when player specific cvars about a player change (for example the users name). Use this function to control what operations a user is allowed to perform to their settings (for example limiting usernames).

ClientCommand Called when a remote client enters a command into the console. This should be used to provide commands to clients (and ConCommand used to implement server side only commands).
NetworkIDValidated Called when the server retrieves a clients network ID (i.e Steam ID). Note that a clients network ID is not set on connect, you must wait for this callback before a users network ID is valid. The client name is passed into this function, you need to search the currently connected players to find the associated edict pointer. Note that the clients name can change between connect and id validation, you should use the entity index to track specific players. Note also that this function is NOT called for the local user when running a listen/non-dedicated server.

Listening to Events

The IGameEventManager2 (IGameEventManager was used previously) interface allows a plugin to listen to game events. Game events are fired by a Mod when things of interest happen, like a player dying or the bomb being planted. IGameEventManager2::AddListener should be called to subscribe to particular game events. It must be called for each event that your listener wishes to be aware of. FireGameEvent is then called in your plugin when an one of the listened for events happen. The data contained in each event is described by event configuration files, in particular:

  • hl2/resource/serverevents.res
  • hl2/resource/GameEvents.res
  • <mod dir>/resource/ModEvents.res

Creating ConVar(en)s and Command(en)s

ConVar(en)s let you specify variables that users can use to configure the behavior of your plugin. ConCommand(en)s allow the creation of commands that your plugin provides. Creating both is easy and self contained, the code snippet below creates a new command empty_version and a new variable plugin_empty. These commands can be run from the server or client, you should use the index provided by SetCommandClient to determine the source of the command.

CON_COMMAND( empty_version, "prints the version of the empty plugin" )
{
        Msg( "Version:1.0.0.0\n" );
}

static ConVar empty_cvar("plugin_empty", "0", 0, "Example plugin cvar");

Interacting with Clients

The engine provides the IServerPluginHelpers interface to allow plugins to message clients. This interface provides a single function, CreateMessage that is called with 3 different dialog options to message users in different ways.

  1. DIALOG_MSG, this prints a simple message to a client.
  2. DIALOG_MENU, this provides a client with a menu of options.
  3. DIALOG_TEXT, this shows a user a larger text field.

Examples of how to use this interface are shown in the sample plugin example. Each message will be displayed for 10 seconds in the HUD and for the menu and text option for up to 200 seconds in GameUI. Only 1 message can be displayed at a time, you have to wait for the current one to expire before a new one can be shown. Messages with a lower "level" field can be used to override current messages (the minimum level value is 0). Details of valid message fields can be found in the sample code.

Debug your plugin

When add "-allowdebug" to your server startup line

Release your plugin

When ready for public consumption or beta testing, announce your server plugin at a community website like SourcePlugins.

Console commands

In the console, you can get a list of available plugin related commands with this command: cvarlist plugin_

cvar list
--------------
plugin_load        : cmd : : plugin_load <filename> : loads a plugin
plugin_pause       : cmd : : plugin_pause <index> : pauses a loaded plugin
plugin_pause_all   : cmd : : pauses all loaded plugins
plugin_print       : cmd : : Prints details about loaded plugins
plugin_unload      : cmd : : plugin_unload <index> : unloads a plugin
plugin_unpause     : cmd : : plugin_unpause <index> : unpauses a disabled plugin
plugin_unpause_all : cmd : : unpauses all disabled plugins
--------------
  7 convars/concommands for [plugin_]