Portponky / better-terrain

Terrain plugin for Godot 4
The Unlicense
509 stars 24 forks source link

Error when using multi-threaded build #71

Closed ice-ko closed 6 months ago

ice-ko commented 8 months ago

Dynamically generating maps is slow. I used multi-threading to generate the map. I am not very familiar with gdscript multi-threading. I am using the C# API and the code is the latest. The error message is as follows: E 0:00:02:0848 BetterTerrain.gd:110 @ _get_cache(): Adding children to a node inside the SceneTree is only allowed from the main thread. Use call_deferred("add_child",node). <C++ Error> Condition "data.inside_tree && !Thread::is_main_thread()" is true. <C++ source file> scene/main/node.cpp:1411 @ add_child()

BetterTerrain.gd:110 @ _get_cache() BetterTerrain.gd:852 @ set_cell()
Portponky commented 8 months ago

Hi, using TileMap from another thread is going to cause problems. Likewise, BetterTerrain's functions are not going to be threadsafe either. Instead, BetterTerrain provides an API for processing terrain calculations in a threadpool. Check out the following functions:

CreateTerrainChangeset
IsTerrainChangesetReady
WaitForTerrainChangeset
ApplyTerrainChangeset

When calling CreateTerrainChangeset and providing a dictionary of Vector2i -> terrain type (int), it triggers terrain processing on another thread. After IsTerrainChangesetReady returns true, you can apply the terrain to the map by calling ApplyTerrainChangeset. Note that you call these functions from the main thread. Hope this helps.