Development/es: Difference between revisions

From DDraceNetwork
(Created page with "Algunos recursos útiles para aprender C++: * [https://www.learncpp.com/ learncpp.com] * [https://en.cppreference.com/w/ cppreference.com] * El motor de búsqueda que prefiera")
(Updating to match new version of source page)
(18 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{MigrateTranslation}}
<languages/>
<languages/>
Este artículo pretende introducirte en el '''''desarollo''''' de DDNet, Al tratarse de un juego de código abierto, depende de las personas que contribuyen a él en su tiempo libre.
Este artículo pretende introducirte en el '''''desarrollo''''' de DDNet, Al tratarse de un juego de código abierto, depende de las personas que contribuyen a él en su tiempo libre.




Line 18: Line 19:
* El motor de búsqueda que prefiera
* El motor de búsqueda que prefiera


<div lang="en" dir="ltr" class="mw-content-ltr">
El código fuente de DDNet se gestiona mediante [https://git-scm.com/ Git], un sistema de control de versiones, una herramienta esencial para colaborar con múltiples desarrolladores.
The source code of DDNet is managed using [https://git-scm.com/ Git], a version control system, an essential tool to collaborate with multiple developers.
 
</div>
Si aún no tiene git en su distribución Linux, asegúrese de instalarlo, por ejemplo, en la mayoría de las distribuciones basadas en debian/ubuntu se instala con el siguiente comando en la terminal: <code>sudo apt install git</code>.


<div lang="en" dir="ltr" class="mw-content-ltr">
If you don't have git yet in your Linux distribution, make sure to install it, for example in most debian/ubuntu based distributions: <code>sudo apt install git</code>.
</div>


<span id="Getting_the_source_code"></span>
== Obtener el código fuente ==


<div lang="en" dir="ltr" class="mw-content-ltr">
El código fuente se encuentra en [https://github.com/ddnet/ddnet Github], puedes obtener el código fuente clonándolo sin necesidad de una cuenta, pero si alguna vez quieres poner tus cambios en el código fuente oficial necesitarás una.
== Getting the source code ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Si no estás familiarizado con git/github puedes aprender lo básico aquí: [https://docs.github.com/en/get-started/quickstart/hello-world Hola Mundo - Github]
The source code is located on [https://github.com/ddnet/ddnet Github], you can get the source code by cloning without the need of an account, but if you want to ever put your changes to the official source code you will need one.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
If you are not familiar with git/github you can learn the basics here: [https://docs.github.com/en/get-started/quickstart/hello-world Hello World - Github]
</div>


<span id="Installing_the_dependencies"></span>
== Instalación de dependencias ==


<div lang="en" dir="ltr" class="mw-content-ltr">
Si utiliza Linux, puede instalar todas las dependencias necesarias leyendo el archivo README en la página de DDNet en github: https://github.com/ddnet/ddnet#dependencies-on-linux--macos
== Installing the dependencies ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Para Arch Linux:
If you are on Linux, you can install all the needed dependencies by reading the README on the DDNet github page: https://github.com/ddnet/ddnet#dependencies-on-linux--macos
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="bash">
For Arch Linux:
sudo pacman -S --needed base-devel cmake curl ffmpeg freetype2 git glew glslang gmock libnotify libpng opusfile python rust sdl2 spirv-tools sqlite vulkan-headers vulkan-icd-loader wavpack x264
</div>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
Para Debian:
<code>sudo pacman -S --needed base-devel cmake curl freetype2 git glew gmock libnotify opusfile python sdl2 sqlite wavpack</code>
</div>


<syntaxhighlight lang="bash">
sudo apt install build-essential cargo cmake git glslang-tools google-mock libavcodec-extra libavdevice-dev libavfilter-dev libavformat-dev libavutil-dev libcurl4-openssl-dev libfreetype6-dev libglew-dev libnotify-dev libogg-dev libopus-dev libopusfile-dev libpng-dev libsdl2-dev libsqlite3-dev libssl-dev libvulkan-dev libwavpack-dev libx264-dev python rustc spirv-tools4
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Compiling_DDNet"></span>
== Compiling DDNet ==
== Compilación de DDNet ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Usamos CMake para controlar el proceso de compilación, si tienes todas las dependencias instaladas, es tan fácil como seguir estos comandos (asegúrate de estar en la carpeta de DDNet):
We use CMake to control the compilation process, if you have all the dependencies installed, it's as easy as following these commands (make sure you are on the DDNet folder):
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="bash">
<syntaxhighlight lang="bash">
mkdir build
mkdir build
Line 72: Line 60:
make -j$(nproc)
make -j$(nproc)
</syntaxhighlight>
</syntaxhighlight>
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="General_information"></span>
== General information ==
== Información general ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Aquí tienes algo de información general:
Here are some general bits of information:
* Actualmente, el código fuente está compilado con el estándar C++17, pero verás que muchas partes del código son más parecidas a C ya que solo la mayor parte del código nuevo utiliza cosas de C++17.
* Currently, the source code is compiled with the C++17 standard, but you will see that many parts of the code are more C-like since only mostly new code uses C++17 stuff.
* <code>std::string</code> rara vez se usa, además de utilizar <code>system.h</code> métodos para manejarlos es la norma.
* <code>std::string</code> is rarely used, char arrays plus using <code>system.h</code> methods for handling them are the norm.
* La mayor parte del código de E/S, formateo e impresión se realiza utilizando los métodos proporcionados por <code>system.h</code>.
* Most I/O code, formatting and printing is done using <code>system.h</code> provided methods.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="The_source_code_layout"></span>
== The source code layout ==
== La disposición del código fuente ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Ahora que ya puedes construir DDNet, puedes empezar a editarlo.
Now that you can build DDNet you can begin editing it.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="The_src/base_directory"></span>
=== The src/base directory ===
=== El directorio src/base ===
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Dado que DDNet es un juego multiplataforma, se necesita una capa de abstracción para facilitar el desarrollo, y este directorio contiene muchas funciones útiles para ello.
Since DDNet is a cross-platform game, an abstraction layer over that is needed to make development easier, this directory contains many useful functions to handle that.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="The_src/engine_directory"></span>
=== The src/engine directory ===
=== El directorio src/engine ===
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Aquí se encuentra el motor del juego, que se encarga de la mayoría de las cosas que no están relacionadas con la jugabilidad, como los gráficos, el sonido, la red, etc.
Here lies the game engine, it handles most stuff that is not gameplay related, such as graphics, sound, network, etc.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="The_src/game_directory"></span>
=== The src/game directory ===
=== El directorio src/game ===
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Todo el código relacionado con el juego está aquí, separado en cliente y servidor.
All gameplay related code is here, separated into client and server.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Server_side"></span>
==== Server side ====
==== Del lado del servidor ====
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Este juego utiliza su propio sistema jerárquico orientado a objetos de entidades, la clase principal de la que derivan todas las demás entidades es[https://en.wikipedia.org/wiki/Entity_component_system Entity Component System], the main class to which all other entities derive from is <code>CEntity</code> located in <code>src/game/server/entity.h</code>.
This game uses its own [https://en.wikipedia.org/wiki/Entity_component_system Entity Component System], the main class to which all other entities derive from is <code>CEntity</code> located in <code>src/game/server/entity.h</code>.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Estas entidades son gestionadas por el game world ubicado aquí <code>src/game/server/gameworld.h</code>
These entities are managed by the game world located here <code>src/game/server/gameworld.h</code>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Algunas entidades importantes son:
Some important entities are:
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
* [https://github.com/ddnet/ddnet/blob/master/src/game/server/entities/character.h CCharacter]: Representa un [[Special:MyLanguage/Common_Terminology#Tee|tee]] que esté vivo, se crea cuando aparece un tee y se elimina cuando muere. Para más información sobre el jugador que se mantiene entre muertes, véase [https://github.com/ddnet/ddnet/blob/master/src/game/server/player.h CPlayer].
* [https://github.com/ddnet/ddnet/blob/master/src/game/server/entities/character.h CCharacter]: Represents a [[Special:MyLanguage/Common_Terminology#Tee|tee]] that is alive, it is instantiated when a tee spawns and deleted when it dies. For information about the player kept between deaths, see [https://github.com/ddnet/ddnet/blob/master/src/game/server/player.h CPlayer].
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Client_side"></span>
==== Client side ====
==== Lado del cliente ====
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
El lado del cliente está formado por componentes, que son clases que heredan de <code>CComponent</code>: Estos componentes pueden aplicar métodos virtuales como <code>OnInit</code>, <code>OnMessage</code>, etc. Para proporcionar su funcionalidad.
The client side is made up of components, these are classes that inherit <code>CComponent</code>: These components can implement the virtual methods such as <code>OnInit</code>, <code>OnMessage</code>, etc. to provide their functionality.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Networking"></span>
==== Networking ====
==== Redes ====
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
El protocolo de red en su mayoría es generado por scripts python que generan código C++, por ejemplo, <code>datasrc/network.py</code> define todos los paquetes de red.
The network protocol is mostly generated by python scripts that output C++ code, for example, <code>datasrc/network.py</code> defines all network packets.
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Code_conventions"></span>
== Code conventions ==
== Convenciones de código ==
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
El debate en curso sobre las convenciones del código se encuentra aquí:
The ongoing discussion on code conventions is located here: [https://github.com/ddnet/ddnet/issues/2945 ddnet#2945]
[https://github.com/ddnet/ddnet/issues/2945 ddnet#2945]
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Actualmente, se aplica lo siguiente:
Currently, the following applies:
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Indentation_style"></span>
=== Indentation style ===
=== Estilo de indentación ===
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
[https://en.wikipedia.org/wiki/Indentation_style#Allman_style Allman style] se utiliza.
[https://en.wikipedia.org/wiki/Indentation_style#Allman_style Allman style] is used.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 199: Line 149:


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Finalthing();
FinalThing();
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 209: Line 158:


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Must be prefixed by <code>C</code> (for legacy reasons this is ignored for structs in some places, such as in graphics code) or <code>I</code> for interfaces.
Must be prefixed by <code>C</code> (for legacy reasons this is ignored for structs in some places, such as in graphics code) or <code>I</code> for interfaces. New <code>struct</code>s should be prefixed by <code>S</code>.
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
Ejemplo:
Example:
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 271: Line 218:
<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
* <code>m</code> for member variables: <code>m_MyVariable</code>.
* <code>m</code> for member variables: <code>m_MyVariable</code>.
* <code>s</code> for static variables: <code>s_MyStaticVariable</code>.
* <code>s</code> for static variables: <code>s_MyStaticVariable</code>, <code>ms_MyStaticMemberVariable</code>.
* <code>g</code> for global variables with external linkage: <code>gs_MyGlobalStaticVar</code>.
* <code>g</code> for global variables with external linkage: <code>gs_MyGlobalStaticVar</code>.
</div>
</div>




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Prefixes"></span>
==== Prefixes ====
==== Prefijos ====
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
* <code>p</code> for pointers: <code>pMyPointer</code>, <code>m_pCharacter</code>, <code>ppMyPointerToPointer</code>.
* <code>p</code> for pointers: <code>pMyPointer</code>, <code>m_pCharacter</code>, <code>ppMyPointerToPointer</code>.
* <code>a</code> for arrays: <code>aMyArray</code>, <code>aBuf</code>.
* <code>a</code> for arrays: <code>aMyArray</code>, <code>aBuf</code>.
* <code>v</code> for <code>std::vector</code>s: <code>vMyVector</code>, <code>vpvMyVectorOfPointersToVectors</code>.
* <code>fn</code> for functions: <code>pfnMyCallback</code>, <code>m_papfnMyPointerToArrayOfCallbacks</code>.
* <code>fn</code> for functions: <code>pfnMyCallback</code>, <code>m_papfnMyPointerToArrayOfCallbacks</code>.
</div>
</div>
Line 296: Line 243:




<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Formatting_text"></span>
=== Formatting text ===
=== Formato del texto ===
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 306: Line 252:
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
See [https://cplusplus.com/reference/cstdio/printf/ printf documentation] for a list of all format specifiers.
=== Iterating over all players ===
=== Iterating over all players ===
</div>
</div>
Line 334: Line 280:




<div lang="en" dir="ltr" class="mw-content-ltr">
 
=== Debug printing ===
<span id="Debug_printing"></span>
</div>
=== Impresión de depuración ===


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 345: Line 291:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
=== Translating text in the client ===
<code>Localize</code> can be used in the game client to get the translation for a specific string from the language file selected by the user.<syntaxhighlight lang="cpp">
DoButton(..., Localize("Connect"), ...);
</syntaxhighlight>The string can also contain format specifiers. The translated string must contain the same format specifiers.<syntaxhighlight lang="cpp">
char aBuf[128];
str_format(aBuf, sizeof(aBuf), Localize("%d of %d servers"), NumServers, TotalServers);
</syntaxhighlight>A script is used to scan the code for calls to <code>Localize</code> and collect the strings to update the translation files. For this reason, the call to <code>Localize</code> must not contain any other code, or the script cannot determine the text correctly.<syntaxhighlight lang="cpp">
// Do NOT do this:
const char *pStr = Localize(Team == TEAM_RED ? "Red team" : "Blue team");
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
== External resources ==
// Do this instead:
const char *pStr = Team == TEAM_RED ? Localize("Red team") : Localize("Blue team");
</syntaxhighlight>
</div>
</div>
<span id="External_resources"></span>
== Recursos externos ==


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
* [https://edgarluque.com/blog/ui-code-ddnet/ UI Code in DDraceNetwork] by [[Special:MyLanguage/User:Ryozuki|Ryozuki]]
* [https://edgarluque.com/blog/intro-to-ddnet/ An intro to the DDraceNetwork game source code]  by [[Special:MyLanguage/User:Ryozuki|Ryozuki]]
* [https://edgarluque.com/blog/intro-to-ddnet/ An intro to the DDraceNetwork game source code]  by [[Special:MyLanguage/User:Ryozuki|Ryozuki]]
* [https://edgarluque.com/blog/code-conventions-in-ddnet/ Code conventions in DDraceNetwork]  by [[Special:MyLanguage/User:Ryozuki|Ryozuki]]
* [https://edgarluque.com/blog/code-conventions-in-ddnet/ Code conventions in DDraceNetwork]  by [[Special:MyLanguage/User:Ryozuki|Ryozuki]]
Line 358: Line 321:
* [https://heinrich5991.github.io/blog/blog/one-tick-unfreeze The Anatomy of a One Tick Unfreeze]
* [https://heinrich5991.github.io/blog/blog/one-tick-unfreeze The Anatomy of a One Tick Unfreeze]
* [https://www.youtube.com/playlist?list=PLhJkqAQmOh5LyYOfnMy4PJB6CSZltQyTc Teeworlds programming YouTube tutorial] by ChillerDragon
* [https://www.youtube.com/playlist?list=PLhJkqAQmOh5LyYOfnMy4PJB6CSZltQyTc Teeworlds programming YouTube tutorial] by ChillerDragon
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
== About Tee Skin Rendering ==
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
This section explains how to render a tee skin.
</div>
<div lang="en" dir="ltr" class="mw-content-ltr">
Values put together by Patiga
Special Thanks to Jupstar
Segment Scaling:
    body: 100%
    feet: 150%
    eyes: 120%
    eye blink: 45%
    hand: 93.75%
Positioning:
    64/64 = 1 = width or height of the body segment
    body: 4/64 up
    feet:
        10/64 down
        7/64 left/right
    eyes:
        0.125 up
        0.05 left/right
    eye movement:
        dir = angle of eyes (view angle), right = 0
        eyes:
            x: cos(dir) * 0.125
            y: sin(dir) * 0.1
        each eye (away from the other):
            x: abs(cos(dir)) * 0.01
</div>
</div>

Revision as of 07:26, 3 September 2023

Este artículo pretende introducirte en el desarrollo de DDNet, Al tratarse de un juego de código abierto, depende de las personas que contribuyen a él en su tiempo libre.


Tu entorno de desarrollo

Es extremadamente recomendable configurar algún entorno de Linux para empezar a programar en DDNet por las siguientes razones (a partir de ahora):

  • La mayoría de los colaboradores de DDNet utilizan Linux para contribuir.
  • Gestión de paquetes más simple, puedes instalar fácilmente todas las librerías necesarias y empezar a contribuir.
  • Este artículo aún no tiene versión para Windows y se centra en Linux.

Primero que todo, DDNet está codificado usando el lenguaje de programación C++, necesitarás estar bastante familiarizado con él, pero también puedes saber lo básico y aprender más con él.

Algunos recursos útiles para aprender C++:

El código fuente de DDNet se gestiona mediante Git, un sistema de control de versiones, una herramienta esencial para colaborar con múltiples desarrolladores.

Si aún no tiene git en su distribución Linux, asegúrese de instalarlo, por ejemplo, en la mayoría de las distribuciones basadas en debian/ubuntu se instala con el siguiente comando en la terminal: sudo apt install git.


Obtener el código fuente

El código fuente se encuentra en Github, puedes obtener el código fuente clonándolo sin necesidad de una cuenta, pero si alguna vez quieres poner tus cambios en el código fuente oficial necesitarás una.

Si no estás familiarizado con git/github puedes aprender lo básico aquí: Hola Mundo - Github


Instalación de dependencias

Si utiliza Linux, puede instalar todas las dependencias necesarias leyendo el archivo README en la página de DDNet en github: https://github.com/ddnet/ddnet#dependencies-on-linux--macos

Para Arch Linux:

sudo pacman -S --needed base-devel cmake curl ffmpeg freetype2 git glew glslang gmock libnotify libpng opusfile python rust sdl2 spirv-tools sqlite vulkan-headers vulkan-icd-loader wavpack x264

Para Debian:

sudo apt install build-essential cargo cmake git glslang-tools google-mock libavcodec-extra libavdevice-dev libavfilter-dev libavformat-dev libavutil-dev libcurl4-openssl-dev libfreetype6-dev libglew-dev libnotify-dev libogg-dev libopus-dev libopusfile-dev libpng-dev libsdl2-dev libsqlite3-dev libssl-dev libvulkan-dev libwavpack-dev libx264-dev python rustc spirv-tools4

Compilación de DDNet

Usamos CMake para controlar el proceso de compilación, si tienes todas las dependencias instaladas, es tan fácil como seguir estos comandos (asegúrate de estar en la carpeta de DDNet):

mkdir build
cd build
cmake ..
make -j$(nproc)


Información general

Aquí tienes algo de información general:

  • Actualmente, el código fuente está compilado con el estándar C++17, pero verás que muchas partes del código son más parecidas a C ya que solo la mayor parte del código nuevo utiliza cosas de C++17.
  • std::string rara vez se usa, además de utilizar system.h métodos para manejarlos es la norma.
  • La mayor parte del código de E/S, formateo e impresión se realiza utilizando los métodos proporcionados por system.h.


La disposición del código fuente

Ahora que ya puedes construir DDNet, puedes empezar a editarlo.


El directorio src/base

Dado que DDNet es un juego multiplataforma, se necesita una capa de abstracción para facilitar el desarrollo, y este directorio contiene muchas funciones útiles para ello.


El directorio src/engine

Aquí se encuentra el motor del juego, que se encarga de la mayoría de las cosas que no están relacionadas con la jugabilidad, como los gráficos, el sonido, la red, etc.


El directorio src/game

Todo el código relacionado con el juego está aquí, separado en cliente y servidor.


Del lado del servidor

Este juego utiliza su propio sistema jerárquico orientado a objetos de entidades, la clase principal de la que derivan todas las demás entidades esEntity Component System, the main class to which all other entities derive from is CEntity located in src/game/server/entity.h.

Estas entidades son gestionadas por el game world ubicado aquí src/game/server/gameworld.h

Algunas entidades importantes son:

  • CCharacter: Representa un tee que esté vivo, se crea cuando aparece un tee y se elimina cuando muere. Para más información sobre el jugador que se mantiene entre muertes, véase CPlayer.


Lado del cliente

El lado del cliente está formado por componentes, que son clases que heredan de CComponent: Estos componentes pueden aplicar métodos virtuales como OnInit, OnMessage, etc. Para proporcionar su funcionalidad.


Redes

El protocolo de red en su mayoría es generado por scripts python que generan código C++, por ejemplo, datasrc/network.py define todos los paquetes de red.


Convenciones de código

El debate en curso sobre las convenciones del código se encuentra aquí: ddnet#2945

Actualmente, se aplica lo siguiente:


Estilo de indentación

Allman style se utiliza.

This style puts the brace associated with a control statement on the next line, indented to the same level as the control statement. Statements within the braces are indented to the next level.

while(x == y)
{
    Something();
    SomethingElse();
}
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
FinalThing();

Classes and Structs

Must be prefixed by C (for legacy reasons this is ignored for structs in some places, such as in graphics code) or I for interfaces. New structs should be prefixed by S.

Ejemplo:

class CCharacter : public CEntity
{
    // ...
}


Enums and constants

Should be screaming snake case, for example: MAX_PLAYERS

enum
{
	FAKETUNE_FREEZE = 1,
	FAKETUNE_SOLO = 2,
	FAKETUNE_NOJUMP = 4,
	FAKETUNE_NOCOLL = 8,
	FAKETUNE_NOHOOK = 16,
	FAKETUNE_JETPACK = 32,
	FAKETUNE_NOHAMMER = 64,
};


Variable naming

  • The names of variables contain 3 parts: qualifier, prefix and name.
  • Variable names should start with uppercase unless they are 1 char long without any prefix or qualifier, for example: i, x, y.
  • Variables can have more than 1 qualifier (or zero) and more than 1 prefix (or zero).

These are laid out like this: [qualifiers]_[prefixes][Name]


Qualifiers

  • m for member variables: m_MyVariable.
  • s for static variables: s_MyStaticVariable, ms_MyStaticMemberVariable.
  • g for global variables with external linkage: gs_MyGlobalStaticVar.


Prefijos

  • p for pointers: pMyPointer, m_pCharacter, ppMyPointerToPointer.
  • a for arrays: aMyArray, aBuf.
  • v for std::vectors: vMyVector, vpvMyVectorOfPointersToVectors.
  • fn for functions: pfnMyCallback, m_papfnMyPointerToArrayOfCallbacks.


Common snippets

Here is a list of code that you may frequently see across the codebase:


Formato del texto

char aBuf[128];
str_format(aBuf, sizeof(aBuf), "number: %d", 2);

See printf documentation for a list of all format specifiers.

Iterating over all players

for(int i = 0; i < MAX_CLIENTS; i++)
{
    // Server-side
    CPlayer *pPlayer = GameServer()->m_apPlayers[i];
}


Printing to the game console

Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "wikiprint", "Hello from the ddnet wiki!");


Impresión de depuración

int i = 2;
dbg_msg("wikiprint", "Hello from the ddnet wiki: %d", i);

Translating text in the client

Localize can be used in the game client to get the translation for a specific string from the language file selected by the user.
DoButton(..., Localize("Connect"), ...);
The string can also contain format specifiers. The translated string must contain the same format specifiers.
char aBuf[128];
str_format(aBuf, sizeof(aBuf), Localize("%d of %d servers"), NumServers, TotalServers);
A script is used to scan the code for calls to Localize and collect the strings to update the translation files. For this reason, the call to Localize must not contain any other code, or the script cannot determine the text correctly.
// Do NOT do this:
const char *pStr = Localize(Team == TEAM_RED ? "Red team" : "Blue team");
</div>

<div lang="en" dir="ltr" class="mw-content-ltr">
// Do this instead:
const char *pStr = Team == TEAM_RED ? Localize("Red team") : Localize("Blue team");

Recursos externos

About Tee Skin Rendering

This section explains how to render a tee skin.

Values put together by Patiga

Special Thanks to Jupstar

Segment Scaling:
   body: 100%
   feet: 150%
   eyes: 120%
   eye blink: 45%
   hand: 93.75%

Positioning:
   64/64 = 1 = width or height of the body segment
   body: 4/64 up
   feet:
       10/64 down
       7/64 left/right
   eyes:
       0.125 up
       0.05 left/right

   eye movement:
       dir = angle of eyes (view angle), right = 0
       eyes:
           x: cos(dir) * 0.125
           y: sin(dir) * 0.1
       each eye (away from the other):
           x: abs(cos(dir)) * 0.01