Common engine methods and macros

Godot’s C++ codebase makes use of dozens of custom methods and macros which are used in almost every file. This page is geared towards beginner contributors, but it can also be useful for those writing custom C++ modules.

Print text

  1. // Prints a message to standard output.
  2. print_line("Message");
  3. // Non-String arguments are automatically converted to String for printing.
  4. // If passing several arguments, they will be concatenated together with a
  5. // space between each argument.
  6. print_line("There are", 123, "nodes");
  7. // Prints a message to standard output, but only when the engine
  8. // is started with the `--verbose` command line argument.
  9. print_verbose("Message");
  10. // Prints a rich-formatted message using BBCode to standard output.
  11. // This supports a subset of BBCode tags supported by RichTextLabel
  12. // and will also appear formatted in the editor Output panel.
  13. // On Windows, this requires Windows 10 or later to work in the terminal.
  14. print_line_rich("[b]Bold[/b], [color=red]Red text[/color]")
  15. // Prints a formatted error or warning message with a trace.
  16. ERR_PRINT("Message");
  17. WARN_PRINT("Message");
  18. // Prints an error or warning message only once per session.
  19. // This can be used to avoid spamming the console output.
  20. ERR_PRINT_ONCE("Message");
  21. WARN_PRINT_ONCE("Message");

If you need to add placeholders in your messages, use format strings as described below.

Format a string

The vformat() function returns a formatted String. It behaves in a way similar to C’s sprintf():

  1. vformat("My name is %s.", "Godette");
  2. vformat("%d bugs on the wall!", 1234);
  3. vformat("Pi is approximately %f.", 3.1416);
  4. // Converts the resulting String into a `const char *`.
  5. // You may need to do this if passing the result as an argument
  6. // to a method that expects a `const char *` instead of a String.
  7. vformat("My name is %s.", "Godette").c_str();

In most cases, try to use vformat() instead of string concatenation as it makes for more readable code.

Convert an integer or float to a string

This is not needed when printing numbers using print_line(), but you may still need to perform manual conversion for some other use cases.

  1. // Stores the string "42" using integer-to-string conversion.
  2. String int_to_string = itos(42);
  3. // Stores the string "123.45" using real-to-string conversion.
  4. String real_to_string = rtos(123.45);

Internationalize a string

There are two types of internationalization in Godot’s codebase:

  • TTR(): Editor (“tools”) translations will only be processed in the editor. If a user uses the same text in one of their projects, it won’t be translated if they provide a translation for it. When contributing to the engine, this is generally the macro you should use for localizable strings.

  • RTR(): Run-time translations will be automatically localized in projects if they provide a translation for the given string. This kind of translation shouldn’t be used in editor-only code.

  1. // Returns the translated string that matches the user's locale settings.
  2. // Translations are located in `editor/translations`.
  3. // The localization template is generated automatically; don't modify it.
  4. TTR("Exit the editor?");

To insert placeholders in localizable strings, wrap the localization macro in a vformat() call as follows:

  1. String file_path = "example.txt";
  2. vformat(TTR("Couldn't open \"%s\" for reading."), file_path);

Note

When using vformat() and a translation macro together, always wrap the translation macro in vformat(), not the other way around. Otherwise, the string will never match the translation as it will have the placeholder already replaced when it’s passed to TranslationServer.

Clamp a value

Godot provides macros for clamping a value with a lower bound (MAX), an upper bound (MIN) or both (CLAMP):

  1. int a = 3;
  2. int b = 5;
  3. MAX(b, 6); // 6
  4. MIN(2, a); // 2
  5. CLAMP(a, 10, 30); // 10

This works with any type that can be compared to other values (like int and float).

Microbenchmarking

If you want to benchmark a piece of code but don’t know how to use a profiler, use this snippet:

  1. uint64_t begin = Time::get_singleton()->get_ticks_usec();
  2. // Your code here...
  3. uint64_t end = Time::get_singleton()->get_ticks_usec();
  4. print_line(vformat("Snippet took %d microseconds", end - begin));

This will print the time spent between the begin declaration and the end declaration.

Note

You may have to #include "core/os/os.h" if it’s not present already.

When opening a pull request, make sure to remove this snippet as well as the include if it wasn’t there previously.

Get project/editor settings

There are four macros available for this:

  1. // Returns the specified project setting's value,
  2. // defaulting to `false` if it doesn't exist.
  3. GLOBAL_DEF("section/subsection/value", false);
  4. // Returns the specified editor setting's value,
  5. // defaulting to "Untitled" if it doesn't exist.
  6. EDITOR_DEF("section/subsection/value", "Untitled");

If a default value has been specified elsewhere, don’t specify it again to avoid repetition:

  1. // Returns the value of the project setting.
  2. GLOBAL_GET("section/subsection/value");
  3. // Returns the value of the editor setting.
  4. EDITOR_GET("section/subsection/value");

It’s recommended to use GLOBAL_DEF/EDITOR_DEF only once per setting and use GLOBAL_GET/EDITOR_GET in all other places where it’s referenced.

Error macros

Godot features many error macros to make error reporting more convenient.

Warning

Conditions in error macros work in the opposite way of GDScript’s built-in assert() function. An error is reached if the condition inside evaluates to true, not false.

Note

Only variants with custom messages are documented here, as these should always be used in new contributions. Make sure the custom message provided includes enough information for people to diagnose the issue, even if they don’t know C++. In case a method was passed invalid arguments, you can print the invalid value in question to ease debugging.

For internal error checking where displaying a human-readable message isn’t necessary, remove _MSG at the end of the macro name and don’t supply a message argument.

Also, always try to return processable data so the engine can keep running well.

  1. // Conditionally prints an error message and returns from the function.
  2. // Use this in methods which don't return a value.
  3. ERR_FAIL_COND_MSG(!mesh.is_valid(), vformat("Couldn't load mesh at: %s", path));
  4. // Conditionally prints an error message and returns `0` from the function.
  5. // Use this in methods which must return a value.
  6. ERR_FAIL_COND_V_MSG(rect.x < 0 || rect.y < 0, 0,
  7. "Couldn't calculate the rectangle's area.");
  8. // Prints an error message if `index` is < 0 or >= `SomeEnum::QUALITY_MAX`,
  9. // then returns from the function.
  10. ERR_FAIL_INDEX_MSG(index, SomeEnum::QUALITY_MAX,
  11. vformat("Invalid quality: %d. See SomeEnum for allowed values.", index));
  12. // Prints an error message if `index` is < 0 >= `some_array.size()`,
  13. // then returns `-1` from the function.
  14. ERR_FAIL_INDEX_V_MSG(index, some_array.size(), -1,
  15. vformat("Item %d is out of bounds.", index));
  16. // Unconditionally prints an error message and returns from the function.
  17. // Only use this if you need to perform complex error checking.
  18. if (!complex_error_checking_routine()) {
  19. ERR_FAIL_MSG("Couldn't reload the filesystem cache.");
  20. }
  21. // Unconditionally prints an error message and returns `false` from the function.
  22. // Only use this if you need to perform complex error checking.
  23. if (!complex_error_checking_routine()) {
  24. ERR_FAIL_V_MSG(false, "Couldn't parse the input arguments.");
  25. }
  26. // Crashes the engine. This should generally never be used
  27. // except for testing crash handling code. Godot's philosophy
  28. // is to never crash, both in the editor and in exported projects.
  29. CRASH_NOW_MSG("Can't predict the future! Aborting.");

See also

See core/error/error_macros.h in Godot’s codebase for more information about each error macro.

Some functions return an error code (materialized by a return type of Error). This value can be returned directly from an error macro. See the list of available error codes in core/error/error_list.h.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next