LightmapGI in Godot – Complete Guide

Welcome to our deep dive into the world of baked lighting and global illumination in game development. In this tutorial, we’re exploring the LightmapGI class in Godot 4, a powerful feature for adding realism and depth to your games. Whether you’re a budding game developer or a seasoned coder looking to polish your skill set, mastering LightmapGI can significantly enhance the visual quality of your games. We invite you to join us on this enlightening journey through one of Godot’s most robust lighting systems.

Understanding LightmapGI

LightmapGI stands for Lightmap Global Illumination in Godot 4 and represents a cutting-edge tool for achieving efficient and beautiful lighting in your 3D scenes. Used correctly, LightmapGI can bake light and color information directly onto your textures, ensuring your games look stunning while maintaining excellent performance, even on less powerful hardware.

The Purpose of LightmapGI

A core component of LightmapGI’s functionality is its ability to pre-calculate and store lighting information, providing your game’s worlds with high-quality indirect lighting effects. LightmapGI is particularly effective at minimizing light leakage and also supports rough reflections through spherical harmonics, which is handy if you want that extra level of detail in your scenes.

Why Learn LightmapGI?

  • Enhanced Visuals: Smooth gradients of light and shadow contribute greatly to the realism of a scene. Learning LightmapGI allows you to create these nuanced effects with ease.
  • Optimized Performance: By pre-baking lighting data, LightmapGI optimizes the runtime performance of your games, making them accessible to players with a wide range of hardware capabilities.
  • Versatility: While LightmapGI excels in static scenes, it also supports dynamic objects using light probes, making it a versatile tool for a variety of game scenarios.

Join us as we unlock the potential of LightmapGI to differentiate your games and captivate your audience with stunning visuals.

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

Setting Up LightmapGI

To get started with LightmapGI, the first step is to set up the environment within the Godot 4 editor. This involves adding a LightmapGI node to your scene. Here’s how:

var lightmap_gi = LightmapGI.new()
get_root().add_child(lightmap_gi)

Once the node is added, adjust its properties to fit your scene’s requirements. The ‘Energy’ property can be tweaked to control the intensity of the baked lighting:

lightmap_gi.energy = 0.8  # Set the intensity of baked lighting

Next, you need to prepare your objects to work with LightmapGI by enabling ‘Use In Baked Light’ and ‘Bake Mode’ on the mesh instances:

for mesh_instance in get_tree().get_nodes_in_group("BakeGroup"):
    mesh_instance.gi_mode = MeshInstance.GI_MODE_BAKED

Creating Light Bakes

With your scene and objects ready for LightmapGI, it’s time to create a light bake. In the Godot editor, you can do this through the ‘Bake Lightmaps’ option in the LightmapGI node, but you can also initiate a bake via GDScript:

lightmap_gi.bake()

After baking, you’ll see that your scene’s lighting now looks more realistic, with soft shadows and subtle color nuances. To further control how light bakes affect different objects, you can adjust the ‘Indirect Lighting Intensity’ and ‘Light Data Energy’ of your MeshInstances:

mesh_instance.set_bake_setting(MeshInstance.BAKE_INDIRECT_ENERGY, 1.5)
mesh_instance.set_bake_setting(MeshInstance.BAKE_MAX_LIGHT_DATA_SIZE, 2048)

These settings determine how much indirect light an object will reflect and the resolution of the baked lightmaps, respectively.

Optimizing for Dynamic Objects

LightmapGI isn’t just for static geometry; you can also optimize dynamic objects to receive indirect lighting. This is achieved by using light probes:

var light_probe = LightProbe.new()
light_probe.bounds = AABB(Vector3(-1, -1, -1), Vector3(2, 2, 2))
add_child(light_probe)

Light probes capture lighting information around dynamic objects. In your script, ensure that your dynamic object is set up to use light probes:

dynamic_mesh_instance.gi_mode = MeshInstance.GI_MODE_LIGHTPROBES

With the probes in place, you’ll need to bake the light data again to include the information they collect:

lightmap_gi.bake()

Light probes help to bridge the gap between the static baked environment and moving objects, by reflecting accurate indirect lighting information onto them as they move through the scene.

Adjusting Baked Reflections

Reflections in LightmapGI can add an extra layer of depth, thanks to the use of spherical harmonics. This allows for approximated reflections of the environment on the surface of your objects. To use this feature, you must enable the ‘Use As Reflection Probe’ option on your MeshInstances:

mesh_instance.use_as_reflection_probe = true

And once again, a bake is necessary to compute the reflections:

lightmap_gi.bake()

Adjusting the reflection probe’s intensity and other properties can be done as follows:

mesh_instance.reflection_probe_intensity = 1.2
mesh_instance.reflection_probe_max_distance = 10.0
mesh_instance.reflection_probe_exterior_ambient = Color(0.3, 0.4, 0.5)

These settings will dictate the strength of the reflections, how far they reach, and what color the ambient light should be when outside the probe’s influence.

Through the use of these code examples, developers can begin to see the potential that LightmapGI can bring to the aesthetic of their games. We encourage experimenting with these settings to find the perfect balance for your scenes.

Improving Lightmap Quality

Once you’re comfortable with using LightmapGI, you may want to refine the quality of the lightmaps for an even more polished look. You can adjust the ‘Lightmap Size’ property to increase the resolution of your lightmaps:

lightmap_gi.lightmap_size = 4096  # Higher values produce better quality lightmaps

Keep in mind that higher resolutions can lead to longer bake times and increased memory usage, so find a balance that works for your project. It’s also possible to adjust the granularity of the light baking process by setting the ‘Bake Cell Size’:

lightmap_gi.bake_cell_size = 0.5  # Smaller values can give more detail but increase bake time

For more control over shadows and other fine details, Godot’s LightmapGI allows tweaking the ‘Capture Cell Size’, which can refine how the light and shadows are captured in the environment:

lightmap_gi.capture_cell_size = 0.1  # Adjusting this affects the precision of light and shadow capture

To optimize the lighting for specific objects, particularly ones that will interact with dynamic lights, you can set up the ‘Light Baking Mode’ on each MeshInstance:

mesh_instance.light_baking_mode = MeshInstance.BAKE_ALL  # Ensures the object fully participates in the baking process

Another way to improve the visual fidelity in your game is by implementing a secondary bounce of light for more realistic global illumination. This can be managed via the ‘Bounces’ property:

lightmap_gi.bounces = 2  # This enables secondary light bounces, creating more realistic lighting

And lastly, for scenes where the lighting conditions may change, such as in day-night cycles, you can fine-tune the ‘Energy Multiplier’ to simulate the different lighting dynamics that would naturally occur:

lightmap_gi.energy_multiplier = 0.6  # Dial down or up the lighting intensity according to the in-game time of day

Debugging and Helpful Tips

As you work to create beautiful and efficient lightmaps, you may run into issues or require specific debugging information. Godot provides tools for visualizing various aspects of the lightmap and global illumination process:

lightmap_gi.debug_mode = LightmapGI.DEBUG_MODE_OVERDRAW  # Visualize where lightmaps may be more dense or overlapping

When it comes to managing your lightmaps and ensuring they don’t consume too much memory, it’s crucial to also manage the individual ‘Max Lightmap Size’ per mesh:

mesh_instance.set_bake_setting(MeshInstance.BAKE_MAX_LIGHTMAP_SIZE, 512)  # Setting max lightmap size for this specific mesh

If you’re finding that the lightmaps don’t seem to be displaying correctly, make sure that the ‘Baking Enabled’ property is set for the entire scene or for individual nodes where necessary:

lightmap_gi.baking_enabled = true  # Confirm that baking is enabled

Lastly, remember to periodically save your scene and lightmap data, especially before initiating a bake that might take some time to complete. This helps prevent loss of work due to mishaps during the baking process:

if lightmap_gi.bake(visualize=true) == OK:
    print("Bake successful")
    get_tree().save_scene(root_node)  # Save the scene post-bake

While the nuances of LightmapGI and global illumination can be complex, patience and practice lead to stunning results. Each code snippet provided offers another tool to enhance your scenes and create immersive gaming experiences. We’re excited to see developers use these tools to bring their virtual worlds to life with realistic lighting.

For those situations where you might need to exclude certain objects from the lightmap baking process, such as dynamic characters or temporary effects, you can use the ‘Exclude from Baking’ property:

var dynamic_object = $DynamicObject
dynamic_object.gi_mode = MeshInstance.GI_MODE_DISABLED  # Disable GI for this object only

On the flip side, when aiming for the highest quality of baked lighting, even minor details matter. Ensuring that your UV2 channels are correctly set up for lightmap bakes is critical. You can verify and set this up in code as follows:

for mesh_instance in get_tree().get_nodes_in_group("BakeGroup"):
    if mesh_instance.get_surface_material(0) and not mesh_instance.get_lightmap().is_valid():
        print("Missing valid UV2 lightmap channel for ", mesh_instance.name)

Godot offers a variety of ways to visualize your lightmaps for debugging and quality assurance. For instance, you might want to see the direct lighting contributions separately:

lightmap_gi.debug_mode = LightmapGI.DEBUG_MODE_DIRECT

To visualize only the indirect lighting, which refers to the light that has bounced off surfaces, use:

lightmap_gi.debug_mode = LightmapGI.DEBUG_MODE_INDIRECT

For developers looking to push the boundaries of lighting realism in their game, Godot also offers an ‘Advanced Settings’ section where you can tweak additional parameters, like the ‘Propagation’ which controls how light spreads:

lightmap_gi.propagation = 0.7  # A higher value spreads light further

Dealing with detailed surfaces and textures, setting the ‘Interior’ flag ensures that the lighting calculation takes into account that the object is inside a structure, which can help to prevent unwanted light leakages:

mesh_instance.interior = true  # Telling the engine that the object is indoors

Lastly, when optimizing your game, be aware of the ‘Quality’ setting in LightmapGI, which can influence the bake time as well as the runtime performance. Adjusting the quality down can lead to faster bake times and improved performance at the cost of some visual fidelity:

lightmap_gi.quality = LightmapGI.QUALITY_LOW  # Useful for real-time applications or quick previews

All these tools and settings within the LightmapGI class in Godot 4 provide a comprehensive solution for lighting in 3D scenes, which can be a game-changer for increasing the realism in your indie game. Utilizing the advanced lighting features not only creates a more immersive environment for players but also ensures that your game stands out in a competitive market. So, experiment with these settings, understand the impact they have on your scenes, and bake the perfect lightmap for your game!

Continuing Your Game Development Journey with Godot

The world of game development is rich and ever-expanding, offering endless opportunities for creators to harness their skills and bring imaginative worlds to life. If you’ve enjoyed embarking on this exploration of LightmapGI in Godot 4 and are eager to delve deeper, the journey doesn’t have to end here.

Our Godot Game Development Mini-Degree is an excellent next step to continue expanding your game development knowledge. With a comprehensive curriculum designed for both beginners and seasoned developers, you’ll gain hands-on experience building cross-platform games and mastering the various facets of Godot 4.

And for those who wish to explore other aspects of Godot or find courses specific to their current learning goals, our broader collection of Godot courses offers a wealth of resources to support your continued growth as a game developer. Whether you’re crafting the next hit indie game or aspiring to join the gaming industry, Zenva stands by to provide high-quality content to help you lead the way.

Conclusion

In wrapping up our tutorial on LightmapGI in Godot 4, we hope you’ve found invaluable insights into the power of baked lighting and global illumination. The right lighting can transform a simple scene into a vivid, dynamic environment that resonates with players, and mastering these techniques sets the foundation for making your game truly standout. But don’t let your learning stop here—this is just the beginning of a thrilling journey into the realms of game development.

We at Zenva understand the passion and the dedication it takes to turn game ideas into tangible experiences. That’s why our Godot Game Development Mini-Degree is crafted to equip you with the skills needed to take your projects to the next level. Join us, and together we’ll bring your dream games into the hands of eager players around the world. Your game development adventure is just getting started, and Zenva is here to guide you every step of the way.

FREE COURSES
Python Blog Image

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