Módulos personalizados en C++¶
Módulos¶
Godot permite extender el motor de forma modular. Se pueden crear nuevos módulos, y después, activarlos o desactivarlos. Esto permite añadir nuevas funcionalidades para el motor en todos los niveles sin modificar el núcleo, el cual se puede escindir para su uso y reutilizar en diferentes módulos.
Los módulos se encuentran en el subdirectorio modules/
del sistema de compilación. Por defecto, decenas de módulos están activados, como GDScript (pues sí, no es parte del motor base), el tiempo de ejecución de Mono, un módulo de expresiones regulares, entre otros. Se pueden crear y combinar tantos módulos nuevos como se quiera. El sistema de compilación SCons se encargará de ello transparentemente.
¿Para qué?¶
Mientras se recomienda que la mayor parte de un juego se escriba en scripts (ya que ahorra mucho tiempo), resulta posible usar C++ en su lugar. Añadir módulos C++ puede resultar útil en los siguientes escenarios:
Vincular una biblioteca externa a Godot (como PhysX, FMOD, etc.).
Optimizar partes críticas de un juego.
Añadir una nueva funcionalidad al motor y/o al editor.
Portar un juego existente.
Escribe un nuevo juego entero en C++ porque no puedes vivir sin C++.
Crear un nuevo módulo¶
Antes de crear un módulo, asegúrate de descargar el código fuente de Godot y compilarlo.
Para crear un nuevo módulo, el primer paso es crear un directorio dentro de modules/
. Si quieres mantener el módulo por separado, puedes obtener un VCS diferente en módulos para utilizarlo.
El módulo de ejemplo será llamado "summator" (godot/modules/summator
). Dentro crearemos una clase summator simple:
/* summator.h */
#ifndef SUMMATOR_H
#define SUMMATOR_H
#include "core/reference.h"
class Summator : public Reference {
GDCLASS(Summator, Reference);
int count;
protected:
static void _bind_methods();
public:
void add(int p_value);
void reset();
int get_total() const;
Summator();
};
#endif // SUMMATOR_H
Y después, el archivo cpp.
/* summator.cpp */
#include "summator.h"
void Summator::add(int p_value) {
count += p_value;
}
void Summator::reset() {
count = 0;
}
int Summator::get_total() const {
return count;
}
void Summator::_bind_methods() {
ClassDB::bind_method(D_METHOD("add", "value"), &Summator::add);
ClassDB::bind_method(D_METHOD("reset"), &Summator::reset);
ClassDB::bind_method(D_METHOD("get_total"), &Summator::get_total);
}
Summator::Summator() {
count = 0;
}
Esta nueva clase necesita ser registrada de alguna forma, así que se necesitan dos archivos más para ser creada:
register_types.h
register_types.cpp
Importante
Los archivos anteriores deben estar en la carpeta de nivel superior de tu módulo (junto a tus archivos SCsub
y config.py
) para que el módulo se registre correctamente.
Estos archivos deberán contener lo siguiente:
/* register_types.h */
void register_summator_types();
void unregister_summator_types();
/* yes, the word in the middle must be the same as the module folder name */
/* register_types.cpp */
#include "register_types.h"
#include "core/class_db.h"
#include "summator.h"
void register_summator_types() {
ClassDB::register_class<Summator>();
}
void unregister_summator_types() {
// Nothing to do here in this example.
}
Lo siguiente que necesitamos es crear un archivo ``SCsub``para que se compile este módulo:
# SCsub
Import('env')
env.add_source_files(env.modules_sources, "*.cpp") # Add all cpp files to the build
Con múltiples fuentes, también puede agregar cada archivo individualmente a una lista de cadenas de Python:
src_list = ["summator.cpp", "other.cpp", "etc.cpp"]
env.add_source_files(env.modules_sources, src_list)
Esto permite grandes posibilidades usando Python para construir la lista de archivos usando bucles y declaraciones lógicas. Eche un vistazo a algunos módulos que vienen con Godot por defecto para ver ejemplos.
Puedes agregar directorios de inclusión a las rutas de entorno para que sean vistos por el compilador:
env.Append(CPPPATH=["mylib/include"]) # this is a relative path
env.Append(CPPPATH=["#myotherlib/include"]) # this is an 'absolute' path
Si desea añadir banderas personalizadas de compilador al construir su módulo, primero necesita clonar `` env , para que no añada esas banderas a toda la compilación de Godot (lo cual puede causar errores). Ejemplo de `` SCsub
con banderas personalizadas:
# SCsub
Import('env')
module_env = env.Clone()
module_env.add_source_files(env.modules_sources, "*.cpp")
# Append CCFLAGS flags for both C and C++ code.
module_env.Append(CCFLAGS=['-O2'])
# If you need to, you can:
# - Append CFLAGS for C code only.
# - Append CXXFLAGS for C++ code only.
Y por último, el archivo de configuración para el módulo, el cual es un script simple de python que debe ser nombrado config.py
:
# config.py
def can_build(env, platform):
return True
def configure(env):
pass
Se le pregunta al módulo si está bien construirlo para la plataforma especificada (en este caso, True
significa que se construirá para cada plataforma).
Y eso es todo. ¡Espero que no haya sido demasiado complicado! Su módulo debería verse así:
godot/modules/summator/config.py
godot/modules/summator/summator.h
godot/modules/summator/summator.cpp
godot/modules/summator/register_types.h
godot/modules/summator/register_types.cpp
godot/modules/summator/SCsub
Luego puede comprimirlo y compartir el módulo con todos los demás. Cuando se construya para cada plataforma (instrucciones en las secciones anteriores), se incluirá su módulo.
Nota
Hay un límite de 5 parámetros en los módulos de C ++ para cosas como subclases. Este límite puede llegar a alcanzar 13 si se incluye el archivo de encabezado core / method_bind_ext.gen.inc
.
Usar el módulo¶
Ahora puede usar su módulo recién creado desde cualquier script:
var s = Summator.new()
s.add(10)
s.add(20)
s.add(30)
print(s.get_total())
s.reset()
La salida será 60
.
Ver también
El ejemplo Summator anterior es excelente para módulos personalizados pequeños, pero podría preguntarse qué sucede si desea usar una biblioteca externa más grande. Consulte Binding to external libraries para más detalles sobre la vinculación de librerías externas.
Advertencia
Si se debe acceder a su módulo desde el proyecto en ejecución (no solo desde el editor), también debe recompilar cada plantilla de exportación que planea usar, y después especificar la ruta a la plantilla personalizada en cada ajuste preestablecido de exportación. De lo contrario, obtendrá errores al ejecutar el proyecto, ya que el módulo no se compila en la plantilla de exportación. Consulte las páginas Compilación de para obtener más información.
Compilar un módulo externamente¶
Compilar un módulo implica mover las fuentes del módulo directamente al directorio modules/
. Si bien esta es la forma más sencilla de compilar un módulo, hay un par de razones por las que esto podría no ser algo práctico:
Tener que copiar manualmente las fuentes de los módulos cada vez que desee compilar el motor con o sin el módulo, o tomar los pasos adicionales necesarios para desactivar manualmente un módulo durante la compilación con una opción de compilación similar a
module_summator_enabled=no
. La creación de enlaces simbólicos también puede ser una solución, pero es posible que deba superar las restricciones del sistema operativo como necesitar el privilegio de enlace simbólico si lo hace a través de un script.Depending on whether you have to work with the engine's source code, the module files added directly to
modules/
changes the working tree to the point where using a VCS (likegit
) proves to be cumbersome as you need to make sure that only the engine-related code is committed by filtering changes.
So if you feel like the independent structure of custom modules is needed, lets take our "summator" module and move it to the engine's parent directory:
mkdir ../modules
mv modules/summator ../modules
Compile the engine with our module by providing custom_modules
build option
which accepts a comma-separated list of directory paths containing custom C++
modules, similar to the following:
scons custom_modules=../modules
The build system shall detect all modules under the ../modules
directory
and compile them accordingly, including our "summator" module.
Advertencia
Any path passed to custom_modules
will be converted to an absolute path
internally as a way to distinguish between custom and built-in modules. It
means that things like generating module documentation may rely on a
specific path structure on your machine.
Improving the build system for development¶
Advertencia
This shared library support is not designed to support distributing a module to other users without recompiling the engine. For that purpose, use GDNative instead.
So far, we defined a clean SCsub that allows us to add the sources of our new module as part of the Godot binary.
This static approach is fine when we want to build a release version of our game, given we want all the modules in a single binary.
However, the trade-off is that every single change requires a full recompilation of the game. Even though SCons is able to detect and recompile only the file that was changed, finding such files and eventually linking the final binary takes a long time.
The solution to avoid such a cost is to build our own module as a shared library that will be dynamically loaded when starting our game's binary.
# SCsub
Import('env')
sources = [
"register_types.cpp",
"summator.cpp"
]
# First, create a custom env for the shared library.
module_env = env.Clone()
# Position-independent code is required for a shared library.
module_env.Append(CCFLAGS=['-fPIC'])
# Don't inject Godot's dependencies into our shared library.
module_env['LIBS'] = []
# Define the shared library. By default, it would be built in the module's
# folder, however it's better to output it into `bin` next to the
# Godot binary.
shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
# Finally, notify the main build environment it now has our shared library
# as a new dependency.
# LIBPATH and LIBS need to be set on the real "env" (not the clone)
# to link the specified libraries to the Godot executable.
env.Append(LIBPATH=['#bin'])
# SCons wants the name of the library with it custom suffixes
# (e.g. ".x11.tools.64") but without the final ".so".
shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
env.Append(LIBS=[shared_lib_shim])
Once compiled, we should end up with a bin
directory containing both the
godot*
binary and our libsummator*.so
. However given the .so is not in
a standard directory (like /usr/lib
), we have to help our binary find it
during runtime with the LD_LIBRARY_PATH
environment variable:
export LD_LIBRARY_PATH="$PWD/bin/"
./bin/godot*
Nota
You have to export
the environment variable. Otherwise,
you won't be able to run your project from the editor.
On top of that, it would be nice to be able to select whether to compile our
module as shared library (for development) or as a part of the Godot binary
(for release). To do that we can define a custom flag to be passed to SCons
using the ARGUMENT
command:
# SCsub
Import('env')
sources = [
"register_types.cpp",
"summator.cpp"
]
module_env = env.Clone()
module_env.Append(CCFLAGS=['-O2'])
if ARGUMENTS.get('summator_shared', 'no') == 'yes':
# Shared lib compilation
module_env.Append(CCFLAGS=['-fPIC'])
module_env['LIBS'] = []
shared_lib = module_env.SharedLibrary(target='#bin/summator', source=sources)
shared_lib_shim = shared_lib[0].name.rsplit('.', 1)[0]
env.Append(LIBS=[shared_lib_shim])
env.Append(LIBPATH=['#bin'])
else:
# Static compilation
module_env.add_source_files(env.modules_sources, sources)
Now by default scons
command will build our module as part of Godot's binary
and as a shared library when passing summator_shared=yes
.
Finally, you can even speed up the build further by explicitly specifying your shared module as target in the SCons command:
scons summator_shared=yes platform=x11 bin/libsummator.x11.tools.64.so
Writing custom documentation¶
Writing documentation may seem like a boring task, but it is highly recommended to document your newly created module in order to make it easier for users to benefit from it. Not to mention that the code you've written one year ago may become indistinguishable from the code that was written by someone else, so be kind to your future self!
There are several steps in order to setup custom docs for the module:
Make a new directory in the root of the module. The directory name can be anything, but we'll be using the
doc_classes
name throughout this section.Ahora necesitamos editar
config.py
, agrega el siguiente código:def get_doc_path(): return "doc_classes" def get_doc_classes(): return [ "Summator", ]
The get_doc_path()
function is used by the build system to determine
the location of the docs. In this case, they will be located in the
modules/summator/doc_classes
directory. If you don't define this,
the doc path for your module will fall back to the main doc/classes
directory.
The get_doc_classes()
method is necessary for the build system to
know which registered classes belong to the module. You need to list all of your
classes here. The classes that you don't list will end up in the
main doc/classes
directory.
Truco
You can use Git to check if you have missed some of your classes by checking the
untracked files with git status
. For example:
user@host:~/godot$ git status
Ejemplo de salida:
Untracked files:
(use "git add <file>..." to include in what will be committed)
doc/classes/MyClass2D.xml
doc/classes/MyClass4D.xml
doc/classes/MyClass5D.xml
doc/classes/MyClass6D.xml
...
Ahora podemos generar la documentación:
We can do this via running Godot's doctool i.e. godot --doctool <path>
,
which will dump the engine API reference to the given <path>
in XML format.
In our case we'll point it to the root of the cloned repository. You can point it to an another folder, and just copy over the files that you need.
Run command:
user@host:~/godot/bin$ ./bin/<godot_binary> --doctool .
Now if you go to the godot/modules/summator/doc_classes
folder, you will see
that it contains a Summator.xml
file, or any other classes, that you referenced
in your get_doc_classes
function.
Edit the file(s) following Contribuyendo a la referencia de la clase and recompile the engine.
Once the compilation process is finished, the docs will become accessible within the engine's built-in documentation system.
In order to keep documentation up-to-date, all you'll have to do is simply modify one of the XML files and recompile the engine from now on.
If you change your module's API, you can also re-extract the docs, they will contain the things that you previously added. Of course if you point it to your godot folder, make sure you don't lose work by extracting older docs from an older engine build on top of the newer ones.
Note that if you don't have write access rights to your supplied <path>
,
you might encounter an error similar to the following:
ERROR: Can't write doc file: docs/doc/classes/@GDScript.xml
At: editor/doc/doc_data.cpp:956
Añadir iconos de editor personalizados¶
Similarly to how you can write self-contained documentation within a module, you can also create your own custom icons for classes to appear in the editor.
For the actual process of creating editor icons to be integrated within the engine, please refer to Iconos del editor first.
Once you've created your icon(s), proceed with the following steps:
Make a new directory in the root of the module named
icons
. This is the default path for the engine to look for module's editor icons.Move your newly created
svg
icons (optimized or not) into that folder.Recompile the engine and run the editor. Now the icon(s) will appear in editor's interface where appropriate.
If you'd like to store your icons somewhere else within your module,
add the following code snippet to config.py
to override the default path:
def get_icons_path(): return "path/to/icons"
Summing up¶
Remember to:
use la macro `` GDCLASS '' para la herencia, para que Godot pueda encapsularla
use `` _bind_methods '' para vincular sus funciones a secuencias de comandos y permitir que funcionen como devoluciones de llamada para señales.
But this is not all, depending what you do, you will be greeted with some (hopefully positive) surprises.
Si hereda de: ref: class_Node (o cualquier tipo de nodo derivado, como Sprite), su nueva clase aparecerá en el editor, en el árbol de herencia en el cuadro de diálogo" Agregar nodo ".
Si hereda de: ref: class_Resource, aparecerá en la lista de recursos y todas las propiedades expuestas se pueden serializar cuando se guardan / cargan.
Con esta misma lógica, usted puede ampliar el Editor y casi cualquier área del motor.