From f8f25adc0b8414d1de819d282087b3749469b88c Mon Sep 17 00:00:00 2001 From: kobewi Date: Thu, 13 Oct 2022 02:12:24 +0200 Subject: [PATCH] Don't free instanced scenes when recreating tiles --- scene/2d/tile_map.cpp | 37 +++++++++++++++++++++++++------------ scene/2d/tile_map.h | 2 ++ 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/scene/2d/tile_map.cpp b/scene/2d/tile_map.cpp index 40e88182623..0159e9f3138 100644 --- a/scene/2d/tile_map.cpp +++ b/scene/2d/tile_map.cpp @@ -1859,11 +1859,13 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList::List &r_ while (q_list_element) { TileMapQuadrant &q = *q_list_element->self(); - // Clear the scenes. - for (const KeyValue &E : q.scenes) { - Node *node = get_node_or_null(E.value); - if (node) { - node->queue_free(); + // Clear the scenes if instance cache was cleared. + if (instantiated_scenes.is_empty()) { + for (const KeyValue &E : q.scenes) { + Node *node = get_node_or_null(E.value); + if (node) { + node->queue_free(); + } } } @@ -1871,6 +1873,15 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList::List &r_ // Recreate the scenes. for (const Vector2i &E_cell : q.cells) { + Vector3i cell_coords = Vector3i(q.layer, E_cell.x, E_cell.y); + if (instantiated_scenes.has(cell_coords)) { + // Skip scene if the instance was cached (to avoid recreating scenes unnecessarily). + continue; + } + if (!Engine::get_singleton()->is_editor_hint()) { + instantiated_scenes.insert(cell_coords); + } + const TileMapCell &c = get_cell(q.layer, E_cell, true); TileSetSource *source; @@ -1907,15 +1918,16 @@ void TileMap::_scenes_update_dirty_quadrants(SelfList::List &r_ } void TileMap::_scenes_cleanup_quadrant(TileMapQuadrant *p_quadrant) { - // Clear the scenes. - for (const KeyValue &E : p_quadrant->scenes) { - Node *node = get_node_or_null(E.value); - if (node) { - node->queue_free(); + // Clear the scenes if instance cache was cleared. + if (instantiated_scenes.is_empty()) { + for (const KeyValue &E : p_quadrant->scenes) { + Node *node = get_node_or_null(E.value); + if (node) { + node->queue_free(); + } } + p_quadrant->scenes.clear(); } - - p_quadrant->scenes.clear(); } void TileMap::_scenes_draw_quadrant_debug(TileMapQuadrant *p_quadrant) { @@ -4037,6 +4049,7 @@ void TileMap::_bind_methods() { void TileMap::_tile_set_changed() { emit_signal(SNAME("changed")); _tile_set_changed_deferred_update_needed = true; + instantiated_scenes.clear(); call_deferred(SNAME("_tile_set_changed_deferred_update")); } diff --git a/scene/2d/tile_map.h b/scene/2d/tile_map.h index 7f3e2418716..a6048b3a967 100644 --- a/scene/2d/tile_map.h +++ b/scene/2d/tile_map.h @@ -236,6 +236,8 @@ private: void _clear_layer_internals(int p_layer); void _clear_internals(); + HashSet instantiated_scenes; + // Rect caching. void _recompute_rect_cache();