Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Métodos comuns da engine e macros
A base de código em C++ do Godot faz uso de dezenas de métodos e macros customizados que são usados em quase todos os arquivos. Esta página é voltada para colaboradores iniciantes, mas também pode ser útil para aqueles que estão escrevendo módulos C++ customizados.
Imprimir texto
// Prints a message to standard output.
print_line("Message");
// Non-String arguments are automatically converted to String for printing.
// If passing several arguments, they will be concatenated together with a
// space between each argument.
print_line("There are", 123, "nodes");
// Prints a message to standard output, but only when the engine
// is started with the `--verbose` command line argument.
print_verbose("Message");
// Prints a rich-formatted message using BBCode to standard output.
// This supports a subset of BBCode tags supported by RichTextLabel
// and will also appear formatted in the editor Output panel.
// On Windows, this requires Windows 10 or later to work in the terminal.
print_line_rich("[b]Bold[/b], [color=red]Red text[/color]")
// Prints a formatted error or warning message with a trace.
ERR_PRINT("Message");
WARN_PRINT("Message");
// Prints an error or warning message only once per session.
// This can be used to avoid spamming the console output.
ERR_PRINT_ONCE("Message");
WARN_PRINT_ONCE("Message");
Se você precisar adicionar marcadores de posição (placeholders) em suas mensagens, use strings de formatação conforme descrito abaixo.
Formate uma string
A função vformat() retorna uma String formatada. Ela se comporta de maneira semelhante ao sprintf() do C:
vformat("My name is %s.", "Godette");
vformat("%d bugs on the wall!", 1234);
vformat("Pi is approximately %f.", 3.1416);
// Converts the resulting String into a `const char *`.
// You may need to do this if passing the result as an argument
// to a method that expects a `const char *` instead of a String.
vformat("My name is %s.", "Godette").utf8().get_data();
Na maioria dos casos, tente usar vformat() em vez de concatenação de strings, pois isso torna o código mais legível.
Converter um inteiro ou flutuante para uma string
Isso não é necessário ao imprimir números usando print_line(), mas você ainda pode precisar realizar a conversão manual para alguns outros casos de uso.
// Stores the string "42" using integer-to-string conversion.
String int_to_string = itos(42);
// Stores the string "123.45" using real-to-string conversion.
String real_to_string = rtos(123.45);
Internacionalizar uma string
Existem dois tipos de internacionalização na base de código do Godot:
TTR(): Traduções do Editor (ferramentas ou "tools") serão processadas apenas no editor. Se um usuário usar o mesmo texto em um de seus projetos, ele não será traduzido mesmo que ele forneça uma tradução para isso. Ao contribuir para a engine, esta é geralmente a macro que você deve usar para strings localizáveis.RTR(): Traduções em tempo de execução (Runtime) serão localizadas automaticamente nos projetos caso eles forneçam uma tradução para a string informada. Esse tipo de tradução não deve ser usado em códigos exclusivos do editor.
// Returns the translated string that matches the user's locale settings.
// Translations are located in `editor/translations`.
// The localization template is generated automatically; don't modify it.
TTR("Exit the editor?");
Para inserir marcadores de posição em strings localizáveis, envolva a macro de localização em uma chamada de vformat() da seguinte forma:
String file_path = "example.txt";
vformat(TTR("Couldn't open \"%s\" for reading."), file_path);
Nota
Ao usar vformat() e uma macro de tradução juntas, sempre envolva a macro de tradução na função vformat(), e não o contrário. Caso contrário, a string nunca corresponderá à tradução, pois ela já terá o marcador de posição substituído quando for passada para o TranslationServer.
Restringir um valor
O Godot fornece macros para limitar (clamp) um valor com um limite inferior (MAX), um limite superior (MIN) ou ambos (CLAMP):
int a = 3;
int b = 5;
MAX(b, 6); // 6
MIN(2, a); // 2
CLAMP(a, 10, 30); // 10
Isso funciona com qualquer tipo que possa ser comparado a outros valores (como int e float).
Microbenchmarking
Se você quiser avaliar o desempenho (benchmark) de um trecho de código mas não sabe como usar um profiler, use este snippet:
uint64_t begin = Time::get_singleton()->get_ticks_usec();
// Your code here...
uint64_t end = Time::get_singleton()->get_ticks_usec();
print_line(vformat("Snippet took %d microseconds", end - begin));
Isso imprimirá o tempo gasto entre a declaração do begin e a do end.
Nota
Você pode precisar incluir #include \"core/os/time.h\" se ele já não estiver presente.
Ao abrir um pull request, certifique-se de remover este snippet bem como o include, caso ele não estivesse lá anteriormente.
Obter configurações do projeto/editor
Há quatro macros disponíveis para isso:
// Returns the specified project setting's value,
// defaulting to `false` if it doesn't exist.
GLOBAL_DEF("section/subsection/value", false);
// Returns the specified editor setting's value,
// defaulting to "Untitled" if it doesn't exist.
EDITOR_DEF("section/subsection/value", "Untitled");
Se um valor padrão já tiver sido especificado em outro lugar, não o especifique novamente para evitar repetição:
// Returns the value of the project setting.
GLOBAL_GET("section/subsection/value");
// Returns the value of the editor setting.
EDITOR_GET("section/subsection/value");
Recomenda-se usar GLOBAL_DEF/EDITOR_DEF apenas uma vez por configuração e usar GLOBAL_GET/EDITOR_GET em todos os outros lugares onde ela for referenciada.
Macros de erro
O Godot apresenta muitas macros de erro para tornar os relatórios de erros mais convenientes.
Aviso
As condições nas macros de erro funcionam de maneira oposta à função embutida assert() do GDScript. Um erro é alcançado se a condição interna for avaliada como true, não false.
Nota
Apenas as variantes com mensagens personalizadas são documentadas aqui, pois estas devem sempre ser usadas em novas contribuições. Certifique-se de que a mensagem personalizada fornecida inclua informações suficientes para que as pessoas possam diagnosticar o problema, mesmo que não conheçam C++. Caso um método tenha recebido argumentos inválidos, você pode imprimir o valor inválido em questão para facilitar a depuração.
Para verificações de erro internas onde a exibição de uma mensagem legível por humanos não seja necessária, remova _MSG do final do nome da macro e não forneça um argumento de mensagem.
Além disso, sempre tente retornar dados processáveis para que a engine possa continuar funcionando bem.
// Conditionally prints an error message and returns from the function.
// Use this in methods which don't return a value.
ERR_FAIL_COND_MSG(!mesh.is_valid(), vformat("Couldn't load mesh at: %s", path));
// Conditionally prints an error message and returns `0` from the function.
// Use this in methods which must return a value.
ERR_FAIL_COND_V_MSG(rect.x < 0 || rect.y < 0, 0,
"Couldn't calculate the rectangle's area.");
// Prints an error message if `index` is < 0 or >= `SomeEnum::QUALITY_MAX`,
// then returns from the function.
ERR_FAIL_INDEX_MSG(index, SomeEnum::QUALITY_MAX,
vformat("Invalid quality: %d. See SomeEnum for allowed values.", index));
// Prints an error message if `index` is < 0 >= `some_array.size()`,
// then returns `-1` from the function.
ERR_FAIL_INDEX_V_MSG(index, some_array.size(), -1,
vformat("Item %d is out of bounds.", index));
// Unconditionally prints an error message and returns from the function.
// Only use this if you need to perform complex error checking.
if (!complex_error_checking_routine()) {
ERR_FAIL_MSG("Couldn't reload the filesystem cache.");
}
// Unconditionally prints an error message and returns `false` from the function.
// Only use this if you need to perform complex error checking.
if (!complex_error_checking_routine()) {
ERR_FAIL_V_MSG(false, "Couldn't parse the input arguments.");
}
// Crashes the engine. This should generally never be used
// except for testing crash handling code. Godot's philosophy
// is to never crash, both in the editor and in exported projects.
CRASH_NOW_MSG("Can't predict the future! Aborting.");
Ver também
Veja core/error/error_macros.h na base de código do Godot para mais informações sobre cada macro de erro.
Algumas funções retornam um código de erro (materializado por um tipo de retorno Error). Este valor pode ser retornado diretamente de uma macro de erro. Veja a lista de códigos de erro disponíveis em core/error/error_list.h.