TextServerAdvanced in Godot – Complete Guide

TextServerAdvanced: The Key to Advanced Text Rendering in Godot 4

When you start game development with Godot 4, sooner or later you’re bound to find yourself faced with the challenge of rendering text. Whether it’s dialogues in an RPG, instructions in a puzzle game, or UI elements in a strategy game, text is an integral part of many gaming experiences. But when it comes to supporting various languages, complex scripts, and advanced typography features, things can quickly get tricky. This is where Godot’s TextServerAdvanced comes into play, an integral part of the engine that can handle these complexities with ease.

What is TextServerAdvanced?

TextServerAdvanced is a class inherited from TextServerExtension, TextServer, RefCounted, and Object. It serves as an advanced text server that supports bidirectional text (BiDi), complex text layout, and contextual OpenType features. Essentially, this means that it can handle right-to-left languages, intricate scripts like Arabic or Indic languages, and advanced typography that can adjust text display based on its context within a sentence or word. Needless to say, the power of TextServerAdvanced is vital for developers aiming to create games that are accessible to a wide, international audience.

What is it for?

The primary reason for using TextServerAdvanced is to ensure your game’s text is not only accurately displayed but also beautifully rendered, no matter the language or complexity of the script. It uses technologies like HarfBuzz, ICU, and SIL Graphite, which are foundational tools for typography in the software industry. In Godot, TextServerAdvanced ensures that text rendering works behind the scenes so that game developers can focus on the creative side of game production rather than the technicalities of text encoding and layout.

Why should I learn it?

By understanding and leveraging the power of TextServerAdvanced, developers open up their games to a global market. You want to make sure that every player gets the same quality experience, whether they speak English, Hebrew, Hindi, or any other language that requires specialized text processing. What’s more, considering the growing importance of accessibility and internationalization in games, proficiency with TextServerAdvanced has become an essential skill for any Godot developer. It ensures that your games are not just functional, but also polished and inclusive.

In the following sections, we’ll dive deeper into how to use TextServerAdvanced with examples that will highlight its importance and utility in Godot 4. Whether you’re just beginning your journey in game development or you’re an experienced coder looking to enhance your skills, this tutorial will provide you with valuable insights into advanced text rendering. Let’s get started!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Setting Up TextServerAdvanced in Godot 4

To begin using TextServerAdvanced in Godot 4, it’s essential to understand how to enable and configure it within your project. Let’s start by initializing the text server and setting the language preference.

Initializing TextServerAdvanced:

var ts_advanced = TextServerAdvanced.new()

This simple piece of code creates a new instance of the TextServerAdvanced class. However, to make it the default text server, you need to add a bit more.

Setting TextServerAdvanced as Default:

TextServer.set_default(ts_advanced)

Now that we’ve initialized the server and set it as the default, we’re ready to start rendering text with it.

Handling Bidi Text With TextServerAdvanced

Bidirectional text refers to text containing both left-to-right (LTR) and right-to-left (RTL) sequences. Languages like Hebrew or Arabic are RTL languages often mixed with LTR words (like numbers or English words). Here is an example of setting up a label that can properly display bidi text:

Creating a Bidi Label:

var label = RichTextLabel.new()
label.text_direction = TextServer.TEXT_DIRECTION_LTR
label.base_direction = TextServer.TEXT_DIRECTION_AUTO
label.add_text("Hello, this text contains both RTL and LTR elements.")

By setting the text direction and base direction, we can ensure the text is processed correctly.

Rendering Complex Scripts

TextServerAdvanced also shines when displaying complex scripts, such as those found in Indian languages. These scripts often involve characters that change shape depending on their position in a word or sentence.

Displaying Text in Devanagari Script:

var label = RichTextLabel.new()
label.text_direction = TextServer.TEXT_DIRECTION_LTR
label.base_direction = TextServer.TEXT_DIRECTION_AUTO
label.add_text("नमस्ते, यह टेक्स्ट देवनागरी स्क्रिप्ट में है।")

By ensuring that the text server supports complex text layouts, we can seamlessly integrate Indic scripts into our game ui.

Utilizing OpenType Features with TextServerAdvanced

OpenType features in TextServerAdvanced allow for beautiful typography in your game’s UI. Here’s a basic example of enabling specific OpenType features, such as kerning or ligatures:

Enabling OpenType Features:

var richtext_label = RichTextLabel.new()
richtext_label.use_top_level_features = true
richtext_label.text = "fi fl"
richtext_label.add_font_feature("kern", 1) # Enables kerning
richtext_label.add_font_feature("liga", 1) # Enables ligatures

The example above demonstrates how to enable top-level features and specific OpenType features within a RichTextLabel.

These examples cover the necessary basics of initializing TextServerAdvanced, handling bidirectional text, rendering complex scripts, and utilizing OpenType features. Stay tuned for further examples where we will delve deeper into more advanced uses of TextServerAdvanced to enhance text rendering in your Godot 4 projects.By now, you’re getting the hang of the core functionalities of TextServerAdvanced. Beyond the basics, there are many other features and techniques that can significantly enhance your text rendering. Let’s explore some of these in greater detail with practical code examples.

Customizing Font Features:
To further customize the look of your text using TextServerAdvanced, you can set various font features that impact the rendering of text.

var label = Label.new()
label.add_font_feature("calt", 0) # Disables contextual alternates
label.add_font_feature("smcp", 1) # Enables small capitals
label.add_font_feature("numr", 1) # Enables numerator styling for numbers
label.add_font_feature("dnom", 1) # Enables denominator styling for numbers

Font features like ‘calt’, ‘smcp’, ‘numr’, and ‘dnom’ give you control over how the text appears, providing flexibility for creative typography in your game’s UI.

Supporting Multiple Fonts and Languages:
When your game supports multiple languages, you might need to switch between different fonts, depending on the character sets. Here’s how you might set it up:

var font_english = load("res://fonts/EnglishFont.tres")
var font_arabic = load("res://fonts/ArabicFont.tres")
var label = Label.new()

if current_language == "arabic":
    label.add_font_override("font", font_arabic)
else:
    label.add_font_override("font", font_english)

label.text = "The text will adjust to the right font."

By changing the font override based on the current language, you ensure that text is always rendered using the most appropriate font.

Adjusting Line Height and Spacing:
Controlling the line height and spacing between characters and lines can impact readability and the overall aesthetic. Here’s how you can fine-tune these parameters:

var label = RichTextLabel.new()
label.percent_visible = 1
label.custom_effects_enabled = true
label.set_line_spacing(-5) # Reduce line spacing
label.set_line_height(20) # Set fixed line height
label.add_text("Adjusting line height and spacing for readability.")

With `set_line_spacing` and `set_line_height`, your text will have the precise look and feel that fits your game’s design.

Handling Text Shaping and Positioning:
For scripts that require complex shaping, such as connecting or reordering glyphs, TextServerAdvanced has sophisticated text shaping capabilities:

var ts = TextServerManager.get_primary_interface()
var glyphs = ts.shape_string("Shaping كلمة with mixed text.")
var label = Label.new()
label.set_text_as_glyphs(glyphs)

The `shape_string` function is powerful—it can take a string and return an array of glyphs, effectively transforming and positioning the characters accurately for complex scripts.

Right-to-Left Text Alignment:
When dealing with right-to-left text, alignment is a crucial aspect to consider:

var label = Label.new()
label.text_direction = TextServer.TEXT_DIRECTION_RTL
label.align = Label.ALIGN_RIGHT
label.text = "עברית טקסט זה מיושר לימין."

Setting the text direction to `TEXT_DIRECTION_RTL` and aligning the label to the right ensures that RTL text is displayed in a manner that’s consistent with its natural reading direction.

These code snippets demonstrate just a slice of the functionality provided by TextServerAdvanced. As you continue to explore, you’ll discover even more ways to ensure your text rendering is as efficient and versatile as your game requires. Remember, the details in typography can have a big impact on the player experience, making your game not only more accessible but also more professional and engaging.Advanced Typography with Ligatures and Alternates:
Advanced typography can enhance the visual appeal of text in your game. Let’s discuss how to utilize ligatures, which are special characters that combine two or more letters into a single glyph, and stylistic alternates which offer different styles for certain characters.

var label = RichTextLabel.new()
label.add_font_feature("liga", 1) # Enable standard ligatures
label.add_font_feature("dlig", 1) # Enable discretionary ligatures
label.add_font_feature("salt", 1) # Enable stylistic alternates
label.add_text("Facetious fjords & stylish.")

Adjusting Text Opacity and Color:
Sometimes you need to adjust the opacity or color of your texts to fit different UI themes or to signal interactivity.

var label = Label.new()
label.set("custom_colors/font_color", Color(1, 1, 1, 0.5)) # Set to half opacity white
label.set("custom_colors/font_color_shadow", Color(0, 0, 0, 0.5)) # Set to half opacity black for shadow
label.text = "This text has customized opacity and color."

By setting custom color properties, you can control text color and opacity with precision.

Text Wrapping and Overflow:
When space is limited, such as in dialogue boxes or UI banners, you need to control text wrapping and overflow effectively.

var label = Label.new()
label.rect_min_size = Vector2(200, 50) # Set min size to constrain text box
label.clip_text = true # Prevent text overflow
label.wrap_enabled = true # Enable text wrapping within the control's size
label.text = "This is an example of text wrap and overflow handling in Godot."

By activating `clip_text` and `wrap_enabled`, text remains within the confines of the UI elements.

Localized Text with TranslationServer:
In conjunction with TextServerAdvanced, Godot’s TranslationServer can be used to swap text in-game based on the selected language.

var label = Label.new()
TranslationServer.set_locale("es") # Change to Spanish locale
label.text = tr("Hello, World!") # Assume "Hello, World!" has a Spanish translation available.

The `tr()` function retrieves the locale-specific translation of the string, allowing for seamless multi-language support.

Dynamic Font Loading and Scaling:
For games with expandable content or modding capabilities, being able to load and scale fonts dynamically is essential.

var dynamic_font = DynamicFont.new()
dynamic_font.font_path = "res://fonts/MyCustomFont.ttf" # Path to the font file
dynamic_font.size = 18 # Set font size
var label = Label.new()
label.add_font(dynamic_font)
label.text = "Dynamic font loading and scaling."

Using `DynamicFont`, we can create fonts on the fly and set their size, making the same font adaptable for various UI elements.

Displaying Rich Text with BBCode:
RichTextLabel in Godot supports BBCode to format text with a simple markup language.

var richtext_label = RichTextLabel.new()
richtext_label.bbcode_enabled = true
richtext_label.bbcode_text = "This [b]BBCode[/b] is [i]nifty[/i]!"

By enabling BBCode and setting `bbcode_text`, you can easily integrate bold, italics, and more advanced formatting options.

Automated Language Detection:
Detecting the input text’s language can be useful for input fields or any user-generated content within the game.

var input_text = "¿Cómo estás?"
var detected_language = "" # Empty string to store the detected language code

# Imagine this function checks the input and returns a language code
detected_language = my_language_detection_function(input_text)

if detected_language == "es": # Spanish
    # Do something for Spanish text
    print("Text is in Spanish")

This shows a template logic where `my_language_detection_function` is a hypothetical function that you might implement or integrate from a language detection library.

By integrating these features, your game will not only look and feel more polished, but it also ensures that players from different linguistic backgrounds can enjoy the experience you’ve crafted. Use these examples as a springboard for further exploration of TextServerAdvanced’s potential in your own projects!

Furthering Your Godot Journey

Embarking on game development is an adventure of never-ending learning, and mastering Godot 4 is a significant milestone on that journey. As you continue to harness the power of TextServerAdvanced and other features, know that this is just the beginning. Our comprehensive Godot Game Development Mini-Degree offers an extensive array of courses that delve into cross-platform game development with Godot.

From 2D and 3D game mechanics to UI design and combat systems, the program was built to sharpen your skills at your own pace, 24/7, with a flexible scheduling system, and completion certificates available that validate your learning journey. Whether you’re just starting or looking to elevate existing skills, we provide resources for all proficiency levels. For those of you eager to explore an even broader collection of content, our selection of Godot courses covers a wide variety of topics in game development.

Dive into our courses and join the vibrant community of game developers who, like you, chose Zenva as their partner in learning. Allow us to assist you in navigating through the exciting world of Godot, transforming your creative visions into reality. Keep coding, keep creating, and let your game development dreams take flight with Zenva.

Conclusion

In your quest to create games that resonate with players around the globe, mastering the nuances of text rendering is paramount. TextServerAdvanced in Godot 4 is your ally, handling everything from bidirectional scripts to advanced typography with finesse. Armed with this knowledge, your games will not only speak to your players in their language but also reflect the care and detail you’ve invested.

We at Zenva are committed to guiding you through every step of this enriching pathway. Lean on our Godot Game Development Mini-Degree to elevate your skills and bring your unique visions to life. Let the art of code and the craft of game design merge seamlessly in your hands. Here’s to crafting experiences that delight and engage across all borders!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.