Debian Codegraph @

scene/2d/tile_map_layer.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* tile_map_layer.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "tile_map_layer.h"
32
33 #include "core/io/marshalls.h"
34 #include "core/math/geometry_2d.h"
35 #include "core/math/random_pcg.h"
36 #include "core/templates/a_hash_map.h"
37 #include "scene/2d/tile_map.h"
38 #include "scene/gui/control.h"
39 #include "scene/resources/2d/navigation_mesh_source_geometry_data_2d.h"
40 #include "scene/resources/material.h"
41 #include "scene/resources/world_2d.h"
42
43 #ifndef PHYSICS_2D_DISABLED
44 #include "servers/physics_2d/physics_server_2d.h"
45 #endif // PHYSICS_3D_DISABLED
46
47 #ifndef NAVIGATION_2D_DISABLED
48 #include "servers/navigation_2d/navigation_server_2d.h"
49 Callable TileMapLayer::_navmesh_source_geometry_parsing_callback;
50 RID TileMapLayer::_navmesh_source_geometry_parser;
51 #endif // NAVIGATION_2D_DISABLED
52
53 Vector2i TileMapLayer::_coords_to_quadrant_coords(const Vector2i &p_coords, const int p_quadrant_size) const {
54 return Vector2i(
55 p_coords.x > 0 ? p_coords.x / p_quadrant_size : (p_coords.x - (p_quadrant_size - 1)) / p_quadrant_size,
56 p_coords.y > 0 ? p_coords.y / p_quadrant_size : (p_coords.y - (p_quadrant_size - 1)) / p_quadrant_size);
57 }
58
59 #ifdef DEBUG_ENABLED
60 /////////////////////////////// Debug //////////////////////////////////////////
61 constexpr int TILE_MAP_DEBUG_QUADRANT_SIZE = 16;
62
63 void TileMapLayer::_debug_update(bool p_force_cleanup) {
64 RenderingServer *rs = RenderingServer::get_singleton();
65
66 // Check if we should cleanup everything.
67 bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
68 if (forced_cleanup && _debug_was_cleaned_up) {
69 return;
70 }
71
72 if (forced_cleanup) {
73 for (KeyValue<Vector2i, Ref<DebugQuadrant>> &kv : debug_quadrant_map) {
74 // Free the quadrant.
75 Ref<DebugQuadrant> &debug_quadrant = kv.value;
76 if (debug_quadrant->canvas_item.is_valid()) {
77 rs->free_rid(debug_quadrant->canvas_item);
78 }
79 if (debug_quadrant->physics_mesh.is_valid()) {
80 rs->free_rid(debug_quadrant->physics_mesh);
81 }
82 }
83 debug_quadrant_map.clear();
84 _debug_was_cleaned_up = true;
85 return;
86 }
87
88 // Check if anything is dirty, in such a case, redraw debug.
89 bool anything_changed = false;
90 for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
91 if (dirty.flags[i]) {
92 anything_changed = true;
93 break;
94 }
95 }
96
97 // List all debug quadrants to update.
98 HashSet<Vector2i> quadrants_to_updates;
99 if (_debug_was_cleaned_up || anything_changed) {
100 // Update all cells.
101 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
102 CellData &cell_data = kv.value;
103 quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
104 #ifndef PHYSICS_2D_DISABLED
105 // Physics quadrants are drawn from their origin.
106 Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
107 quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
108 #endif // PHYSICS_2D_DISABLED
109 }
110 } else {
111 // Update dirty cells.
112 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
113 CellData &cell_data = *cell_data_list_element->self();
114 quadrants_to_updates.insert(_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE));
115 #ifndef PHYSICS_2D_DISABLED
116 // Physics quadrants are drawn from their origin.
117 Vector2i physics_quadrant_origin = _coords_to_quadrant_coords(cell_data.coords, physics_quadrant_size) * physics_quadrant_size;
118 quadrants_to_updates.insert(_coords_to_quadrant_coords(physics_quadrant_origin, TILE_MAP_DEBUG_QUADRANT_SIZE));
119 #endif // PHYSICS_2D_DISABLED
120 }
121 }
122
123 // Create new quadrants if needed.
124 for (const Vector2i &quadrant_coords : quadrants_to_updates) {
125 if (!debug_quadrant_map.has(quadrant_coords)) {
126 // Create a new quadrant and add it to the quadrant map.
127 Ref<DebugQuadrant> new_quadrant;
128 new_quadrant.instantiate();
129 new_quadrant->quadrant_coords = quadrant_coords;
130 debug_quadrant_map[quadrant_coords] = new_quadrant;
131 }
132 }
133
134 // Second pass on modified cells to update the list of cells per quandrant.
135 if (_debug_was_cleaned_up || anything_changed) {
136 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
137 CellData &cell_data = kv.value;
138 Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
139 if (!cell_data.debug_quadrant_list_element.in_list()) {
140 debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
141 }
142 }
143 } else {
144 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
145 CellData &cell_data = *cell_data_list_element->self();
146 Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[_coords_to_quadrant_coords(cell_data.coords, TILE_MAP_DEBUG_QUADRANT_SIZE)];
147 if (!cell_data.debug_quadrant_list_element.in_list()) {
148 debug_quadrant->cells.add(&cell_data.debug_quadrant_list_element);
149 }
150 }
151 }
152
153 // Update those quadrants.
154 bool needs_set_not_interpolated = is_inside_tree() && get_tree()->is_physics_interpolation_enabled() && !is_physics_interpolated();
155 for (const Vector2i &quadrant_coords : quadrants_to_updates) {
156 Ref<DebugQuadrant> debug_quadrant = debug_quadrant_map[quadrant_coords];
157
158 // Update the quadrant's canvas item.
159 RID &ci = debug_quadrant->canvas_item;
160 if (ci.is_valid()) {
161 rs->canvas_item_clear(ci);
162 } else {
163 ci = rs->canvas_item_create();
164 if (needs_set_not_interpolated) {
165 rs->canvas_item_set_interpolated(ci, false);
166 }
167 rs->canvas_item_set_z_index(ci, RS::CANVAS_ITEM_Z_MAX - 1);
168 rs->canvas_item_set_parent(ci, get_canvas_item());
169 }
170 const Vector2 quadrant_pos = tile_set->map_to_local(debug_quadrant->quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
171 Transform2D xform(0, quadrant_pos);
172 rs->canvas_item_set_transform(ci, xform);
173
174 #ifndef PHYSICS_2D_DISABLED
175 // Draw physics.
176 _physics_draw_quadrant_debug(ci, *debug_quadrant.ptr());
177 #endif // PHYSICS_2D_DISABLED
178
179 // Draw debug info.
180 for (SelfList<CellData> *cell_data_list_element = debug_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
181 CellData &cell_data = *cell_data_list_element->self();
182 if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
183 _rendering_draw_cell_debug(ci, quadrant_pos, cell_data);
184 #ifndef NAVIGATION_2D_DISABLED
185 _navigation_draw_cell_debug(ci, quadrant_pos, cell_data);
186 #endif // NAVIGATION_2D_DISABLED
187 _scenes_draw_cell_debug(ci, quadrant_pos, cell_data);
188 debug_quadrant->drawn_to = true;
189 }
190 }
191
192 // Free the quadrants that were not drawn to.
193 if (!debug_quadrant->drawn_to) {
194 // Free the quadrant.
195 if (ci.is_valid()) {
196 rs->free_rid(ci);
197 }
198 debug_quadrant_map.erase(quadrant_coords);
199 }
200 }
201
202 _debug_was_cleaned_up = false;
203 }
204
205 #endif // DEBUG_ENABLED
206
207 Color TileMapLayer::_highlight_color(const Color &p_modulate) const {
208 if (highlight_mode == HIGHLIGHT_MODE_BELOW) {
209 return p_modulate.darkened(0.5);
210 }
211 if (highlight_mode == HIGHLIGHT_MODE_ABOVE) {
212 Color c = p_modulate.darkened(0.5);
213 c.a *= 0.3;
214 return c;
215 }
216 return p_modulate;
217 }
218
219 /////////////////////////////// Rendering //////////////////////////////////////
220 void TileMapLayer::_rendering_update(bool p_force_cleanup) {
221 RenderingServer *rs = RenderingServer::get_singleton();
222
223 // Check if we should cleanup everything.
224 bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
225 if (forced_cleanup && _rendering_was_cleaned_up) {
226 return;
227 }
228
229 // ----------- Layer level processing -----------
230 // Modulate the layer.
231 Color layer_modulate = get_self_modulate();
232 #ifdef TOOLS_ENABLED
233 if (!forced_cleanup) {
234 layer_modulate = _highlight_color(layer_modulate);
235 rs->canvas_item_set_self_modulate(get_canvas_item(), layer_modulate);
236 }
237 #endif // TOOLS_ENABLED
238
239 // ----------- Quadrants processing -----------
240
241 // List all rendering quadrants to update, creating new ones if needed.
242 SelfList<RenderingQuadrant>::List dirty_rendering_quadrant_list;
243
244 // Check if anything changed that might change the quadrant shape.
245 // If so, recreate everything.
246 bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] || dirty.flags[DIRTY_FLAGS_TILE_SET] ||
247 (is_y_sort_enabled() && (dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] || dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] || dirty.flags[DIRTY_FLAGS_LAYER_LOCAL_TRANSFORM])) ||
248 (!is_y_sort_enabled() && dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE]);
249
250 // Free all quadrants.
251 if (!_rendering_was_cleaned_up && (forced_cleanup || quadrant_shape_changed)) {
252 for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
253 for (const RID &ci : kv.value->canvas_items) {
254 if (ci.is_valid()) {
255 rs->free_rid(ci);
256 }
257 }
258 kv.value->cells.clear();
259 }
260 rendering_quadrant_map.clear();
261 _rendering_was_cleaned_up = true;
262 }
263
264 if (!forced_cleanup) {
265 // List all quadrants to update, recreating them if needed.
266 if (dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _rendering_was_cleaned_up) {
267 // Update all cells.
268 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
269 CellData &cell_data = kv.value;
270 _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
271 }
272 } else {
273 // Update dirty cells.
274 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
275 CellData &cell_data = *cell_data_list_element->self();
276 _rendering_quadrants_update_cell(cell_data, dirty_rendering_quadrant_list);
277 }
278 }
279
280 // Update all dirty quadrants.
281 bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
282 for (SelfList<RenderingQuadrant> *quadrant_list_element = dirty_rendering_quadrant_list.first(); quadrant_list_element;) {
283 SelfList<RenderingQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
284
285 const Ref<RenderingQuadrant> &rendering_quadrant = quadrant_list_element->self();
286
287 // Check if the quadrant has a tile.
288 bool has_a_tile = false;
289 for (SelfList<CellData> *cell_data_list_element = rendering_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
290 CellData &cell_data = *cell_data_list_element->self();
291 if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
292 has_a_tile = true;
293 break;
294 }
295 }
296
297 if (has_a_tile) {
298 // Process the quadrant.
299
300 // First, clear the quadrant's canvas items.
301 for (RID &ci : rendering_quadrant->canvas_items) {
302 rs->free_rid(ci);
303 }
304 rendering_quadrant->canvas_items.clear();
305
306 // Sort the quadrant cells.
307 if (is_y_sort_enabled() && x_draw_order_reversed) {
308 rendering_quadrant->cells.sort_custom<CellDataYSortedXReversedComparator>();
309 } else {
310 rendering_quadrant->cells.sort();
311 }
312
313 // Those allow to group cell per material or z-index.
314 Ref<Material> prev_material;
315 int prev_z_index = 0;
316 RID prev_ci;
317
318 for (SelfList<CellData> *cell_data_quadrant_list_element = rendering_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
319 CellData &cell_data = *cell_data_quadrant_list_element->self();
320
321 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
322
323 // Get the tile data.
324 const TileData *tile_data;
325 if (cell_data.runtime_tile_data_cache) {
326 tile_data = cell_data.runtime_tile_data_cache;
327 } else {
328 tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
329 }
330
331 Ref<Material> mat = tile_data->get_material();
332 int tile_z_index = tile_data->get_z_index();
333
334 // Quandrant pos.
335
336 // --- CanvasItems ---
337 RID ci;
338
339 // Check if the material or the z_index changed.
340 if (prev_ci == RID() || prev_material != mat || prev_z_index != tile_z_index) {
341 // If so, create a new CanvasItem.
342 ci = rs->canvas_item_create();
343 if (needs_set_not_interpolated) {
344 rs->canvas_item_set_interpolated(ci, false);
345 }
346 if (mat.is_valid()) {
347 rs->canvas_item_set_material(ci, mat->get_rid());
348 }
349 rs->canvas_item_set_parent(ci, get_canvas_item());
350 rs->canvas_item_set_use_parent_material(ci, mat.is_null());
351
352 Transform2D xform(0, rendering_quadrant->canvas_items_position);
353 rs->canvas_item_set_transform(ci, xform);
354
355 rs->canvas_item_set_light_mask(ci, get_light_mask());
356 rs->canvas_item_set_z_as_relative_to_parent(ci, true);
357 rs->canvas_item_set_z_index(ci, tile_z_index);
358 rs->canvas_item_set_self_modulate(ci, layer_modulate);
359
360 rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
361 rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
362
363 rendering_quadrant->canvas_items.push_back(ci);
364
365 prev_ci = ci;
366 prev_material = mat;
367 prev_z_index = tile_z_index;
368
369 } else {
370 // Keep the same canvas_item to draw on.
371 ci = prev_ci;
372 }
373
374 const Vector2 local_tile_pos = tile_set->map_to_local(cell_data.coords);
375
376 // Random animation offset.
377 real_t random_animation_offset = 0.0;
378 if (atlas_source->get_tile_animation_mode(cell_data.cell.get_atlas_coords()) != TileSetAtlasSource::TILE_ANIMATION_MODE_DEFAULT) {
379 Array to_hash = { local_tile_pos, get_instance_id() }; // Use instance id as a random hash
380 random_animation_offset = RandomPCG(to_hash.hash()).randf();
381 }
382
383 // Drawing the tile in the canvas item.
384 draw_tile(ci, local_tile_pos - rendering_quadrant->canvas_items_position, tile_set, cell_data.cell.source_id, cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile, -1, tile_data, random_animation_offset);
385 }
386
387 // Reset physics interpolation for any recreated canvas items.
388 if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
389 for (const RID &ci : rendering_quadrant->canvas_items) {
390 rs->canvas_item_reset_physics_interpolation(ci);
391 }
392 }
393
394 } else {
395 // Free the quadrant.
396 for (const RID &ci : rendering_quadrant->canvas_items) {
397 if (ci.is_valid()) {
398 rs->free_rid(ci);
399 }
400 }
401 rendering_quadrant->cells.clear();
402 rendering_quadrant_map.erase(rendering_quadrant->quadrant_coords);
403 }
404
405 quadrant_list_element = next_quadrant_list_element;
406 }
407
408 dirty_rendering_quadrant_list.clear();
409
410 // Reset the drawing indices.
411 {
412 int index = -(int64_t)0x80000000; // Always must be drawn below children.
413
414 // Sort the quadrants coords per local coordinates.
415 LocalVector<Pair<Vector2, Ref<RenderingQuadrant>>> sortable_quadrant_keys;
416 sortable_quadrant_keys.reserve(rendering_quadrant_map.size());
417 for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
418 Vector2 local_coords = tile_set->map_to_local(kv.value->quadrant_coords);
419 sortable_quadrant_keys.push_back(Pair<Vector2, Ref<RenderingQuadrant>>(local_coords, kv.value));
420 }
421 struct PairedQuadrantSorter {
422 RenderingQuadrant::CoordsWorldComparator comparator;
423 _ALWAYS_INLINE_ bool operator()(const Pair<Vector2, Ref<RenderingQuadrant>> &p_a, const Pair<Vector2, Ref<RenderingQuadrant>> &p_b) const {
424 return comparator(p_a.first, p_b.first);
425 }
426 };
427 sortable_quadrant_keys.sort_custom<PairedQuadrantSorter>();
428
429 // Set the draw indices.
430 for (const Pair<Vector2, Ref<RenderingQuadrant>> &E : sortable_quadrant_keys) {
431 for (const RID &ci : E.second->canvas_items) {
432 RS::get_singleton()->canvas_item_set_draw_index(ci, index++);
433 }
434 }
435 }
436
437 // Updates on rendering changes.
438 if (dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] ||
439 dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] ||
440 dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] ||
441 dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE] ||
442 dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE]) {
443 for (KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
444 Ref<RenderingQuadrant> &rendering_quadrant = kv.value;
445 for (const RID &ci : rendering_quadrant->canvas_items) {
446 rs->canvas_item_set_light_mask(ci, get_light_mask());
447 rs->canvas_item_set_default_texture_filter(ci, RS::CanvasItemTextureFilter(get_texture_filter_in_tree()));
448 rs->canvas_item_set_default_texture_repeat(ci, RS::CanvasItemTextureRepeat(get_texture_repeat_in_tree()));
449 rs->canvas_item_set_self_modulate(ci, layer_modulate);
450 }
451 }
452 }
453 }
454
455 // -----------
456 // Mark the rendering state as up to date.
457 _rendering_was_cleaned_up = forced_cleanup;
458
459 // ----------- Occluders processing -----------
460 bool cleanup_occlusion = forced_cleanup || !occlusion_enabled;
461 if (cleanup_occlusion && _occlusion_was_cleaned_up) {
462 return;
463 }
464
465 if (cleanup_occlusion) {
466 // Clean everything.
467 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
468 _rendering_occluders_clear_cell(kv.value);
469 }
470 } else {
471 if (_occlusion_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
472 // Update all cells.
473 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
474 _rendering_occluders_update_cell(kv.value);
475 }
476 } else {
477 // Update dirty cells.
478 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
479 CellData &cell_data = *cell_data_list_element->self();
480 _rendering_occluders_update_cell(cell_data);
481 }
482 }
483 }
484
485 // -----------
486 // Mark the occlusion state as up to date.
487 _occlusion_was_cleaned_up = cleanup_occlusion;
488 }
489
490 void TileMapLayer::_rendering_notification(int p_what) {
491 RenderingServer *rs = RenderingServer::get_singleton();
492 if (p_what == NOTIFICATION_TRANSFORM_CHANGED || p_what == NOTIFICATION_ENTER_CANVAS || p_what == NOTIFICATION_VISIBILITY_CHANGED) {
493 if (tile_set.is_valid()) {
494 Transform2D tilemap_xform = get_global_transform();
495 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
496 const CellData &cell_data = kv.value;
497 for (const LocalVector<RID> &polygons : cell_data.occluders) {
498 for (const RID &rid : polygons) {
499 if (rid.is_null()) {
500 continue;
501 }
502 Transform2D xform(0, tile_set->map_to_local(kv.key));
503 rs->canvas_light_occluder_attach_to_canvas(rid, get_canvas());
504 rs->canvas_light_occluder_set_transform(rid, tilemap_xform * xform);
505 }
506 }
507 }
508 }
509 } else if (p_what == NOTIFICATION_RESET_PHYSICS_INTERPOLATION) {
510 if (is_physics_interpolated_and_enabled() && is_visible_in_tree()) {
511 for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
512 for (const RID &ci : kv.value->canvas_items) {
513 if (ci.is_valid()) {
514 rs->canvas_item_reset_physics_interpolation(ci);
515 }
516 }
517 }
518 }
519 }
520 }
521
522 void TileMapLayer::_rendering_quadrants_update_cell(CellData &r_cell_data, SelfList<RenderingQuadrant>::List &r_dirty_rendering_quadrant_list) {
523 // Check if the cell is valid and retrieve its y_sort_origin.
524 bool is_valid = false;
525 int tile_y_sort_origin = 0;
526 TileSetSource *source;
527 if (tile_set->has_source(r_cell_data.cell.source_id)) {
528 source = *tile_set->get_source(r_cell_data.cell.source_id);
529 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
530 if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
531 is_valid = true;
532 const TileData *tile_data;
533 if (r_cell_data.runtime_tile_data_cache) {
534 tile_data = r_cell_data.runtime_tile_data_cache;
535 } else {
536 tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
537 }
538 tile_y_sort_origin = tile_data->get_y_sort_origin();
539 }
540 }
541
542 if (is_valid) {
543 // Get the quadrant coords.
544 Vector2 canvas_items_position;
545 Vector2i quadrant_coords;
546 if (is_y_sort_enabled()) {
547 canvas_items_position = Vector2(0, tile_set->map_to_local(r_cell_data.coords).y + tile_y_sort_origin + y_sort_origin);
548 quadrant_coords = canvas_items_position * 100;
549 } else {
550 const Vector2i &coords = r_cell_data.coords;
551
552 // Rounding down, instead of simply rounding towards zero (truncating).
553 quadrant_coords = _coords_to_quadrant_coords(coords, rendering_quadrant_size);
554 canvas_items_position = tile_set->map_to_local(rendering_quadrant_size * quadrant_coords);
555 }
556
557 Ref<RenderingQuadrant> rendering_quadrant;
558 if (rendering_quadrant_map.has(quadrant_coords)) {
559 // Reuse existing rendering quadrant.
560 rendering_quadrant = rendering_quadrant_map[quadrant_coords];
561 } else {
562 // Create a new rendering quadrant.
563 rendering_quadrant.instantiate();
564 rendering_quadrant->quadrant_coords = quadrant_coords;
565 rendering_quadrant->canvas_items_position = canvas_items_position;
566 rendering_quadrant_map[quadrant_coords] = rendering_quadrant;
567 }
568
569 // Mark the old quadrant as dirty (if it exists).
570 if (r_cell_data.rendering_quadrant.is_valid()) {
571 if (!r_cell_data.rendering_quadrant->dirty_quadrant_list_element.in_list()) {
572 r_dirty_rendering_quadrant_list.add(&r_cell_data.rendering_quadrant->dirty_quadrant_list_element);
573 }
574 }
575
576 // Remove the cell from that quadrant.
577 if (r_cell_data.rendering_quadrant_list_element.in_list()) {
578 r_cell_data.rendering_quadrant_list_element.remove_from_list();
579 }
580
581 // Add the cell to its new quadrant.
582 r_cell_data.rendering_quadrant = rendering_quadrant;
583 r_cell_data.rendering_quadrant->cells.add(&r_cell_data.rendering_quadrant_list_element);
584
585 // Add the new quadrant to the dirty quadrant list.
586 if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
587 r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
588 }
589 } else {
590 Ref<RenderingQuadrant> rendering_quadrant = r_cell_data.rendering_quadrant;
591
592 // Remove the cell from its quadrant.
593 r_cell_data.rendering_quadrant = Ref<RenderingQuadrant>();
594 if (r_cell_data.rendering_quadrant_list_element.in_list()) {
595 rendering_quadrant->cells.remove(&r_cell_data.rendering_quadrant_list_element);
596 }
597
598 if (rendering_quadrant.is_valid()) {
599 // Add the quadrant to the dirty quadrant list.
600 if (!rendering_quadrant->dirty_quadrant_list_element.in_list()) {
601 r_dirty_rendering_quadrant_list.add(&rendering_quadrant->dirty_quadrant_list_element);
602 }
603 }
604 }
605 }
606
607 void TileMapLayer::_rendering_occluders_clear_cell(CellData &r_cell_data) {
608 RenderingServer *rs = RenderingServer::get_singleton();
609
610 // Free the occluders.
611 for (const LocalVector<RID> &polygons : r_cell_data.occluders) {
612 for (const RID &rid : polygons) {
613 rs->free_rid(rid);
614 }
615 }
616 r_cell_data.occluders.clear();
617 }
618
619 void TileMapLayer::_rendering_occluders_update_cell(CellData &r_cell_data) {
620 RenderingServer *rs = RenderingServer::get_singleton();
621
622 // Free unused occluders then resize the occluder array.
623 for (uint32_t i = tile_set->get_occlusion_layers_count(); i < r_cell_data.occluders.size(); i++) {
624 for (const RID &occluder_id : r_cell_data.occluders[i]) {
625 if (occluder_id.is_valid()) {
626 rs->free_rid(occluder_id);
627 }
628 }
629 }
630 r_cell_data.occluders.resize(tile_set->get_occlusion_layers_count());
631
632 TileSetSource *source;
633 if (tile_set->has_source(r_cell_data.cell.source_id)) {
634 source = *tile_set->get_source(r_cell_data.cell.source_id);
635
636 if (source->has_tile(r_cell_data.cell.get_atlas_coords()) && source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
637 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
638 if (atlas_source) {
639 // Get the tile data.
640 const TileData *tile_data;
641 if (r_cell_data.runtime_tile_data_cache) {
642 tile_data = r_cell_data.runtime_tile_data_cache;
643 } else {
644 tile_data = atlas_source->get_tile_data(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile);
645 }
646
647 // Transform flags.
648 bool flip_h = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
649 bool flip_v = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
650 bool transpose = (r_cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
651
652 // Create, update or clear occluders.
653 bool needs_set_not_interpolated = SceneTree::is_fti_enabled() && !is_physics_interpolated();
654 for (uint32_t occlusion_layer_index = 0; occlusion_layer_index < r_cell_data.occluders.size(); occlusion_layer_index++) {
655 LocalVector<RID> &occluders = r_cell_data.occluders[occlusion_layer_index];
656
657 // Free unused occluders then resize the occluders array.
658 for (uint32_t i = tile_data->get_occluder_polygons_count(occlusion_layer_index); i < r_cell_data.occluders[occlusion_layer_index].size(); i++) {
659 RID occluder_id = occluders[i];
660 if (occluder_id.is_valid()) {
661 rs->free_rid(occluder_id);
662 }
663 }
664 occluders.resize(tile_data->get_occluder_polygons_count(occlusion_layer_index));
665
666 for (uint32_t occlusion_polygon_index = 0; occlusion_polygon_index < occluders.size(); occlusion_polygon_index++) {
667 RID &occluder = occluders[occlusion_polygon_index];
668 Ref<OccluderPolygon2D> occluder_polygon = tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index);
669 if (occluder_polygon.is_valid()) {
670 // Create or update occluder.
671
672 Transform2D xform;
673 xform.set_origin(tile_set->map_to_local(r_cell_data.coords));
674 if (!occluder.is_valid()) {
675 occluder = rs->canvas_light_occluder_create();
676 if (needs_set_not_interpolated) {
677 rs->canvas_light_occluder_set_interpolated(occluder, false);
678 }
679 }
680 rs->canvas_light_occluder_set_transform(occluder, get_global_transform() * xform);
681 rs->canvas_light_occluder_set_polygon(occluder, tile_data->get_occluder_polygon(occlusion_layer_index, occlusion_polygon_index, flip_h, flip_v, transpose)->get_rid());
682 rs->canvas_light_occluder_attach_to_canvas(occluder, get_canvas());
683 rs->canvas_light_occluder_set_light_mask(occluder, tile_set->get_occlusion_layer_light_mask(occlusion_layer_index));
684 rs->canvas_light_occluder_set_as_sdf_collision(occluder, tile_set->get_occlusion_layer_sdf_collision(occlusion_layer_index));
685 } else {
686 // Clear occluder.
687 if (occluder.is_valid()) {
688 rs->free_rid(occluder);
689 occluder = RID();
690 }
691 }
692 }
693 }
694
695 return;
696 }
697 }
698 }
699
700 // If we did not return earlier, clear the cell.
701 _rendering_occluders_clear_cell(r_cell_data);
702 }
703
704 #ifdef DEBUG_ENABLED
705 void TileMapLayer::_rendering_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
706 ERR_FAIL_COND(tile_set.is_null());
707
708 if (!Engine::get_singleton()->is_editor_hint()) {
709 return;
710 }
711
712 // Draw a placeholder for tiles needing one.
713 RenderingServer *rs = RenderingServer::get_singleton();
714 const TileMapCell &c = r_cell_data.cell;
715
716 TileSetSource *source;
717 if (tile_set->has_source(c.source_id)) {
718 source = *tile_set->get_source(c.source_id);
719
720 if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
721 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
722 if (atlas_source) {
723 Vector2i grid_size = atlas_source->get_atlas_grid_size();
724 if (atlas_source->get_runtime_texture().is_null() || c.get_atlas_coords().x >= grid_size.x || c.get_atlas_coords().y >= grid_size.y) {
725 // Generate a random color from the hashed values of the tiles.
726 Array to_hash = { c.source_id, c.get_atlas_coords(), c.alternative_tile };
727 uint32_t hash = RandomPCG(to_hash.hash()).rand();
728
729 Color color;
730 color = color.from_hsv(
731 (float)((hash >> 24) & 0xFF) / 256.0,
732 Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
733 Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
734 0.8);
735
736 // Draw a placeholder tile.
737 Transform2D cell_to_quadrant;
738 cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
739 rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
740 rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
741 }
742 }
743 }
744 }
745 }
746 #endif // DEBUG_ENABLED
747
748 /////////////////////////////// Physics //////////////////////////////////////
749
750 #ifndef PHYSICS_2D_DISABLED
751 void TileMapLayer::_physics_update(bool p_force_cleanup) {
752 PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
753
754 // Check if we should cleanup everything.
755 bool forced_cleanup = p_force_cleanup || !enabled || !collision_enabled || !is_inside_tree() || tile_set.is_null();
756 if (forced_cleanup && _physics_was_cleaned_up) {
757 return;
758 }
759
760 // ----------- Quadrants processing -----------
761
762 // List all physics quadrants to update, creating new ones if needed.
763 SelfList<PhysicsQuadrant>::List dirty_physics_quadrant_list;
764
765 // Check if anything changed that might change the quadrant shape.
766 // If so, recreate everything.
767 bool quadrant_shape_changed = dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE];
768
769 // Free all quadrants.
770 if (!_physics_was_cleaned_up && (forced_cleanup || quadrant_shape_changed)) {
771 for (const KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
772 // Clear bodies.
773 for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
774 if (kvbody.value.body.is_valid()) {
775 bodies_coords.erase(kvbody.value.body);
776 ps->free_rid(kvbody.value.body);
777 }
778 }
779 kv.value->bodies.clear();
780 kv.value->cells.clear();
781 }
782 physics_quadrant_map.clear();
783 _physics_was_cleaned_up = true;
784 }
785
786 if (!forced_cleanup) {
787 RID space = get_world_2d()->get_space();
788 Transform2D gl_transform = get_global_transform();
789
790 // List all quadrants to update, recreating them if needed.
791 if (dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || _physics_was_cleaned_up) {
792 // Update all cells.
793 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
794 CellData &cell_data = kv.value;
795 _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
796 }
797 } else {
798 // Update dirty cells.
799 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
800 CellData &cell_data = *cell_data_list_element->self();
801 _physics_quadrants_update_cell(cell_data, dirty_physics_quadrant_list);
802 }
803 }
804
805 // Update all dirty quadrants.
806 for (SelfList<PhysicsQuadrant> *quadrant_list_element = dirty_physics_quadrant_list.first(); quadrant_list_element;) {
807 SelfList<PhysicsQuadrant> *next_quadrant_list_element = quadrant_list_element->next(); // "Hack" to clear the list while iterating.
808
809 const Ref<PhysicsQuadrant> &physics_quadrant = quadrant_list_element->self();
810
811 // Check if the quadrant has a tile.
812 bool has_a_tile = false;
813 for (SelfList<CellData> *cell_data_list_element = physics_quadrant->cells.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
814 CellData &cell_data = *cell_data_list_element->self();
815 if (cell_data.cell.source_id != TileSet::INVALID_SOURCE) {
816 has_a_tile = true;
817 break;
818 }
819 }
820
821 if (has_a_tile) {
822 // Process the quadrant.
823
824 // First, clear the quadrant bodies.
825 for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
826 RID &body = kvbody.value.body;
827 if (body.is_valid()) {
828 bodies_coords.erase(body);
829 ps->free_rid(body);
830 body = RID();
831 }
832 }
833 physics_quadrant->bodies.clear();
834 physics_quadrant->shapes.clear();
835
836 // Quadrant origin
837 Vector2 quadrant_origin = tile_set->map_to_local(physics_quadrant->quadrant_coords);
838
839 // Recreate the quadrant bodies.
840 for (uint32_t tile_set_physics_layer = 0; tile_set_physics_layer < (uint32_t)tile_set->get_physics_layers_count(); tile_set_physics_layer++) {
841 Ref<PhysicsMaterial> physics_material = tile_set->get_physics_layer_physics_material(tile_set_physics_layer);
842 uint32_t physics_layer = tile_set->get_physics_layer_collision_layer(tile_set_physics_layer);
843 uint32_t physics_mask = tile_set->get_physics_layer_collision_mask(tile_set_physics_layer);
844
845 // Merge polygons together for each quadrant.
846 for (SelfList<CellData> *cell_data_quadrant_list_element = physics_quadrant->cells.first(); cell_data_quadrant_list_element; cell_data_quadrant_list_element = cell_data_quadrant_list_element->next()) {
847 CellData &cell_data = *cell_data_quadrant_list_element->self();
848
849 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(*tile_set->get_source(cell_data.cell.source_id));
850
851 // Get the tile data.
852 const TileData *tile_data;
853 if (cell_data.runtime_tile_data_cache) {
854 tile_data = cell_data.runtime_tile_data_cache;
855 } else {
856 tile_data = atlas_source->get_tile_data(cell_data.cell.get_atlas_coords(), cell_data.cell.alternative_tile);
857 }
858
859 // Transform flags.
860 bool flip_h = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
861 bool flip_v = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
862 bool transpose = (cell_data.cell.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
863
864 Vector2 linear_velocity = tile_data->get_constant_linear_velocity(tile_set_physics_layer);
865 real_t angular_velocity = tile_data->get_constant_angular_velocity(tile_set_physics_layer);
866
867 // Setup polygons for merge.
868 for (int polygon_index = 0; polygon_index < tile_data->get_collision_polygons_count(tile_set_physics_layer); polygon_index++) {
869 // Iterate over the polygons.
870 int shapes_count = tile_data->get_collision_polygon_shapes_count(tile_set_physics_layer, polygon_index);
871
872 // Check if we need to create a new body.
873 PhysicsQuadrant::PhysicsBodyKey physics_body_key;
874 physics_body_key.physics_layer = tile_set_physics_layer;
875 physics_body_key.linear_velocity = linear_velocity;
876 physics_body_key.angular_velocity = angular_velocity;
877 physics_body_key.one_way_collision = tile_data->is_collision_polygon_one_way(tile_set_physics_layer, polygon_index);
878 physics_body_key.one_way_collision_margin = tile_data->get_collision_polygon_one_way_margin(tile_set_physics_layer, polygon_index);
879 physics_body_key.y_origin = map_to_local(cell_data.coords).y;
880
881 if (!physics_quadrant->bodies.has(physics_body_key)) {
882 RID body = ps->body_create();
883 physics_quadrant->bodies[physics_body_key] = {};
884 physics_quadrant->bodies[physics_body_key].body = body;
885 bodies_coords[body] = physics_quadrant->quadrant_coords;
886
887 // Create or update the body.
888 ps->body_set_mode(body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
889 ps->body_set_space(body, space);
890
891 Transform2D xform;
892 xform.set_origin(quadrant_origin);
893 xform = gl_transform * xform;
894 ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
895
896 ps->body_attach_object_instance_id(body, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
897 ps->body_set_collision_layer(body, physics_layer);
898 ps->body_set_collision_mask(body, physics_mask);
899 ps->body_set_pickable(body, false);
900 ps->body_set_state(body, PhysicsServer2D::BODY_STATE_LINEAR_VELOCITY, linear_velocity);
901 ps->body_set_state(body, PhysicsServer2D::BODY_STATE_ANGULAR_VELOCITY, angular_velocity);
902
903 if (!physics_material.is_valid()) {
904 ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, 0);
905 ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, 1);
906 } else {
907 ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_BOUNCE, physics_material->computed_bounce());
908 ps->body_set_param(body, PhysicsServer2D::BODY_PARAM_FRICTION, physics_material->computed_friction());
909 }
910 }
911
912 for (int shape_index = 0; shape_index < shapes_count; shape_index++) {
913 Ref<ConvexPolygonShape2D> shape = tile_data->get_collision_polygon_shape(tile_set_physics_layer, polygon_index, shape_index, flip_h, flip_v, transpose);
914
915 // Translate the polygon.
916 Vector<Vector2> convex_polygon = shape->get_points();
917 for (int i = 0; i < convex_polygon.size(); i++) {
918 convex_polygon.set(i, convex_polygon[i] + tile_set->map_to_local(cell_data.coords) - quadrant_origin);
919 }
920
921 physics_quadrant->bodies[physics_body_key].polygons.push_back(convex_polygon);
922 }
923 }
924 }
925 }
926
927 // Iterate over the bodies
928 for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
929 // Actually merge the polygons.
930 Vector<Vector<Vector2>> out_polygons;
931 Vector<Vector<Vector2>> out_holes;
932 Geometry2D::merge_many_polygons(kvbody.value.polygons, out_polygons, out_holes);
933 // Create shapes for each polygon.
934 int body_shape_index = 0;
935 Vector<Vector<Vector2>> convex_polygons = Geometry2D::decompose_many_polygons_in_convex(out_polygons, out_holes);
936 for (Vector<Vector2> &convex_polygon : convex_polygons) {
937 Ref<ConvexPolygonShape2D> shape;
938 shape.instantiate();
939 shape->set_points(convex_polygon);
940 ps->body_add_shape(kvbody.value.body, shape->get_rid());
941 ps->body_set_shape_as_one_way_collision(kvbody.value.body, body_shape_index, kvbody.key.one_way_collision, kvbody.key.one_way_collision_margin);
942 physics_quadrant->shapes.push_back(shape);
943 body_shape_index++;
944 }
945 }
946 } else {
947 // Free the quadrant.
948 for (KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kv : physics_quadrant->bodies) {
949 RID &body = kv.value.body;
950 if (body.is_valid()) {
951 bodies_coords.erase(body);
952 ps->free_rid(body);
953 }
954 }
955 physics_quadrant->bodies.clear();
956 physics_quadrant->cells.clear();
957 physics_quadrant_map.erase(physics_quadrant->quadrant_coords);
958 }
959
960 quadrant_list_element = next_quadrant_list_element;
961 }
962
963 dirty_physics_quadrant_list.clear();
964
965 // Updates on physics changes.
966 if (dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES]) {
967 for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
968 Ref<PhysicsQuadrant> &physics_quadrant = kv.value;
969 for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
970 ps->body_set_mode(kvbody.value.body, use_kinematic_bodies ? PhysicsServer2D::BODY_MODE_KINEMATIC : PhysicsServer2D::BODY_MODE_STATIC);
971 }
972 }
973 }
974 }
975
976 // -----------
977 // Mark the physics state as up to date.
978 _physics_was_cleaned_up = forced_cleanup;
979 }
980
981 void TileMapLayer::_physics_quadrants_update_cell(CellData &r_cell_data, SelfList<PhysicsQuadrant>::List &r_dirty_physics_quadrant_list) {
982 // Check if the cell is valid and retrieve its y_sort_origin.
983 bool is_valid = false;
984 TileSetSource *source;
985 if (tile_set->has_source(r_cell_data.cell.source_id)) {
986 source = *tile_set->get_source(r_cell_data.cell.source_id);
987 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
988 if (atlas_source && atlas_source->has_tile(r_cell_data.cell.get_atlas_coords()) && atlas_source->has_alternative_tile(r_cell_data.cell.get_atlas_coords(), r_cell_data.cell.alternative_tile)) {
989 is_valid = true;
990 }
991 }
992
993 if (is_valid) {
994 // Get the quadrant coords.
995 const Vector2i &coords = r_cell_data.coords;
996 Vector2i quadrant_coords = _coords_to_quadrant_coords(coords, physics_quadrant_size);
997
998 Ref<PhysicsQuadrant> physics_quadrant;
999 if (physics_quadrant_map.has(quadrant_coords)) {
1000 // Reuse existing physics quadrant.
1001 physics_quadrant = physics_quadrant_map[quadrant_coords];
1002 } else {
1003 // Create a new physics quadrant.
1004 physics_quadrant.instantiate();
1005 physics_quadrant->quadrant_coords = quadrant_coords;
1006 physics_quadrant_map[quadrant_coords] = physics_quadrant;
1007 }
1008
1009 // Mark the old quadrant as dirty (if it exists).
1010 if (r_cell_data.physics_quadrant.is_valid()) {
1011 if (!r_cell_data.physics_quadrant->dirty_quadrant_list_element.in_list()) {
1012 r_dirty_physics_quadrant_list.add(&r_cell_data.physics_quadrant->dirty_quadrant_list_element);
1013 }
1014 }
1015
1016 // Remove the cell from that quadrant.
1017 if (r_cell_data.physics_quadrant_list_element.in_list()) {
1018 r_cell_data.physics_quadrant_list_element.remove_from_list();
1019 }
1020
1021 // Add the cell to its new quadrant.
1022 r_cell_data.physics_quadrant = physics_quadrant;
1023 r_cell_data.physics_quadrant->cells.add(&r_cell_data.physics_quadrant_list_element);
1024
1025 // Add the new quadrant to the dirty quadrant list.
1026 if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
1027 r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
1028 }
1029 } else {
1030 Ref<PhysicsQuadrant> physics_quadrant = r_cell_data.physics_quadrant;
1031
1032 // Remove the cell from its quadrant.
1033 r_cell_data.physics_quadrant = Ref<PhysicsQuadrant>();
1034 if (r_cell_data.physics_quadrant_list_element.in_list()) {
1035 physics_quadrant->cells.remove(&r_cell_data.physics_quadrant_list_element);
1036 }
1037
1038 if (physics_quadrant.is_valid()) {
1039 // Add the quadrant to the dirty quadrant list.
1040 if (!physics_quadrant->dirty_quadrant_list_element.in_list()) {
1041 r_dirty_physics_quadrant_list.add(&physics_quadrant->dirty_quadrant_list_element);
1042 }
1043 }
1044 }
1045 }
1046
1047 void TileMapLayer::_physics_notification(int p_what) {
1048 Transform2D gl_transform = get_global_transform();
1049 PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
1050
1051 switch (p_what) {
1052 case NOTIFICATION_TRANSFORM_CHANGED:
1053 // Move the collisison shapes along with the TileMap.
1054 if (is_inside_tree() && tile_set.is_valid()) {
1055 for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
1056 for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
1057 const RID &body = kvbody.value.body;
1058 Transform2D xform(0, tile_set->map_to_local(kv.key));
1059 xform = gl_transform * xform;
1060 ps->body_set_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM, xform);
1061 }
1062 }
1063 }
1064 break;
1065 case NOTIFICATION_ENTER_TREE:
1066 // Changes in the tree may cause the space to change (e.g. when reparenting to a SubViewport).
1067 if (is_inside_tree()) {
1068 RID space = get_world_2d()->get_space();
1069
1070 for (KeyValue<Vector2i, Ref<PhysicsQuadrant>> &kv : physics_quadrant_map) {
1071 for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : kv.value->bodies) {
1072 const RID &body = kvbody.value.body;
1073 ps->body_set_space(body, space);
1074 }
1075 }
1076 }
1077 }
1078 }
1079
1080 #ifdef DEBUG_ENABLED
1081 void TileMapLayer::_physics_draw_quadrant_debug(const RID &p_canvas_item, DebugQuadrant &r_debug_quadrant) {
1082 // Draw the debug collision shapes.
1083 ERR_FAIL_COND(tile_set.is_null());
1084
1085 if (!get_tree()) {
1086 return;
1087 }
1088
1089 bool show_collision = false;
1090 switch (collision_visibility_mode) {
1091 case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
1092 show_collision = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_collisions_hint();
1093 break;
1094 case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
1095 show_collision = false;
1096 break;
1097 case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
1098 show_collision = true;
1099 break;
1100 }
1101 if (!show_collision) {
1102 return;
1103 }
1104
1105 RenderingServer *rs = RenderingServer::get_singleton();
1106 PhysicsServer2D *ps = PhysicsServer2D::get_singleton();
1107
1108 const Color &debug_collision_color = get_tree()->get_debug_collisions_color();
1109
1110 RandomPCG rand;
1111 rand.seed(hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.y, hash_murmur3_one_real(r_debug_quadrant.quadrant_coords.x)));
1112
1113 // Create a mesh.
1114 if (!r_debug_quadrant.physics_mesh.is_valid()) {
1115 r_debug_quadrant.physics_mesh = rs->mesh_create();
1116 }
1117 rs->mesh_clear(r_debug_quadrant.physics_mesh);
1118
1119 // Redraw all shapes from the physics quadrants
1120 Rect2i covered_cell_area = Rect2i(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE, Vector2i(TILE_MAP_DEBUG_QUADRANT_SIZE, TILE_MAP_DEBUG_QUADRANT_SIZE));
1121 Vector2i first_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_position() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
1122 Vector2i last_physics_quadrant_coords = _coords_to_quadrant_coords(covered_cell_area.get_end() - Vector2i(1, 1), physics_quadrant_size) + Vector2i(1, 1);
1123
1124 LocalVector<Vector2> face_vertex_array;
1125 LocalVector<Color> face_color_array;
1126 LocalVector<int32_t> face_index_array;
1127
1128 LocalVector<Vector2> line_vertex_array;
1129 LocalVector<Color> line_color_array;
1130
1131 AHashMap<Vector2, int> vertex_map;
1132
1133 // Arrays to generate a mesh.
1134 for (int x = first_physics_quadrant_coords.x; x < last_physics_quadrant_coords.x; x++) {
1135 for (int y = first_physics_quadrant_coords.y; y < last_physics_quadrant_coords.y; y++) {
1136 const Vector2i physics_quadrant_coords = Vector2i(x, y);
1137 if (!physics_quadrant_map.has(physics_quadrant_coords)) {
1138 continue;
1139 }
1140 r_debug_quadrant.drawn_to = true;
1141 Ref<PhysicsQuadrant> physics_quadrant = physics_quadrant_map[physics_quadrant_coords];
1142
1143 const Vector2 debug_quadrant_pos = tile_set->map_to_local(r_debug_quadrant.quadrant_coords * TILE_MAP_DEBUG_QUADRANT_SIZE);
1144 Transform2D global_to_debug_quadrant = (get_global_transform() * Transform2D(0, debug_quadrant_pos)).affine_inverse();
1145
1146 // Clear arrays for new quadrant while keeping allocated memory.
1147
1148 face_vertex_array.clear();
1149 face_color_array.clear();
1150 face_index_array.clear();
1151
1152 line_vertex_array.clear();
1153 line_color_array.clear();
1154
1155 vertex_map.clear();
1156
1157 for (const KeyValue<PhysicsQuadrant::PhysicsBodyKey, PhysicsQuadrant::PhysicsBodyValue> &kvbody : physics_quadrant->bodies) {
1158 const RID &body = kvbody.value.body;
1159 int shape_count = ps->body_get_shape_count(body);
1160 if (shape_count == 0) {
1161 continue;
1162 }
1163 const Transform2D body_to_quadrant = global_to_debug_quadrant * Transform2D(ps->body_get_state(body, PhysicsServer2D::BODY_STATE_TRANSFORM));
1164
1165 Color face_random_variation_color;
1166 face_random_variation_color.set_hsv(
1167 debug_collision_color.get_h() + rand.random(-1.0, 1.0) * 0.05,
1168 debug_collision_color.get_s(),
1169 debug_collision_color.get_v() + rand.random(-1.0, 1.0) * 0.1,
1170 debug_collision_color.a);
1171 const Color line_random_variation_color = face_random_variation_color.lightened(0.2);
1172
1173 for (int shape_index = 0; shape_index < shape_count; shape_index++) {
1174 const RID &shape = ps->body_get_shape(body, shape_index);
1175 const Transform2D &shape_xform = ps->body_get_shape_transform(body, shape_index);
1176 const PhysicsServer2D::ShapeType &type = ps->shape_get_type(shape);
1177
1178 if (type == PhysicsServer2D::SHAPE_CONVEX_POLYGON) {
1179 PackedVector2Array outline = ps->shape_get_data(shape);
1180 const int outline_size = outline.size();
1181 if (outline_size < 3) {
1182 continue;
1183 }
1184
1185 const Transform2D outline_xform = body_to_quadrant * shape_xform;
1186
1187 // Adds debug mesh lines.
1188
1189 Vector2 previous_line_vertex = outline_xform.xform(outline[outline_size - 1]);
1190
1191 for (int i = 0; i < outline_size; i++) {
1192 Vector2 line_vertex = outline_xform.xform(outline[i]);
1193
1194 line_vertex_array.push_back(previous_line_vertex);
1195 line_vertex_array.push_back(line_vertex);
1196
1197 previous_line_vertex = line_vertex;
1198
1199 line_color_array.push_back(line_random_variation_color);
1200 line_color_array.push_back(line_random_variation_color);
1201 }
1202
1203 // Adds debug mesh faces.
1204
1205 const Vector2 vertex1 = outline_xform.xform(outline[0]);
1206 const Vector2 vertex2 = outline_xform.xform(outline[1]);
1207 Vector2 vertex3;
1208
1209 int vertex1_index = -1;
1210 int vertex2_index = -1;
1211 int vertex3_index = -1;
1212
1213 int last_vertex3_index = -1;
1214
1215 // Find triangle fan anchor vertex1 index.
1216 {
1217 AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex1);
1218 if (!E) {
1219 E = vertex_map.insert(vertex1, vertex_map.size());
1220 face_vertex_array.push_back(vertex1);
1221 face_color_array.push_back(face_random_variation_color);
1222 }
1223 vertex1_index = E->value;
1224 }
1225
1226 // Find starting vertex2 index.
1227 {
1228 AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex2);
1229 if (!E) {
1230 E = vertex_map.insert(vertex2, vertex_map.size());
1231 face_vertex_array.push_back(vertex2);
1232 face_color_array.push_back(face_random_variation_color);
1233 }
1234 vertex2_index = E->value;
1235 }
1236
1237 // Create mesh triangle face fan from outline vertices using vertex_map indices.
1238 for (int i = 1; i < outline_size - 1; i++) {
1239 if (i > 1) {
1240 vertex2_index = last_vertex3_index;
1241 }
1242
1243 vertex3 = outline_xform.xform(outline[i + 1]);
1244
1245 {
1246 AHashMap<Vector2, int>::Iterator E = vertex_map.find(vertex3);
1247 if (!E) {
1248 E = vertex_map.insert(vertex3, vertex_map.size());
1249 face_vertex_array.push_back(vertex3);
1250 face_color_array.push_back(face_random_variation_color);
1251 }
1252 vertex3_index = E->value;
1253 last_vertex3_index = vertex3_index;
1254 }
1255
1256 face_index_array.push_back(vertex1_index);
1257 face_index_array.push_back(vertex2_index);
1258 face_index_array.push_back(vertex3_index);
1259 }
1260
1261 } else {
1262 WARN_PRINT("Wrong shape type for a tile, should be SHAPE_CONVEX_POLYGON.");
1263 }
1264 }
1265 }
1266
1267 if (face_index_array.size() > 2) {
1268 Array face_mesh_array;
1269 face_mesh_array.resize(RS::ARRAY_MAX);
1270 face_mesh_array[RS::ARRAY_VERTEX] = Vector<Vector2>(face_vertex_array);
1271 face_mesh_array[RS::ARRAY_INDEX] = Vector<int32_t>(face_index_array);
1272 face_mesh_array[RS::ARRAY_COLOR] = Vector<Color>(face_color_array);
1273 rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_TRIANGLES, face_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
1274
1275 Array line_mesh_array;
1276 line_mesh_array.resize(RS::ARRAY_MAX);
1277 line_mesh_array[RS::ARRAY_VERTEX] = Vector<Vector2>(line_vertex_array);
1278 line_mesh_array[RS::ARRAY_COLOR] = Vector<Color>(line_color_array);
1279
1280 rs->mesh_add_surface_from_arrays(r_debug_quadrant.physics_mesh, RS::PRIMITIVE_LINES, line_mesh_array, Array(), Dictionary(), RS::ARRAY_FLAG_USE_2D_VERTICES);
1281 }
1282 }
1283 }
1284 rs->canvas_item_add_mesh(p_canvas_item, r_debug_quadrant.physics_mesh, Transform2D());
1285 }
1286 #endif // DEBUG_ENABLED
1287 #endif // PHYSICS_2D_DISABLED
1288
1289 #ifndef NAVIGATION_2D_DISABLED
1290 /////////////////////////////// Navigation //////////////////////////////////////
1291
1292 void TileMapLayer::_navigation_update(bool p_force_cleanup) {
1293 ERR_FAIL_NULL(NavigationServer2D::get_singleton());
1294 NavigationServer2D *ns = NavigationServer2D::get_singleton();
1295
1296 // Check if we should cleanup everything.
1297 bool forced_cleanup = p_force_cleanup || !enabled || !navigation_enabled || !is_inside_tree() || tile_set.is_null();
1298 if (forced_cleanup && _navigation_was_cleaned_up) {
1299 return;
1300 }
1301
1302 // ----------- Layer level processing -----------
1303 // All this processing is kept for compatibility with the TileMap node.
1304 // Otherwise, layers shall use the World2D navigation map or define a custom one with set_navigation_map(...).
1305 if (tile_map_node) {
1306 if (forced_cleanup) {
1307 if (navigation_map_override.is_valid()) {
1308 ns->free_rid(navigation_map_override);
1309 navigation_map_override = RID();
1310 }
1311 } else {
1312 // Update navigation maps.
1313 if (!navigation_map_override.is_valid()) {
1314 if (layer_index_in_tile_map_node > 0) {
1315 // Create a dedicated map for each layer.
1316 RID new_layer_map = ns->map_create();
1317 // Set the default NavigationPolygon cell_size on the new map as a mismatch causes an error.
1318 ns->map_set_cell_size(new_layer_map, NavigationDefaults2D::NAV_MESH_CELL_SIZE);
1319 ns->map_set_active(new_layer_map, true);
1320 navigation_map_override = new_layer_map;
1321 }
1322 }
1323 }
1324 }
1325
1326 // ----------- Navigation regions processing -----------
1327 if (forced_cleanup) {
1328 // Clean everything.
1329 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
1330 _navigation_clear_cell(kv.value);
1331 }
1332 } else {
1333 if (_navigation_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP]) {
1334 // Update all cells.
1335 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
1336 _navigation_update_cell(kv.value);
1337 }
1338 } else {
1339 // Update dirty cells.
1340 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
1341 CellData &cell_data = *cell_data_list_element->self();
1342 _navigation_update_cell(cell_data);
1343 }
1344 }
1345 }
1346
1347 // -----------
1348 // Mark the navigation state as up to date.
1349 _navigation_was_cleaned_up = forced_cleanup;
1350 }
1351
1352 void TileMapLayer::_navigation_notification(int p_what) {
1353 if (p_what == NOTIFICATION_TRANSFORM_CHANGED) {
1354 if (tile_set.is_valid()) {
1355 Transform2D tilemap_xform = get_global_transform();
1356 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
1357 const CellData &cell_data = kv.value;
1358 // Update navigation regions transform.
1359 for (const RID &region : cell_data.navigation_regions) {
1360 if (!region.is_valid()) {
1361 continue;
1362 }
1363 Transform2D tile_transform;
1364 tile_transform.set_origin(tile_set->map_to_local(kv.key));
1365 NavigationServer2D::get_singleton()->region_set_transform(region, tilemap_xform * tile_transform);
1366 }
1367 }
1368 }
1369 }
1370 }
1371
1372 void TileMapLayer::_navigation_clear_cell(CellData &r_cell_data) {
1373 NavigationServer2D *ns = NavigationServer2D::get_singleton();
1374 // Clear navigation shapes.
1375 for (uint32_t i = 0; i < r_cell_data.navigation_regions.size(); i++) {
1376 const RID &region = r_cell_data.navigation_regions[i];
1377 if (region.is_valid()) {
1378 ns->region_set_map(region, RID());
1379 ns->free_rid(region);
1380 }
1381 }
1382 r_cell_data.navigation_regions.clear();
1383 }
1384
1385 void TileMapLayer::_navigation_update_cell(CellData &r_cell_data) {
1386 NavigationServer2D *ns = NavigationServer2D::get_singleton();
1387 Transform2D gl_xform = get_global_transform();
1388 RID navigation_map = navigation_map_override.is_valid() ? navigation_map_override : get_world_2d()->get_navigation_map();
1389 ERR_FAIL_COND(navigation_map.is_null());
1390
1391 // Get the navigation polygons and create regions.
1392 TileMapCell &c = r_cell_data.cell;
1393
1394 TileSetSource *source;
1395 if (tile_set->has_source(c.source_id)) {
1396 source = *tile_set->get_source(c.source_id);
1397
1398 if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
1399 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
1400 if (atlas_source) {
1401 const TileData *tile_data;
1402 if (r_cell_data.runtime_tile_data_cache) {
1403 tile_data = r_cell_data.runtime_tile_data_cache;
1404 } else {
1405 tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
1406 }
1407
1408 // Transform flags.
1409 bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
1410 bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
1411 bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
1412
1413 // Free unused regions then resize the regions array.
1414 for (uint32_t i = tile_set->get_navigation_layers_count(); i < r_cell_data.navigation_regions.size(); i++) {
1415 RID &region = r_cell_data.navigation_regions[i];
1416 if (region.is_valid()) {
1417 ns->region_set_map(region, RID());
1418 ns->free_rid(region);
1419 region = RID();
1420 }
1421 }
1422 r_cell_data.navigation_regions.resize(tile_set->get_navigation_layers_count());
1423
1424 // Create, update or clear regions.
1425 for (uint32_t navigation_layer_index = 0; navigation_layer_index < r_cell_data.navigation_regions.size(); navigation_layer_index++) {
1426 Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer_index, flip_h, flip_v, transpose);
1427
1428 RID &region = r_cell_data.navigation_regions[navigation_layer_index];
1429
1430 if (navigation_polygon.is_valid() && (navigation_polygon->get_polygon_count() > 0 || navigation_polygon->get_outline_count() > 0)) {
1431 // Create or update regions.
1432 Transform2D tile_transform;
1433 tile_transform.set_origin(tile_set->map_to_local(r_cell_data.coords));
1434 if (!region.is_valid()) {
1435 region = ns->region_create();
1436 }
1437 ns->region_set_owner_id(region, tile_map_node ? tile_map_node->get_instance_id() : get_instance_id());
1438 ns->region_set_map(region, navigation_map);
1439 ns->region_set_transform(region, gl_xform * tile_transform);
1440 ns->region_set_navigation_layers(region, tile_set->get_navigation_layer_layers(navigation_layer_index));
1441 ns->region_set_navigation_polygon(region, navigation_polygon);
1442 } else {
1443 // Clear region.
1444 if (region.is_valid()) {
1445 ns->region_set_map(region, RID());
1446 ns->free_rid(region);
1447 region = RID();
1448 }
1449 }
1450 }
1451
1452 return;
1453 }
1454 }
1455 }
1456
1457 // If we did not return earlier, clear the cell.
1458 _navigation_clear_cell(r_cell_data);
1459 }
1460
1461 #ifdef DEBUG_ENABLED
1462 void TileMapLayer::_navigation_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
1463 // Draw the debug collision shapes.
1464 bool show_navigation = false;
1465 switch (navigation_visibility_mode) {
1466 case TileMapLayer::DEBUG_VISIBILITY_MODE_DEFAULT:
1467 show_navigation = !Engine::get_singleton()->is_editor_hint() && get_tree()->is_debugging_navigation_hint();
1468 break;
1469 case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_HIDE:
1470 show_navigation = false;
1471 break;
1472 case TileMapLayer::DEBUG_VISIBILITY_MODE_FORCE_SHOW:
1473 show_navigation = true;
1474 break;
1475 }
1476 if (!show_navigation) {
1477 return;
1478 }
1479
1480 // Check if the navigation is used.
1481 if (r_cell_data.navigation_regions.is_empty()) {
1482 return;
1483 }
1484
1485 RenderingServer *rs = RenderingServer::get_singleton();
1486 const NavigationServer2D *ns2d = NavigationServer2D::get_singleton();
1487
1488 bool enabled_geometry_face_random_color = ns2d->get_debug_navigation_enable_geometry_face_random_color();
1489 bool enabled_edge_lines = ns2d->get_debug_navigation_enable_edge_lines();
1490
1491 Color debug_face_color = ns2d->get_debug_navigation_geometry_face_color();
1492 Color debug_edge_color = ns2d->get_debug_navigation_geometry_edge_color();
1493
1494 RandomPCG rand;
1495
1496 const TileMapCell &c = r_cell_data.cell;
1497
1498 TileSetSource *source;
1499 if (tile_set->has_source(c.source_id)) {
1500 source = *tile_set->get_source(c.source_id);
1501
1502 if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
1503 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
1504 if (atlas_source) {
1505 const TileData *tile_data;
1506 if (r_cell_data.runtime_tile_data_cache) {
1507 tile_data = r_cell_data.runtime_tile_data_cache;
1508 } else {
1509 tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
1510 }
1511
1512 Transform2D cell_to_quadrant;
1513 cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
1514 rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
1515
1516 for (int layer_index = 0; layer_index < tile_set->get_navigation_layers_count(); layer_index++) {
1517 bool flip_h = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
1518 bool flip_v = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
1519 bool transpose = (c.alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
1520 Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(layer_index, flip_h, flip_v, transpose);
1521 if (navigation_polygon.is_valid()) {
1522 Vector<Vector2> navigation_polygon_vertices = navigation_polygon->get_vertices();
1523 if (navigation_polygon_vertices.size() < 3) {
1524 continue;
1525 }
1526
1527 for (int i = 0; i < navigation_polygon->get_polygon_count(); i++) {
1528 // An array of vertices for this polygon.
1529 Vector<int> polygon = navigation_polygon->get_polygon(i);
1530 Vector<Vector2> debug_polygon_vertices;
1531 debug_polygon_vertices.resize(polygon.size());
1532 for (int j = 0; j < polygon.size(); j++) {
1533 ERR_FAIL_INDEX(polygon[j], navigation_polygon_vertices.size());
1534 debug_polygon_vertices.write[j] = navigation_polygon_vertices[polygon[j]];
1535 }
1536
1537 // Generate the polygon color, slightly randomly modified from the settings one.
1538 Color random_variation_color = debug_face_color;
1539 if (enabled_geometry_face_random_color) {
1540 random_variation_color.set_hsv(
1541 debug_face_color.get_h() + rand.random(-1.0, 1.0) * 0.1,
1542 debug_face_color.get_s(),
1543 debug_face_color.get_v() + rand.random(-1.0, 1.0) * 0.2);
1544 }
1545 random_variation_color.a = debug_face_color.a;
1546
1547 Vector<Color> debug_face_colors;
1548 debug_face_colors.push_back(random_variation_color);
1549 rs->canvas_item_add_polygon(p_canvas_item, debug_polygon_vertices, debug_face_colors);
1550
1551 if (enabled_edge_lines) {
1552 Vector<Color> debug_edge_colors;
1553 debug_edge_colors.push_back(debug_edge_color);
1554 debug_polygon_vertices.push_back(debug_polygon_vertices[0]); // Add first again for closing polyline.
1555 rs->canvas_item_add_polyline(p_canvas_item, debug_polygon_vertices, debug_edge_colors);
1556 }
1557 }
1558 }
1559 }
1560 }
1561 }
1562 }
1563 }
1564 #endif // DEBUG_ENABLED
1565 #endif // NAVIGATION_2D_DISABLED
1566
1567 /////////////////////////////// Scenes //////////////////////////////////////
1568
1569 void TileMapLayer::_scenes_update(bool p_force_cleanup) {
1570 // Check if we should cleanup everything.
1571 bool forced_cleanup = p_force_cleanup || !enabled || !is_inside_tree() || tile_set.is_null();
1572 if (forced_cleanup && _scenes_was_cleaned_up) {
1573 return;
1574 }
1575
1576 if (forced_cleanup) {
1577 // Clean everything.
1578 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
1579 _scenes_clear_cell(kv.value);
1580 }
1581 } else {
1582 if (_scenes_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET] || dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] || dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE]) {
1583 // Update all cells.
1584 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
1585 _scenes_update_cell(kv.value);
1586 }
1587 } else {
1588 // Update dirty cells.
1589 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
1590 CellData &cell_data = *cell_data_list_element->self();
1591 _scenes_update_cell(cell_data);
1592 }
1593 }
1594 }
1595
1596 // -----------
1597 // Mark the scenes state as up to date.
1598 _scenes_was_cleaned_up = forced_cleanup;
1599 }
1600
1601 void TileMapLayer::_scenes_clear_cell(CellData &r_cell_data) {
1602 // Cleanup existing scene.
1603 Node *node = nullptr;
1604 if (tile_map_node) {
1605 // Compatibility with TileMap.
1606 node = tile_map_node->get_node_or_null(r_cell_data.scene);
1607 } else {
1608 node = get_node_or_null(r_cell_data.scene);
1609 }
1610 if (node) {
1611 node->queue_free();
1612 }
1613 r_cell_data.scene = "";
1614 }
1615
1616 void TileMapLayer::_scenes_update_cell(CellData &r_cell_data) {
1617 // Clear the scene in any case.
1618 _scenes_clear_cell(r_cell_data);
1619
1620 // Create the scene.
1621 const TileMapCell &c = r_cell_data.cell;
1622
1623 TileSetSource *source;
1624 if (tile_set->has_source(c.source_id)) {
1625 source = *tile_set->get_source(c.source_id);
1626
1627 if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
1628 TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
1629 if (scenes_collection_source) {
1630 Ref<PackedScene> packed_scene = scenes_collection_source->get_scene_tile_scene(c.alternative_tile);
1631 if (packed_scene.is_valid()) {
1632 Node *scene = packed_scene->instantiate();
1633 Control *scene_as_control = Object::cast_to<Control>(scene);
1634 Node2D *scene_as_node2d = Object::cast_to<Node2D>(scene);
1635 if (scene_as_control) {
1636 scene_as_control->set_position(tile_set->map_to_local(r_cell_data.coords) + scene_as_control->get_position());
1637 } else if (scene_as_node2d) {
1638 _set_scene_transform_with_alternative(scene_as_node2d, tile_set->map_to_local(r_cell_data.coords), c.alternative_tile);
1639 }
1640 #ifdef TOOLS_ENABLED
1641 RenderingServer *rs = RenderingServer::get_singleton();
1642 CanvasItem *scene_as_ci = Object::cast_to<CanvasItem>(scene);
1643 if (scene_as_ci) {
1644 rs->canvas_item_set_modulate(scene_as_ci->get_canvas_item(), _highlight_color(scene_as_ci->get_modulate()));
1645 }
1646 #endif // TOOLS_ENABLED
1647 if (tile_map_node) {
1648 // Compatibility with TileMap.
1649 tile_map_node->add_child(scene);
1650 } else {
1651 add_child(scene);
1652 }
1653 r_cell_data.scene = scene->get_name();
1654 }
1655 }
1656 }
1657 }
1658 }
1659
1660 #ifdef DEBUG_ENABLED
1661 void TileMapLayer::_scenes_draw_cell_debug(const RID &p_canvas_item, const Vector2 &p_quadrant_pos, const CellData &r_cell_data) {
1662 ERR_FAIL_COND(tile_set.is_null());
1663
1664 if (!Engine::get_singleton()->is_editor_hint()) {
1665 return;
1666 }
1667
1668 // Draw a placeholder for scenes needing one.
1669 RenderingServer *rs = RenderingServer::get_singleton();
1670
1671 const TileMapCell &c = r_cell_data.cell;
1672
1673 TileSetSource *source;
1674 if (tile_set->has_source(c.source_id)) {
1675 source = *tile_set->get_source(c.source_id);
1676
1677 if (!source->has_tile(c.get_atlas_coords()) || !source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
1678 return;
1679 }
1680
1681 TileSetScenesCollectionSource *scenes_collection_source = Object::cast_to<TileSetScenesCollectionSource>(source);
1682 if (scenes_collection_source) {
1683 if (scenes_collection_source->get_scene_tile_scene(c.alternative_tile).is_null() || scenes_collection_source->get_scene_tile_display_placeholder(c.alternative_tile)) {
1684 // Generate a random color from the hashed values of the tiles.
1685 Array to_hash = { c.source_id, c.alternative_tile };
1686 uint32_t hash = RandomPCG(to_hash.hash()).rand();
1687
1688 Color color;
1689 color = color.from_hsv(
1690 (float)((hash >> 24) & 0xFF) / 256.0,
1691 Math::lerp(0.5, 1.0, (float)((hash >> 16) & 0xFF) / 256.0),
1692 Math::lerp(0.5, 1.0, (float)((hash >> 8) & 0xFF) / 256.0),
1693 0.8);
1694
1695 // Draw a placeholder tile.
1696 Transform2D cell_to_quadrant;
1697 cell_to_quadrant.set_origin(tile_set->map_to_local(r_cell_data.coords) - p_quadrant_pos);
1698 rs->canvas_item_add_set_transform(p_canvas_item, cell_to_quadrant);
1699 rs->canvas_item_add_circle(p_canvas_item, Vector2(), MIN(tile_set->get_tile_size().x, tile_set->get_tile_size().y) / 4.0, color);
1700 }
1701 }
1702 }
1703 }
1704 #endif // DEBUG_ENABLED
1705
1706 void TileMapLayer::_set_scene_transform_with_alternative(Node2D *p_scene, const Vector2 &p_cell_position, const int p_alternative_id) {
1707 // Determine the transformations based on the alternative ID.
1708 bool transform_flip_h = p_alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_H;
1709 bool transform_flip_v = p_alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_V;
1710 bool transform_transpose = p_alternative_id & TileSetAtlasSource::TRANSFORM_TRANSPOSE;
1711
1712 int axis_h = transform_transpose ? 1 : 0;
1713 int axis_v = 1 - axis_h;
1714
1715 Transform2D xform;
1716 xform[axis_h].x = transform_flip_h ? -1.0f : 1.0f;
1717 xform[axis_h].y = 0.0f;
1718 xform[axis_v].x = 0.0f;
1719 xform[axis_v].y = transform_flip_v ? -1.0f : 1.0f;
1720 xform.set_origin(p_cell_position);
1721
1722 p_scene->set_transform(xform * p_scene->get_transform());
1723 }
1724
1725 /////////////////////////////////////////////////////////////////////
1726
1727 void TileMapLayer::_build_runtime_update_tile_data(bool p_force_cleanup) {
1728 // Check if we should cleanup everything.
1729 bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
1730 if (!forced_cleanup) {
1731 bool valid_runtime_update = GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update);
1732 bool valid_runtime_update_for_tilemap = tile_map_node && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_use_tile_data_runtime_update) && tile_map_node->GDVIRTUAL_IS_OVERRIDDEN(_tile_data_runtime_update); // For keeping compatibility.
1733 if (valid_runtime_update || valid_runtime_update_for_tilemap) {
1734 bool use_tilemap_for_runtime = valid_runtime_update_for_tilemap && !valid_runtime_update;
1735 if (_runtime_update_tile_data_was_cleaned_up || dirty.flags[DIRTY_FLAGS_TILE_SET]) {
1736 _runtime_update_needs_all_cells_cleaned_up = true;
1737 for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
1738 _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime);
1739 }
1740 } else if (dirty.flags[DIRTY_FLAGS_LAYER_RUNTIME_UPDATE]) {
1741 for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
1742 _build_runtime_update_tile_data_for_cell(E.value, use_tilemap_for_runtime, true);
1743 }
1744 } else {
1745 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
1746 CellData &cell_data = *cell_data_list_element->self();
1747 _build_runtime_update_tile_data_for_cell(cell_data, use_tilemap_for_runtime);
1748 }
1749 }
1750 }
1751 }
1752
1753 // -----------
1754 // Mark the tile data state as up to date.
1755 _runtime_update_tile_data_was_cleaned_up = forced_cleanup;
1756 }
1757
1758 void TileMapLayer::_build_runtime_update_tile_data_for_cell(CellData &r_cell_data, bool p_use_tilemap_for_runtime, bool p_auto_add_to_dirty_list) {
1759 TileMapCell &c = r_cell_data.cell;
1760 TileSetSource *source;
1761 if (tile_set->has_source(c.source_id)) {
1762 source = *tile_set->get_source(c.source_id);
1763
1764 if (source->has_tile(c.get_atlas_coords()) && source->has_alternative_tile(c.get_atlas_coords(), c.alternative_tile)) {
1765 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
1766 if (atlas_source) {
1767 bool ret = false;
1768
1769 if (p_use_tilemap_for_runtime) {
1770 // Compatibility with TileMap.
1771 if (tile_map_node->GDVIRTUAL_CALL(_use_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, ret) && ret) {
1772 TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
1773
1774 // Create the runtime TileData.
1775 TileData *tile_data_runtime_use = tile_data->duplicate();
1776 tile_data_runtime_use->set_allow_transform(true);
1777 r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
1778
1779 tile_map_node->GDVIRTUAL_CALL(_tile_data_runtime_update, layer_index_in_tile_map_node, r_cell_data.coords, tile_data_runtime_use);
1780
1781 if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
1782 dirty.cell_list.add(&r_cell_data.dirty_list_element);
1783 }
1784 }
1785 } else {
1786 if (GDVIRTUAL_CALL(_use_tile_data_runtime_update, r_cell_data.coords, ret) && ret) {
1787 TileData *tile_data = atlas_source->get_tile_data(c.get_atlas_coords(), c.alternative_tile);
1788
1789 // Create the runtime TileData.
1790 TileData *tile_data_runtime_use = tile_data->duplicate();
1791 tile_data_runtime_use->set_allow_transform(true);
1792 r_cell_data.runtime_tile_data_cache = tile_data_runtime_use;
1793
1794 GDVIRTUAL_CALL(_tile_data_runtime_update, r_cell_data.coords, tile_data_runtime_use);
1795
1796 if (p_auto_add_to_dirty_list && !r_cell_data.dirty_list_element.in_list()) {
1797 dirty.cell_list.add(&r_cell_data.dirty_list_element);
1798 }
1799 }
1800 }
1801 }
1802 }
1803 }
1804 }
1805
1806 void TileMapLayer::_clear_runtime_update_tile_data() {
1807 if (_runtime_update_needs_all_cells_cleaned_up) {
1808 for (KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
1809 _clear_runtime_update_tile_data_for_cell(E.value);
1810 }
1811 _runtime_update_needs_all_cells_cleaned_up = false;
1812 } else {
1813 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
1814 CellData &r_cell_data = *cell_data_list_element->self();
1815 _clear_runtime_update_tile_data_for_cell(r_cell_data);
1816 }
1817 }
1818 }
1819
1820 void TileMapLayer::_clear_runtime_update_tile_data_for_cell(CellData &r_cell_data) {
1821 // Clear the runtime tile data.
1822 if (r_cell_data.runtime_tile_data_cache) {
1823 memdelete(r_cell_data.runtime_tile_data_cache);
1824 r_cell_data.runtime_tile_data_cache = nullptr;
1825 }
1826 }
1827
1828 void TileMapLayer::_update_cells_callback(bool p_force_cleanup) {
1829 if (!GDVIRTUAL_IS_OVERRIDDEN(_update_cells)) {
1830 return;
1831 }
1832
1833 // Check if we should cleanup everything.
1834 bool forced_cleanup = p_force_cleanup || !enabled || tile_set.is_null() || !is_visible_in_tree();
1835
1836 // List all the dirty cell's positions to notify script of cell updates.
1837 TypedArray<Vector2i> dirty_cell_positions;
1838 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
1839 CellData &cell_data = *cell_data_list_element->self();
1840 dirty_cell_positions.push_back(cell_data.coords);
1841 }
1842
1843 GDVIRTUAL_CALL(_update_cells, dirty_cell_positions, forced_cleanup);
1844 }
1845
1846 TileSet::TerrainsPattern TileMapLayer::_get_best_terrain_pattern_for_constraints(int p_terrain_set, const Vector2i &p_position, const RBSet<TerrainConstraint> &p_constraints, TileSet::TerrainsPattern p_current_pattern) const {
1847 if (tile_set.is_null()) {
1848 return TileSet::TerrainsPattern();
1849 }
1850 // Returns all tiles compatible with the given constraints.
1851 RBMap<TileSet::TerrainsPattern, int> terrain_pattern_score;
1852 RBSet<TileSet::TerrainsPattern> pattern_set = tile_set->get_terrains_pattern_set(p_terrain_set);
1853 ERR_FAIL_COND_V(pattern_set.is_empty(), TileSet::TerrainsPattern());
1854 for (TileSet::TerrainsPattern &terrain_pattern : pattern_set) {
1855 int score = 0;
1856
1857 // Check the center bit constraint.
1858 TerrainConstraint terrain_constraint = TerrainConstraint(tile_set, p_position, terrain_pattern.get_terrain());
1859 const RBSet<TerrainConstraint>::Element *in_set_constraint_element = p_constraints.find(terrain_constraint);
1860 if (in_set_constraint_element) {
1861 if (in_set_constraint_element->get().get_terrain() != terrain_constraint.get_terrain()) {
1862 score += in_set_constraint_element->get().get_priority();
1863 }
1864 } else if (p_current_pattern.get_terrain() != terrain_pattern.get_terrain()) {
1865 continue; // Ignore a pattern that cannot keep bits without constraints unmodified.
1866 }
1867
1868 // Check the surrounding bits
1869 bool invalid_pattern = false;
1870 for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
1871 TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
1872 if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
1873 // Check if the bit is compatible with the constraints.
1874 TerrainConstraint terrain_bit_constraint = TerrainConstraint(tile_set, p_position, bit, terrain_pattern.get_terrain_peering_bit(bit));
1875 in_set_constraint_element = p_constraints.find(terrain_bit_constraint);
1876 if (in_set_constraint_element) {
1877 if (in_set_constraint_element->get().get_terrain() != terrain_bit_constraint.get_terrain()) {
1878 score += in_set_constraint_element->get().get_priority();
1879 }
1880 } else if (p_current_pattern.get_terrain_peering_bit(bit) != terrain_pattern.get_terrain_peering_bit(bit)) {
1881 invalid_pattern = true; // Ignore a pattern that cannot keep bits without constraints unmodified.
1882 break;
1883 }
1884 }
1885 }
1886 if (invalid_pattern) {
1887 continue;
1888 }
1889
1890 terrain_pattern_score[terrain_pattern] = score;
1891 }
1892
1893 // Compute the minimum score.
1894 TileSet::TerrainsPattern min_score_pattern = p_current_pattern;
1895 int min_score = INT32_MAX;
1896 for (KeyValue<TileSet::TerrainsPattern, int> E : terrain_pattern_score) {
1897 if (E.value < min_score) {
1898 min_score_pattern = E.key;
1899 min_score = E.value;
1900 }
1901 }
1902
1903 return min_score_pattern;
1904 }
1905
1906 RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_added_pattern(const Vector2i &p_position, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern) const {
1907 if (tile_set.is_null()) {
1908 return RBSet<TerrainConstraint>();
1909 }
1910
1911 // Compute the constraints needed from the surrounding tiles.
1912 RBSet<TerrainConstraint> output;
1913 output.insert(TerrainConstraint(tile_set, p_position, p_terrains_pattern.get_terrain()));
1914
1915 for (uint32_t i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) {
1916 TileSet::CellNeighbor side = TileSet::CellNeighbor(i);
1917 if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, side)) {
1918 TerrainConstraint c = TerrainConstraint(tile_set, p_position, side, p_terrains_pattern.get_terrain_peering_bit(side));
1919 output.insert(c);
1920 }
1921 }
1922
1923 return output;
1924 }
1925
1926 RBSet<TerrainConstraint> TileMapLayer::_get_terrain_constraints_from_painted_cells_list(const RBSet<Vector2i> &p_painted, int p_terrain_set, bool p_ignore_empty_terrains) const {
1927 if (tile_set.is_null()) {
1928 return RBSet<TerrainConstraint>();
1929 }
1930
1931 ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), RBSet<TerrainConstraint>());
1932
1933 // Build a set of dummy constraints to get the constrained points.
1934 RBSet<TerrainConstraint> dummy_constraints;
1935 for (const Vector2i &E : p_painted) {
1936 for (int i = 0; i < TileSet::CELL_NEIGHBOR_MAX; i++) { // Iterates over neighbor bits.
1937 TileSet::CellNeighbor bit = TileSet::CellNeighbor(i);
1938 if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
1939 dummy_constraints.insert(TerrainConstraint(tile_set, E, bit, -1));
1940 }
1941 }
1942 }
1943
1944 // For each constrained point, we get all overlapping tiles, and select the most adequate terrain for it.
1945 RBSet<TerrainConstraint> constraints;
1946 for (const TerrainConstraint &E_constraint : dummy_constraints) {
1947 HashMap<int, int> terrain_count;
1948
1949 // Count the number of occurrences per terrain.
1950 HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = E_constraint.get_overlapping_coords_and_peering_bits();
1951 for (const KeyValue<Vector2i, TileSet::CellNeighbor> &E_overlapping : overlapping_terrain_bits) {
1952 TileData *neighbor_tile_data = nullptr;
1953 TileMapCell neighbor_cell = get_cell(E_overlapping.key);
1954 if (neighbor_cell.source_id != TileSet::INVALID_SOURCE) {
1955 Ref<TileSetSource> source = tile_set->get_source(neighbor_cell.source_id);
1956 Ref<TileSetAtlasSource> atlas_source = source;
1957 if (atlas_source.is_valid()) {
1958 TileData *tile_data = atlas_source->get_tile_data(neighbor_cell.get_atlas_coords(), neighbor_cell.alternative_tile);
1959 if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
1960 neighbor_tile_data = tile_data;
1961 }
1962 }
1963 }
1964
1965 int terrain = neighbor_tile_data ? neighbor_tile_data->get_terrain_peering_bit(TileSet::CellNeighbor(E_overlapping.value)) : -1;
1966 if (!p_ignore_empty_terrains || terrain >= 0) {
1967 if (!terrain_count.has(terrain)) {
1968 terrain_count[terrain] = 0;
1969 }
1970 terrain_count[terrain] += 1;
1971 }
1972 }
1973
1974 // Get the terrain with the max number of occurrences.
1975 int max = 0;
1976 int max_terrain = -1;
1977 for (const KeyValue<int, int> &E_terrain_count : terrain_count) {
1978 if (E_terrain_count.value > max) {
1979 max = E_terrain_count.value;
1980 max_terrain = E_terrain_count.key;
1981 }
1982 }
1983
1984 // Set the adequate terrain.
1985 if (max > 0) {
1986 TerrainConstraint c = E_constraint;
1987 c.set_terrain(max_terrain);
1988 constraints.insert(c);
1989 }
1990 }
1991
1992 // Add the centers as constraints.
1993 for (Vector2i E_coords : p_painted) {
1994 TileData *tile_data = nullptr;
1995 TileMapCell cell = get_cell(E_coords);
1996 if (cell.source_id != TileSet::INVALID_SOURCE) {
1997 Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
1998 Ref<TileSetAtlasSource> atlas_source = source;
1999 if (atlas_source.is_valid()) {
2000 tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
2001 }
2002 }
2003
2004 int terrain = (tile_data && tile_data->get_terrain_set() == p_terrain_set) ? tile_data->get_terrain() : -1;
2005 if (!p_ignore_empty_terrains || terrain >= 0) {
2006 constraints.insert(TerrainConstraint(tile_set, E_coords, terrain));
2007 }
2008 }
2009
2010 return constraints;
2011 }
2012
2013 void TileMapLayer::_tile_set_changed() {
2014 dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
2015 _queue_internal_update();
2016 emit_signal(CoreStringName(changed));
2017 }
2018
2019 void TileMapLayer::_renamed() {
2020 emit_signal(CoreStringName(changed));
2021 }
2022
2023 void TileMapLayer::_update_notify_local_transform() {
2024 bool notify = is_using_kinematic_bodies() || is_y_sort_enabled();
2025 if (!notify) {
2026 if (is_y_sort_enabled()) {
2027 notify = true;
2028 }
2029 }
2030 set_notify_local_transform(notify);
2031 }
2032
2033 void TileMapLayer::_queue_internal_update() {
2034 if (pending_update) {
2035 return;
2036 }
2037 // Don't update when outside the tree, it doesn't do anything useful, and causes threading problems.
2038 if (is_inside_tree()) {
2039 pending_update = true;
2040 callable_mp(this, &TileMapLayer::_deferred_internal_update).call_deferred();
2041 }
2042 }
2043
2044 void TileMapLayer::_deferred_internal_update() {
2045 // Other updates.
2046 if (!pending_update) {
2047 return;
2048 }
2049
2050 // Update dirty quadrants on layers.
2051 _internal_update(false);
2052 }
2053
2054 void TileMapLayer::_internal_update(bool p_force_cleanup) {
2055 // Find TileData that need a runtime modification.
2056 // This may add cells to the dirty list if a runtime modification has been notified.
2057 _build_runtime_update_tile_data(p_force_cleanup);
2058
2059 // Callback for implementing custom subsystems.
2060 // This may add to the dirty list if some cells are changed inside _update_cells.
2061 _update_cells_callback(p_force_cleanup);
2062
2063 // Update all subsystems.
2064 _rendering_update(p_force_cleanup);
2065 #ifndef PHYSICS_2D_DISABLED
2066 _physics_update(p_force_cleanup);
2067 #endif // PHYSICS_2D_DISABLED
2068 #ifndef NAVIGATION_2D_DISABLED
2069 _navigation_update(p_force_cleanup);
2070 #endif // NAVIGATION_2D_DISABLED
2071 _scenes_update(p_force_cleanup);
2072 #ifdef DEBUG_ENABLED
2073 _debug_update(p_force_cleanup);
2074 #endif // DEBUG_ENABLED
2075
2076 _clear_runtime_update_tile_data();
2077
2078 // Clear the "what is dirty" flags.
2079 for (int i = 0; i < DIRTY_FLAGS_MAX; i++) {
2080 dirty.flags[i] = false;
2081 }
2082
2083 // List the cells to delete definitely.
2084 Vector<Vector2i> to_delete;
2085 for (SelfList<CellData> *cell_data_list_element = dirty.cell_list.first(); cell_data_list_element; cell_data_list_element = cell_data_list_element->next()) {
2086 CellData &cell_data = *cell_data_list_element->self();
2087 // Select the cell from tile_map if it is invalid.
2088 if (cell_data.cell.source_id == TileSet::INVALID_SOURCE) {
2089 to_delete.push_back(cell_data.coords);
2090 }
2091 }
2092
2093 // Remove cells that are empty after the cleanup.
2094 for (const Vector2i &coords : to_delete) {
2095 tile_map_layer_data.erase(coords);
2096 }
2097
2098 // Clear the dirty cells list.
2099 dirty.cell_list.clear();
2100
2101 pending_update = false;
2102 }
2103
2104 void TileMapLayer::_physics_interpolated_changed() {
2105 RenderingServer *rs = RenderingServer::get_singleton();
2106
2107 bool interpolated = is_physics_interpolated();
2108 bool needs_reset = interpolated && is_visible_in_tree();
2109
2110 for (const KeyValue<Vector2i, Ref<RenderingQuadrant>> &kv : rendering_quadrant_map) {
2111 for (const RID &ci : kv.value->canvas_items) {
2112 if (ci.is_valid()) {
2113 rs->canvas_item_set_interpolated(ci, interpolated);
2114 if (needs_reset) {
2115 rs->canvas_item_reset_physics_interpolation(ci);
2116 }
2117 }
2118 }
2119 }
2120
2121 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2122 for (const LocalVector<RID> &polygons : E.value.occluders) {
2123 for (const RID &occluder_id : polygons) {
2124 if (occluder_id.is_valid()) {
2125 rs->canvas_light_occluder_set_interpolated(occluder_id, interpolated);
2126 if (needs_reset) {
2127 rs->canvas_light_occluder_reset_physics_interpolation(occluder_id);
2128 }
2129 }
2130 }
2131 }
2132 }
2133 }
2134
2135 void TileMapLayer::_notification(int p_what) {
2136 switch (p_what) {
2137 case NOTIFICATION_POSTINITIALIZE: {
2138 connect(SNAME("renamed"), callable_mp(this, &TileMapLayer::_renamed));
2139 break;
2140 }
2141 case NOTIFICATION_ENTER_TREE: {
2142 _update_notify_local_transform();
2143 dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
2144 _queue_internal_update();
2145 } break;
2146
2147 case NOTIFICATION_EXIT_TREE: {
2148 dirty.flags[DIRTY_FLAGS_LAYER_IN_TREE] = true;
2149 // Update immediately on exiting, and force cleanup.
2150 _internal_update(true);
2151 } break;
2152
2153 case NOTIFICATION_ENTER_CANVAS: {
2154 dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
2155 _queue_internal_update();
2156 } break;
2157
2158 case NOTIFICATION_EXIT_CANVAS: {
2159 dirty.flags[DIRTY_FLAGS_LAYER_IN_CANVAS] = true;
2160 // Update immediately on exiting, and force cleanup.
2161 _internal_update(true);
2162 } break;
2163
2164 case NOTIFICATION_VISIBILITY_CHANGED: {
2165 dirty.flags[DIRTY_FLAGS_LAYER_VISIBILITY] = true;
2166 _queue_internal_update();
2167 } break;
2168 }
2169
2170 _rendering_notification(p_what);
2171 #ifndef PHYSICS_2D_DISABLED
2172 _physics_notification(p_what);
2173 #endif // PHYSICS_2D_DISABLED
2174 #ifndef NAVIGATION_2D_DISABLED
2175 _navigation_notification(p_what);
2176 #endif // NAVIGATION_2D_DISABLED
2177 }
2178
2179 void TileMapLayer::_bind_methods() {
2180 // --- Cells manipulation ---
2181 // Generic cells manipulations and access.
2182 ClassDB::bind_method(D_METHOD("set_cell", "coords", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::set_cell, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(0));
2183 ClassDB::bind_method(D_METHOD("erase_cell", "coords"), &TileMapLayer::erase_cell);
2184 ClassDB::bind_method(D_METHOD("fix_invalid_tiles"), &TileMapLayer::fix_invalid_tiles);
2185 ClassDB::bind_method(D_METHOD("clear"), &TileMapLayer::clear);
2186
2187 ClassDB::bind_method(D_METHOD("get_cell_source_id", "coords"), &TileMapLayer::get_cell_source_id);
2188 ClassDB::bind_method(D_METHOD("get_cell_atlas_coords", "coords"), &TileMapLayer::get_cell_atlas_coords);
2189 ClassDB::bind_method(D_METHOD("get_cell_alternative_tile", "coords"), &TileMapLayer::get_cell_alternative_tile);
2190 ClassDB::bind_method(D_METHOD("get_cell_tile_data", "coords"), &TileMapLayer::get_cell_tile_data);
2191
2192 ClassDB::bind_method(D_METHOD("is_cell_flipped_h", "coords"), &TileMapLayer::is_cell_flipped_h);
2193 ClassDB::bind_method(D_METHOD("is_cell_flipped_v", "coords"), &TileMapLayer::is_cell_flipped_v);
2194 ClassDB::bind_method(D_METHOD("is_cell_transposed", "coords"), &TileMapLayer::is_cell_transposed);
2195
2196 ClassDB::bind_method(D_METHOD("get_used_cells"), &TileMapLayer::get_used_cells);
2197 ClassDB::bind_method(D_METHOD("get_used_cells_by_id", "source_id", "atlas_coords", "alternative_tile"), &TileMapLayer::get_used_cells_by_id, DEFVAL(TileSet::INVALID_SOURCE), DEFVAL(TileSetSource::INVALID_ATLAS_COORDS), DEFVAL(TileSetSource::INVALID_TILE_ALTERNATIVE));
2198 ClassDB::bind_method(D_METHOD("get_used_rect"), &TileMapLayer::get_used_rect);
2199
2200 // Patterns.
2201 ClassDB::bind_method(D_METHOD("get_pattern", "coords_array"), &TileMapLayer::get_pattern);
2202 ClassDB::bind_method(D_METHOD("set_pattern", "position", "pattern"), &TileMapLayer::set_pattern);
2203
2204 // Terrains.
2205 ClassDB::bind_method(D_METHOD("set_cells_terrain_connect", "cells", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_connect, DEFVAL(true));
2206 ClassDB::bind_method(D_METHOD("set_cells_terrain_path", "path", "terrain_set", "terrain", "ignore_empty_terrains"), &TileMapLayer::set_cells_terrain_path, DEFVAL(true));
2207
2208 #ifndef PHYSICS_2D_DISABLED
2209 // --- Physics helpers ---
2210 ClassDB::bind_method(D_METHOD("has_body_rid", "body"), &TileMapLayer::has_body_rid);
2211 ClassDB::bind_method(D_METHOD("get_coords_for_body_rid", "body"), &TileMapLayer::get_coords_for_body_rid);
2212 #endif // PHYSICS_2D_DISABLED
2213
2214 // --- Runtime ---
2215 ClassDB::bind_method(D_METHOD("update_internals"), &TileMapLayer::update_internals);
2216 ClassDB::bind_method(D_METHOD("notify_runtime_tile_data_update"), &TileMapLayer::notify_runtime_tile_data_update);
2217
2218 // --- Shortcuts to methods defined in TileSet ---
2219 ClassDB::bind_method(D_METHOD("map_pattern", "position_in_tilemap", "coords_in_pattern", "pattern"), &TileMapLayer::map_pattern);
2220 ClassDB::bind_method(D_METHOD("get_surrounding_cells", "coords"), &TileMapLayer::get_surrounding_cells);
2221 ClassDB::bind_method(D_METHOD("get_neighbor_cell", "coords", "neighbor"), &TileMapLayer::get_neighbor_cell);
2222 ClassDB::bind_method(D_METHOD("map_to_local", "map_position"), &TileMapLayer::map_to_local);
2223 ClassDB::bind_method(D_METHOD("local_to_map", "local_position"), &TileMapLayer::local_to_map);
2224
2225 // --- Accessors ---
2226 ClassDB::bind_method(D_METHOD("set_tile_map_data_from_array", "tile_map_layer_data"), &TileMapLayer::set_tile_map_data_from_array);
2227 ClassDB::bind_method(D_METHOD("get_tile_map_data_as_array"), &TileMapLayer::get_tile_map_data_as_array);
2228
2229 ClassDB::bind_method(D_METHOD("set_enabled", "enabled"), &TileMapLayer::set_enabled);
2230 ClassDB::bind_method(D_METHOD("is_enabled"), &TileMapLayer::is_enabled);
2231
2232 ClassDB::bind_method(D_METHOD("set_tile_set", "tile_set"), &TileMapLayer::set_tile_set);
2233 ClassDB::bind_method(D_METHOD("get_tile_set"), &TileMapLayer::get_tile_set);
2234
2235 ClassDB::bind_method(D_METHOD("set_y_sort_origin", "y_sort_origin"), &TileMapLayer::set_y_sort_origin);
2236 ClassDB::bind_method(D_METHOD("get_y_sort_origin"), &TileMapLayer::get_y_sort_origin);
2237 ClassDB::bind_method(D_METHOD("set_x_draw_order_reversed", "x_draw_order_reversed"), &TileMapLayer::set_x_draw_order_reversed);
2238 ClassDB::bind_method(D_METHOD("is_x_draw_order_reversed"), &TileMapLayer::is_x_draw_order_reversed);
2239 ClassDB::bind_method(D_METHOD("set_rendering_quadrant_size", "size"), &TileMapLayer::set_rendering_quadrant_size);
2240 ClassDB::bind_method(D_METHOD("get_rendering_quadrant_size"), &TileMapLayer::get_rendering_quadrant_size);
2241
2242 ClassDB::bind_method(D_METHOD("set_collision_enabled", "enabled"), &TileMapLayer::set_collision_enabled);
2243 ClassDB::bind_method(D_METHOD("is_collision_enabled"), &TileMapLayer::is_collision_enabled);
2244 ClassDB::bind_method(D_METHOD("set_use_kinematic_bodies", "use_kinematic_bodies"), &TileMapLayer::set_use_kinematic_bodies);
2245 ClassDB::bind_method(D_METHOD("is_using_kinematic_bodies"), &TileMapLayer::is_using_kinematic_bodies);
2246 ClassDB::bind_method(D_METHOD("set_collision_visibility_mode", "visibility_mode"), &TileMapLayer::set_collision_visibility_mode);
2247 ClassDB::bind_method(D_METHOD("get_collision_visibility_mode"), &TileMapLayer::get_collision_visibility_mode);
2248 ClassDB::bind_method(D_METHOD("set_physics_quadrant_size", "size"), &TileMapLayer::set_physics_quadrant_size);
2249 ClassDB::bind_method(D_METHOD("get_physics_quadrant_size"), &TileMapLayer::get_physics_quadrant_size);
2250
2251 ClassDB::bind_method(D_METHOD("set_occlusion_enabled", "enabled"), &TileMapLayer::set_occlusion_enabled);
2252 ClassDB::bind_method(D_METHOD("is_occlusion_enabled"), &TileMapLayer::is_occlusion_enabled);
2253
2254 #ifndef NAVIGATION_2D_DISABLED
2255 ClassDB::bind_method(D_METHOD("set_navigation_enabled", "enabled"), &TileMapLayer::set_navigation_enabled);
2256 ClassDB::bind_method(D_METHOD("is_navigation_enabled"), &TileMapLayer::is_navigation_enabled);
2257 ClassDB::bind_method(D_METHOD("set_navigation_map", "map"), &TileMapLayer::set_navigation_map);
2258 ClassDB::bind_method(D_METHOD("get_navigation_map"), &TileMapLayer::get_navigation_map);
2259 ClassDB::bind_method(D_METHOD("set_navigation_visibility_mode", "show_navigation"), &TileMapLayer::set_navigation_visibility_mode);
2260 ClassDB::bind_method(D_METHOD("get_navigation_visibility_mode"), &TileMapLayer::get_navigation_visibility_mode);
2261 #endif // NAVIGATION_2D_DISABLED
2262
2263 GDVIRTUAL_BIND(_use_tile_data_runtime_update, "coords");
2264 GDVIRTUAL_BIND(_tile_data_runtime_update, "coords", "tile_data");
2265 GDVIRTUAL_BIND(_update_cells, "coords", "forced_cleanup");
2266
2267 ADD_PROPERTY(PropertyInfo(Variant::PACKED_BYTE_ARRAY, "tile_map_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_tile_map_data_from_array", "get_tile_map_data_as_array");
2268
2269 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "enabled"), "set_enabled", "is_enabled");
2270 ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tile_set", PROPERTY_HINT_RESOURCE_TYPE, "TileSet"), "set_tile_set", "get_tile_set");
2271 ADD_GROUP("Rendering", "");
2272 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "occlusion_enabled"), "set_occlusion_enabled", "is_occlusion_enabled");
2273 ADD_PROPERTY(PropertyInfo(Variant::INT, "y_sort_origin"), "set_y_sort_origin", "get_y_sort_origin");
2274 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "x_draw_order_reversed"), "set_x_draw_order_reversed", "is_x_draw_order_reversed");
2275 ADD_PROPERTY(PropertyInfo(Variant::INT, "rendering_quadrant_size"), "set_rendering_quadrant_size", "get_rendering_quadrant_size");
2276 ADD_GROUP("Physics", "");
2277 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "collision_enabled"), "set_collision_enabled", "is_collision_enabled");
2278 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_kinematic_bodies"), "set_use_kinematic_bodies", "is_using_kinematic_bodies");
2279 ADD_PROPERTY(PropertyInfo(Variant::INT, "collision_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_collision_visibility_mode", "get_collision_visibility_mode");
2280 ADD_PROPERTY(PropertyInfo(Variant::INT, "physics_quadrant_size"), "set_physics_quadrant_size", "get_physics_quadrant_size");
2281 #ifndef NAVIGATION_2D_DISABLED
2282 ADD_GROUP("Navigation", "navigation_");
2283 ADD_PROPERTY(PropertyInfo(Variant::BOOL, "navigation_enabled", PROPERTY_HINT_GROUP_ENABLE), "set_navigation_enabled", "is_navigation_enabled");
2284 ADD_PROPERTY(PropertyInfo(Variant::INT, "navigation_visibility_mode", PROPERTY_HINT_ENUM, "Default,Force Show,Force Hide"), "set_navigation_visibility_mode", "get_navigation_visibility_mode");
2285 #endif // NAVIGATION_2D_DISABLED
2286
2287 ADD_SIGNAL(MethodInfo(CoreStringName(changed)));
2288
2289 ADD_PROPERTY_DEFAULT("tile_map_data_format", TileMapDataFormat::TILE_MAP_DATA_FORMAT_1);
2290
2291 BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_DEFAULT);
2292 BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_HIDE);
2293 BIND_ENUM_CONSTANT(DEBUG_VISIBILITY_MODE_FORCE_SHOW);
2294 }
2295
2296 void TileMapLayer::_validate_property(PropertyInfo &p_property) const {
2297 if (!Engine::get_singleton()->is_editor_hint()) {
2298 return;
2299 }
2300 if (is_y_sort_enabled()) {
2301 if (p_property.name == "rendering_quadrant_size") {
2302 p_property.usage |= PROPERTY_USAGE_READ_ONLY;
2303 }
2304 } else {
2305 if (p_property.name == "x_draw_order_reversed") {
2306 p_property.usage |= PROPERTY_USAGE_READ_ONLY;
2307 }
2308 }
2309 }
2310
2311 void TileMapLayer::_update_self_texture_filter(RS::CanvasItemTextureFilter p_texture_filter) {
2312 // Set a default texture filter for the whole tilemap.
2313 CanvasItem::_update_self_texture_filter(p_texture_filter);
2314 dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_FILTER] = true;
2315 _queue_internal_update();
2316 emit_signal(CoreStringName(changed));
2317 }
2318
2319 void TileMapLayer::_update_self_texture_repeat(RS::CanvasItemTextureRepeat p_texture_repeat) {
2320 // Set a default texture repeat for the whole tilemap.
2321 CanvasItem::_update_self_texture_repeat(p_texture_repeat);
2322 dirty.flags[DIRTY_FLAGS_LAYER_TEXTURE_REPEAT] = true;
2323 _queue_internal_update();
2324 emit_signal(CoreStringName(changed));
2325 }
2326
2327 #ifdef TOOLS_ENABLED
2328 bool TileMapLayer::_edit_is_selected_on_click(const Point2 &p_point, double p_tolerance) const {
2329 return tile_set.is_valid() && get_cell_source_id(local_to_map(p_point)) != TileSet::INVALID_SOURCE;
2330 }
2331 #endif
2332
2333 void TileMapLayer::set_as_tile_map_internal_node(int p_index) {
2334 // Compatibility with TileMap.
2335 ERR_FAIL_NULL(get_parent());
2336 tile_map_node = Object::cast_to<TileMap>(get_parent());
2337 set_use_parent_material(true);
2338 if (layer_index_in_tile_map_node != p_index) {
2339 layer_index_in_tile_map_node = p_index;
2340 dirty.flags[DIRTY_FLAGS_LAYER_INDEX_IN_TILE_MAP_NODE] = true;
2341 _queue_internal_update();
2342 }
2343 }
2344
2345 Rect2 TileMapLayer::get_rect(bool &r_changed) const {
2346 if (tile_set.is_null()) {
2347 r_changed = rect_cache != Rect2();
2348 return Rect2();
2349 }
2350
2351 // Compute the displayed area of the tilemap.
2352 r_changed = false;
2353 #ifdef DEBUG_ENABLED
2354
2355 if (rect_cache_dirty) {
2356 Rect2 r_total;
2357 bool first = true;
2358 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2359 Rect2 r;
2360 r.position = tile_set->map_to_local(E.key);
2361 r.size = Size2();
2362 if (first) {
2363 r_total = r;
2364 first = false;
2365 } else {
2366 r_total = r_total.merge(r);
2367 }
2368 }
2369
2370 r_changed = rect_cache != r_total;
2371
2372 rect_cache = r_total;
2373 rect_cache_dirty = false;
2374 }
2375 #endif
2376 return rect_cache;
2377 }
2378
2379 HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_constraints(const Vector<Vector2i> &p_to_replace, int p_terrain_set, const RBSet<TerrainConstraint> &p_constraints) const {
2380 if (tile_set.is_null()) {
2381 return HashMap<Vector2i, TileSet::TerrainsPattern>();
2382 }
2383
2384 // Copy the constraints set.
2385 RBSet<TerrainConstraint> constraints = p_constraints;
2386
2387 // Output map.
2388 HashMap<Vector2i, TileSet::TerrainsPattern> output;
2389
2390 // Add all positions to a set.
2391 for (int i = 0; i < p_to_replace.size(); i++) {
2392 const Vector2i &coords = p_to_replace[i];
2393
2394 // Select the best pattern for the given constraints.
2395 TileSet::TerrainsPattern current_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
2396 TileMapCell cell = get_cell(coords);
2397 if (cell.source_id != TileSet::INVALID_SOURCE) {
2398 TileSetSource *source = *tile_set->get_source(cell.source_id);
2399 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
2400 if (atlas_source) {
2401 // Get tile data.
2402 TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
2403 if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
2404 current_pattern = tile_data->get_terrains_pattern();
2405 }
2406 }
2407 }
2408 TileSet::TerrainsPattern pattern = _get_best_terrain_pattern_for_constraints(p_terrain_set, coords, constraints, current_pattern);
2409
2410 // Update the constraint set with the new ones.
2411 RBSet<TerrainConstraint> new_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, pattern);
2412 for (const TerrainConstraint &E_constraint : new_constraints) {
2413 if (constraints.has(E_constraint)) {
2414 constraints.erase(E_constraint);
2415 }
2416 TerrainConstraint c = E_constraint;
2417 c.set_priority(5);
2418 constraints.insert(c);
2419 }
2420
2421 output[coords] = pattern;
2422 }
2423 return output;
2424 }
2425
2426 HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_connect(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
2427 ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2428 ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2429 HashMap<Vector2i, TileSet::TerrainsPattern> output;
2430
2431 // Build list and set of tiles that can be modified (painted and their surroundings).
2432 Vector<Vector2i> can_modify_list;
2433 RBSet<Vector2i> can_modify_set;
2434 RBSet<Vector2i> painted_set;
2435 for (int i = p_coords_array.size() - 1; i >= 0; i--) {
2436 const Vector2i &coords = p_coords_array[i];
2437 can_modify_list.push_back(coords);
2438 can_modify_set.insert(coords);
2439 painted_set.insert(coords);
2440 }
2441 for (Vector2i coords : p_coords_array) {
2442 // Find the adequate neighbor.
2443 for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
2444 TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
2445 if (tile_set->is_existing_neighbor(bit)) {
2446 Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
2447 if (!can_modify_set.has(neighbor)) {
2448 can_modify_list.push_back(neighbor);
2449 can_modify_set.insert(neighbor);
2450 }
2451 }
2452 }
2453 }
2454
2455 // Build a set, out of the possibly modified tiles, of the one with a center bit that is set (or will be) to the painted terrain.
2456 RBSet<Vector2i> cells_with_terrain_center_bit;
2457 for (Vector2i coords : can_modify_set) {
2458 bool connect = false;
2459 if (painted_set.has(coords)) {
2460 connect = true;
2461 } else {
2462 // Get the center bit of the cell.
2463 TileData *tile_data = nullptr;
2464 TileMapCell cell = get_cell(coords);
2465 if (cell.source_id != TileSet::INVALID_SOURCE) {
2466 Ref<TileSetSource> source = tile_set->get_source(cell.source_id);
2467 Ref<TileSetAtlasSource> atlas_source = source;
2468 if (atlas_source.is_valid()) {
2469 tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
2470 }
2471 }
2472
2473 if (tile_data && tile_data->get_terrain_set() == p_terrain_set && tile_data->get_terrain() == p_terrain) {
2474 connect = true;
2475 }
2476 }
2477 if (connect) {
2478 cells_with_terrain_center_bit.insert(coords);
2479 }
2480 }
2481
2482 RBSet<TerrainConstraint> constraints;
2483
2484 // Add new constraints from the path drawn.
2485 for (Vector2i coords : p_coords_array) {
2486 // Constraints on the center bit.
2487 TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
2488 c.set_priority(10);
2489 constraints.insert(c);
2490
2491 // Constraints on the connecting bits.
2492 for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
2493 TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
2494 if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
2495 c = TerrainConstraint(tile_set, coords, bit, p_terrain);
2496 c.set_priority(10);
2497 if ((int(bit) % 2) == 0) {
2498 // Side peering bits: add the constraint if the center is of the same terrain.
2499 Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
2500 if (cells_with_terrain_center_bit.has(neighbor)) {
2501 constraints.insert(c);
2502 }
2503 } else {
2504 // Corner peering bits: add the constraint if all tiles on the constraint has the same center bit.
2505 HashMap<Vector2i, TileSet::CellNeighbor> overlapping_terrain_bits = c.get_overlapping_coords_and_peering_bits();
2506 bool valid = true;
2507 for (KeyValue<Vector2i, TileSet::CellNeighbor> kv : overlapping_terrain_bits) {
2508 if (!cells_with_terrain_center_bit.has(kv.key)) {
2509 valid = false;
2510 break;
2511 }
2512 }
2513 if (valid) {
2514 constraints.insert(c);
2515 }
2516 }
2517 }
2518 }
2519 }
2520
2521 // Fills in the constraint list from existing tiles.
2522 for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
2523 constraints.insert(c);
2524 }
2525
2526 // Fill the terrains.
2527 return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
2528 }
2529
2530 HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_path(const Vector<Vector2i> &p_coords_array, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) const {
2531 ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2532 ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2533 HashMap<Vector2i, TileSet::TerrainsPattern> output;
2534
2535 // Make sure the path is correct and build the peering bit list while doing it.
2536 Vector<TileSet::CellNeighbor> neighbor_list;
2537 for (int i = 0; i < p_coords_array.size() - 1; i++) {
2538 // Find the adequate neighbor.
2539 TileSet::CellNeighbor found_bit = TileSet::CELL_NEIGHBOR_MAX;
2540 for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
2541 TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
2542 if (tile_set->is_existing_neighbor(bit)) {
2543 if (tile_set->get_neighbor_cell(p_coords_array[i], bit) == p_coords_array[i + 1]) {
2544 found_bit = bit;
2545 break;
2546 }
2547 }
2548 }
2549 ERR_FAIL_COND_V_MSG(found_bit == TileSet::CELL_NEIGHBOR_MAX, output, vformat("Invalid terrain path, %s is not a neighboring tile of %s", p_coords_array[i + 1], p_coords_array[i]));
2550 neighbor_list.push_back(found_bit);
2551 }
2552
2553 // Build list and set of tiles that can be modified (painted and their surroundings).
2554 Vector<Vector2i> can_modify_list;
2555 RBSet<Vector2i> can_modify_set;
2556 RBSet<Vector2i> painted_set;
2557 for (int i = p_coords_array.size() - 1; i >= 0; i--) {
2558 const Vector2i &coords = p_coords_array[i];
2559 can_modify_list.push_back(coords);
2560 can_modify_set.insert(coords);
2561 painted_set.insert(coords);
2562 }
2563 for (Vector2i coords : p_coords_array) {
2564 // Find the adequate neighbor.
2565 for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
2566 TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
2567 if (tile_set->is_valid_terrain_peering_bit(p_terrain_set, bit)) {
2568 Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
2569 if (!can_modify_set.has(neighbor)) {
2570 can_modify_list.push_back(neighbor);
2571 can_modify_set.insert(neighbor);
2572 }
2573 }
2574 }
2575 }
2576
2577 RBSet<TerrainConstraint> constraints;
2578
2579 // Add new constraints from the path drawn.
2580 for (Vector2i coords : p_coords_array) {
2581 // Constraints on the center bit.
2582 TerrainConstraint c = TerrainConstraint(tile_set, coords, p_terrain);
2583 c.set_priority(10);
2584 constraints.insert(c);
2585 }
2586 for (int i = 0; i < p_coords_array.size() - 1; i++) {
2587 // Constraints on the peering bits.
2588 TerrainConstraint c = TerrainConstraint(tile_set, p_coords_array[i], neighbor_list[i], p_terrain);
2589 c.set_priority(10);
2590 constraints.insert(c);
2591 }
2592
2593 // Fills in the constraint list from existing tiles.
2594 for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
2595 constraints.insert(c);
2596 }
2597
2598 // Fill the terrains.
2599 return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
2600 }
2601
2602 HashMap<Vector2i, TileSet::TerrainsPattern> TileMapLayer::terrain_fill_pattern(const Vector<Vector2i> &p_coords_array, int p_terrain_set, TileSet::TerrainsPattern p_terrains_pattern, bool p_ignore_empty_terrains) const {
2603 ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2604 ERR_FAIL_INDEX_V(p_terrain_set, tile_set->get_terrain_sets_count(), (HashMap<Vector2i, TileSet::TerrainsPattern>()));
2605 HashMap<Vector2i, TileSet::TerrainsPattern> output;
2606
2607 // Build list and set of tiles that can be modified (painted and their surroundings).
2608 Vector<Vector2i> can_modify_list;
2609 RBSet<Vector2i> can_modify_set;
2610 RBSet<Vector2i> painted_set;
2611 for (int i = p_coords_array.size() - 1; i >= 0; i--) {
2612 const Vector2i &coords = p_coords_array[i];
2613 can_modify_list.push_back(coords);
2614 can_modify_set.insert(coords);
2615 painted_set.insert(coords);
2616 }
2617 for (Vector2i coords : p_coords_array) {
2618 // Find the adequate neighbor.
2619 for (int j = 0; j < TileSet::CELL_NEIGHBOR_MAX; j++) {
2620 TileSet::CellNeighbor bit = TileSet::CellNeighbor(j);
2621 if (tile_set->is_existing_neighbor(bit)) {
2622 Vector2i neighbor = tile_set->get_neighbor_cell(coords, bit);
2623 if (!can_modify_set.has(neighbor)) {
2624 can_modify_list.push_back(neighbor);
2625 can_modify_set.insert(neighbor);
2626 }
2627 }
2628 }
2629 }
2630
2631 // Add constraint by the new ones.
2632 RBSet<TerrainConstraint> constraints;
2633
2634 // Add new constraints from the path drawn.
2635 for (Vector2i coords : p_coords_array) {
2636 // Constraints on the center bit.
2637 RBSet<TerrainConstraint> added_constraints = _get_terrain_constraints_from_added_pattern(coords, p_terrain_set, p_terrains_pattern);
2638 for (TerrainConstraint c : added_constraints) {
2639 c.set_priority(10);
2640 constraints.insert(c);
2641 }
2642 }
2643
2644 // Fills in the constraint list from modified tiles border.
2645 for (TerrainConstraint c : _get_terrain_constraints_from_painted_cells_list(painted_set, p_terrain_set, p_ignore_empty_terrains)) {
2646 constraints.insert(c);
2647 }
2648
2649 // Fill the terrains.
2650 return terrain_fill_constraints(can_modify_list, p_terrain_set, constraints);
2651 }
2652
2653 TileMapCell TileMapLayer::get_cell(const Vector2i &p_coords) const {
2654 if (!tile_map_layer_data.has(p_coords)) {
2655 return TileMapCell();
2656 } else {
2657 return tile_map_layer_data.find(p_coords)->value.cell;
2658 }
2659 }
2660
2661 void TileMapLayer::draw_tile(RID p_canvas_item, const Vector2 &p_position, const Ref<TileSet> p_tile_set, int p_atlas_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile, int p_frame, const TileData *p_tile_data_override, real_t p_normalized_animation_offset) {
2662 ERR_FAIL_COND(p_tile_set.is_null());
2663 ERR_FAIL_COND(!p_tile_set->has_source(p_atlas_source_id));
2664 ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_tile(p_atlas_coords));
2665 ERR_FAIL_COND(!p_tile_set->get_source(p_atlas_source_id)->has_alternative_tile(p_atlas_coords, p_alternative_tile));
2666 TileSetSource *source = *p_tile_set->get_source(p_atlas_source_id);
2667 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
2668 if (atlas_source) {
2669 // Check for the frame.
2670 if (p_frame >= 0) {
2671 ERR_FAIL_INDEX(p_frame, atlas_source->get_tile_animation_frames_count(p_atlas_coords));
2672 }
2673
2674 // Get the texture.
2675 Ref<Texture2D> tex = atlas_source->get_runtime_texture();
2676 if (tex.is_null()) {
2677 return;
2678 }
2679
2680 // Check if we are in the texture, return otherwise.
2681 Vector2i grid_size = atlas_source->get_atlas_grid_size();
2682 if (p_atlas_coords.x >= grid_size.x || p_atlas_coords.y >= grid_size.y) {
2683 return;
2684 }
2685
2686 // Get tile data.
2687 const TileData *tile_data = p_tile_data_override ? p_tile_data_override : atlas_source->get_tile_data(p_atlas_coords, p_alternative_tile);
2688
2689 // Get the tile modulation.
2690 Color modulate = tile_data->get_modulate();
2691
2692 // Compute the dest rect.
2693 Rect2 dest_rect;
2694 bool transpose;
2695 compute_transformed_tile_dest_rect(dest_rect, transpose, p_position, atlas_source->get_runtime_tile_texture_region(p_atlas_coords).size, tile_data, p_alternative_tile);
2696
2697 // Draw the tile.
2698 if (p_frame >= 0) {
2699 Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, p_frame);
2700 tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
2701 } else if (atlas_source->get_tile_animation_frames_count(p_atlas_coords) == 1) {
2702 Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, 0);
2703 tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
2704 } else {
2705 real_t speed = atlas_source->get_tile_animation_speed(p_atlas_coords);
2706 real_t animation_duration = atlas_source->get_tile_animation_total_duration(p_atlas_coords) / speed;
2707 real_t animation_offset = p_normalized_animation_offset * animation_duration;
2708 // Accumulate durations unaffected by the speed to avoid accumulating floating point division errors.
2709 // Aka do `sum(duration[i]) / speed` instead of `sum(duration[i] / speed)`.
2710 real_t time_unscaled = 0.0;
2711 for (int frame = 0; frame < atlas_source->get_tile_animation_frames_count(p_atlas_coords); frame++) {
2712 real_t frame_duration_unscaled = atlas_source->get_tile_animation_frame_duration(p_atlas_coords, frame);
2713 real_t slice_start = time_unscaled / speed;
2714 real_t slice_end = (time_unscaled + frame_duration_unscaled) / speed;
2715 RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, animation_duration, slice_start, slice_end, animation_offset);
2716
2717 Rect2i source_rect = atlas_source->get_runtime_tile_texture_region(p_atlas_coords, frame);
2718 tex->draw_rect_region(p_canvas_item, dest_rect, source_rect, modulate, transpose, p_tile_set->is_uv_clipping());
2719
2720 time_unscaled += frame_duration_unscaled;
2721 }
2722 RenderingServer::get_singleton()->canvas_item_add_animation_slice(p_canvas_item, 1.0, 0.0, 1.0, 0.0);
2723 }
2724 }
2725 }
2726
2727 void TileMapLayer::compute_transformed_tile_dest_rect(Rect2 &r_dest_rect, bool &r_transpose, const Vector2 &p_position, const Vector2 &p_dest_rect_size, const TileData *p_tile_data, int p_alternative_tile) {
2728 DEV_ASSERT(p_tile_data);
2729 // Conceptually the order of transformations is (starting from the tile centered at the origin):
2730 // - Per TileSet-tile transforms (transpose then flips).
2731 // - Translation so texture origin is at the origin.
2732 // - Per TileMapLayer-cell transforms (transpose then flips).
2733 // - Translation to target position.
2734
2735 const bool tile_transpose = p_tile_data->get_transpose();
2736 const bool tile_flip_h = p_tile_data->get_flip_h();
2737 const bool tile_flip_v = p_tile_data->get_flip_v();
2738
2739 const Vector2 texture_origin = p_tile_data->get_texture_origin();
2740
2741 const bool cell_transpose = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
2742 const bool cell_flip_h = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_H);
2743 const bool cell_flip_v = bool(p_alternative_tile & TileSetAtlasSource::TRANSFORM_FLIP_V);
2744
2745 const bool final_transpose = tile_transpose != cell_transpose;
2746 const bool final_flip_h = cell_flip_h != (cell_transpose ? tile_flip_v : tile_flip_h);
2747 const bool final_flip_v = cell_flip_v != (cell_transpose ? tile_flip_h : tile_flip_v);
2748
2749 // Rect draw commands swap the size based on the passed transpose, so the size is left non-tranposed here.
2750 // Position calculations need to use transposed size though.
2751 Rect2 dest_rect;
2752 dest_rect.size = p_dest_rect_size;
2753 dest_rect.size.x += FP_ADJUST;
2754 dest_rect.size.y += FP_ADJUST;
2755 Vector2 transposed_size = final_transpose ? Vector2(dest_rect.size.y, dest_rect.size.x) : dest_rect.size;
2756 if (final_flip_h) {
2757 dest_rect.size.x = -dest_rect.size.x;
2758 }
2759 if (final_flip_v) {
2760 dest_rect.size.y = -dest_rect.size.y;
2761 }
2762
2763 dest_rect.position = -0.5f * transposed_size;
2764 dest_rect.position -= cell_transpose ? Vector2(texture_origin.y, texture_origin.x) : texture_origin;
2765 if (cell_flip_h) {
2766 dest_rect.position.x = -(dest_rect.position.x + transposed_size.x);
2767 }
2768 if (cell_flip_v) {
2769 dest_rect.position.y = -(dest_rect.position.y + transposed_size.y);
2770 }
2771 dest_rect.position += p_position;
2772
2773 r_dest_rect = dest_rect;
2774 r_transpose = final_transpose;
2775 }
2776
2777 void TileMapLayer::set_cell(const Vector2i &p_coords, int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) {
2778 // Set the current cell tile (using integer position).
2779 Vector2i pk(p_coords);
2780 HashMap<Vector2i, CellData>::Iterator E = tile_map_layer_data.find(pk);
2781
2782 int source_id = p_source_id;
2783 Vector2i atlas_coords = p_atlas_coords;
2784 int alternative_tile = p_alternative_tile;
2785
2786 if ((source_id == TileSet::INVALID_SOURCE || atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE) &&
2787 (source_id != TileSet::INVALID_SOURCE || atlas_coords != TileSetSource::INVALID_ATLAS_COORDS || alternative_tile != TileSetSource::INVALID_TILE_ALTERNATIVE)) {
2788 source_id = TileSet::INVALID_SOURCE;
2789 atlas_coords = TileSetSource::INVALID_ATLAS_COORDS;
2790 alternative_tile = TileSetSource::INVALID_TILE_ALTERNATIVE;
2791 }
2792
2793 if (!E) {
2794 if (source_id == TileSet::INVALID_SOURCE) {
2795 return; // Nothing to do, the tile is already empty.
2796 }
2797
2798 // Insert a new cell in the tile map.
2799 CellData new_cell_data;
2800 new_cell_data.coords = pk;
2801 E = tile_map_layer_data.insert(pk, new_cell_data);
2802 } else {
2803 if (E->value.cell.source_id == source_id && E->value.cell.get_atlas_coords() == atlas_coords && E->value.cell.alternative_tile == alternative_tile) {
2804 return; // Nothing changed.
2805 }
2806 }
2807
2808 TileMapCell &c = E->value.cell;
2809 c.source_id = source_id;
2810 c.set_atlas_coords(atlas_coords);
2811 c.alternative_tile = alternative_tile;
2812
2813 // Make the given cell dirty.
2814 if (!E->value.dirty_list_element.in_list()) {
2815 dirty.cell_list.add(&(E->value.dirty_list_element));
2816 }
2817 _queue_internal_update();
2818
2819 used_rect_cache_dirty = true;
2820 }
2821
2822 void TileMapLayer::erase_cell(const Vector2i &p_coords) {
2823 set_cell(p_coords, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
2824 }
2825
2826 void TileMapLayer::fix_invalid_tiles() {
2827 ERR_FAIL_COND_MSG(tile_set.is_null(), "Cannot call fix_invalid_tiles() on a TileMapLayer without a valid TileSet.");
2828
2829 RBSet<Vector2i> coords;
2830 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2831 TileSetSource *source = *tile_set->get_source(E.value.cell.source_id);
2832 if (!source || !source->has_tile(E.value.cell.get_atlas_coords()) || !source->has_alternative_tile(E.value.cell.get_atlas_coords(), E.value.cell.alternative_tile)) {
2833 coords.insert(E.key);
2834 }
2835 }
2836 for (const Vector2i &E : coords) {
2837 set_cell(E, TileSet::INVALID_SOURCE, TileSetSource::INVALID_ATLAS_COORDS, TileSetSource::INVALID_TILE_ALTERNATIVE);
2838 }
2839 }
2840
2841 void TileMapLayer::clear() {
2842 // Remove all tiles.
2843 for (KeyValue<Vector2i, CellData> &kv : tile_map_layer_data) {
2844 erase_cell(kv.key);
2845 }
2846 used_rect_cache_dirty = true;
2847 }
2848
2849 int TileMapLayer::get_cell_source_id(const Vector2i &p_coords) const {
2850 // Get a cell source id from position.
2851 HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
2852
2853 if (!E) {
2854 return TileSet::INVALID_SOURCE;
2855 }
2856
2857 return E->value.cell.source_id;
2858 }
2859
2860 Vector2i TileMapLayer::get_cell_atlas_coords(const Vector2i &p_coords) const {
2861 // Get a cell source id from position.
2862 HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
2863
2864 if (!E) {
2865 return TileSetSource::INVALID_ATLAS_COORDS;
2866 }
2867
2868 return E->value.cell.get_atlas_coords();
2869 }
2870
2871 int TileMapLayer::get_cell_alternative_tile(const Vector2i &p_coords) const {
2872 // Get a cell source id from position.
2873 HashMap<Vector2i, CellData>::ConstIterator E = tile_map_layer_data.find(p_coords);
2874
2875 if (!E) {
2876 return TileSetSource::INVALID_TILE_ALTERNATIVE;
2877 }
2878
2879 return E->value.cell.alternative_tile;
2880 }
2881
2882 TileData *TileMapLayer::get_cell_tile_data(const Vector2i &p_coords) const {
2883 int source_id = get_cell_source_id(p_coords);
2884 if (source_id == TileSet::INVALID_SOURCE) {
2885 return nullptr;
2886 }
2887
2888 Ref<TileSetAtlasSource> source = tile_set->get_source(source_id);
2889 if (source.is_valid()) {
2890 return source->get_tile_data(get_cell_atlas_coords(p_coords), get_cell_alternative_tile(p_coords));
2891 }
2892
2893 return nullptr;
2894 }
2895
2896 TypedArray<Vector2i> TileMapLayer::get_used_cells() const {
2897 // Returns the cells used in the tilemap.
2898 TypedArray<Vector2i> a;
2899 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2900 const TileMapCell &c = E.value.cell;
2901 if (c.source_id == TileSet::INVALID_SOURCE) {
2902 continue;
2903 }
2904 a.push_back(E.key);
2905 }
2906
2907 return a;
2908 }
2909
2910 TypedArray<Vector2i> TileMapLayer::get_used_cells_by_id(int p_source_id, const Vector2i &p_atlas_coords, int p_alternative_tile) const {
2911 // Returns the cells used in the tilemap.
2912 TypedArray<Vector2i> a;
2913 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2914 const TileMapCell &c = E.value.cell;
2915 if (c.source_id == TileSet::INVALID_SOURCE) {
2916 continue;
2917 }
2918 if ((p_source_id == TileSet::INVALID_SOURCE || p_source_id == c.source_id) &&
2919 (p_atlas_coords == TileSetSource::INVALID_ATLAS_COORDS || p_atlas_coords == c.get_atlas_coords()) &&
2920 (p_alternative_tile == TileSetSource::INVALID_TILE_ALTERNATIVE || p_alternative_tile == c.alternative_tile)) {
2921 a.push_back(E.key);
2922 }
2923 }
2924
2925 return a;
2926 }
2927
2928 Rect2i TileMapLayer::get_used_rect() const {
2929 // Return the rect of the currently used area.
2930 if (used_rect_cache_dirty) {
2931 used_rect_cache = Rect2i();
2932
2933 bool first = true;
2934 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
2935 const TileMapCell &c = E.value.cell;
2936 if (c.source_id == TileSet::INVALID_SOURCE) {
2937 continue;
2938 }
2939 if (first) {
2940 used_rect_cache = Rect2i(E.key, Size2i());
2941 first = false;
2942 } else {
2943 used_rect_cache.expand_to(E.key);
2944 }
2945 }
2946 if (!first) {
2947 // Only if we have at least one cell.
2948 // The cache expands to top-left coordinate, so we add one full tile.
2949 used_rect_cache.size += Vector2i(1, 1);
2950 }
2951 used_rect_cache_dirty = false;
2952 }
2953
2954 return used_rect_cache;
2955 }
2956
2957 bool TileMapLayer::is_cell_flipped_h(const Vector2i &p_coords) const {
2958 return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_H;
2959 }
2960
2961 bool TileMapLayer::is_cell_flipped_v(const Vector2i &p_coords) const {
2962 return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_FLIP_V;
2963 }
2964
2965 bool TileMapLayer::is_cell_transposed(const Vector2i &p_coords) const {
2966 return get_cell_alternative_tile(p_coords) & TileSetAtlasSource::TRANSFORM_TRANSPOSE;
2967 }
2968
2969 Ref<TileMapPattern> TileMapLayer::get_pattern(TypedArray<Vector2i> p_coords_array) {
2970 ERR_FAIL_COND_V(tile_set.is_null(), nullptr);
2971
2972 Ref<TileMapPattern> output;
2973 output.instantiate();
2974 if (p_coords_array.is_empty()) {
2975 return output;
2976 }
2977
2978 Vector2i min = Vector2i(p_coords_array[0]);
2979 for (int i = 1; i < p_coords_array.size(); i++) {
2980 min = min.min(p_coords_array[i]);
2981 }
2982
2983 Vector<Vector2i> coords_in_pattern_array;
2984 coords_in_pattern_array.resize(p_coords_array.size());
2985 Vector2i ensure_positive_offset;
2986 for (int i = 0; i < p_coords_array.size(); i++) {
2987 Vector2i coords = p_coords_array[i];
2988 Vector2i coords_in_pattern = coords - min;
2989 if (tile_set->get_tile_shape() != TileSet::TILE_SHAPE_SQUARE) {
2990 if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED) {
2991 if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
2992 coords_in_pattern.x -= 1;
2993 if (coords_in_pattern.x < 0) {
2994 ensure_positive_offset.x = 1;
2995 }
2996 } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
2997 coords_in_pattern.y -= 1;
2998 if (coords_in_pattern.y < 0) {
2999 ensure_positive_offset.y = 1;
3000 }
3001 }
3002 } else if (tile_set->get_tile_layout() == TileSet::TILE_LAYOUT_STACKED_OFFSET) {
3003 if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_HORIZONTAL && bool(min.y % 2) && bool(coords_in_pattern.y % 2)) {
3004 coords_in_pattern.x += 1;
3005 } else if (tile_set->get_tile_offset_axis() == TileSet::TILE_OFFSET_AXIS_VERTICAL && bool(min.x % 2) && bool(coords_in_pattern.x % 2)) {
3006 coords_in_pattern.y += 1;
3007 }
3008 }
3009 }
3010 coords_in_pattern_array.write[i] = coords_in_pattern;
3011 }
3012
3013 for (int i = 0; i < coords_in_pattern_array.size(); i++) {
3014 Vector2i coords = p_coords_array[i];
3015 Vector2i coords_in_pattern = coords_in_pattern_array[i];
3016 output->set_cell(coords_in_pattern + ensure_positive_offset, get_cell_source_id(coords), get_cell_atlas_coords(coords), get_cell_alternative_tile(coords));
3017 }
3018
3019 return output;
3020 }
3021
3022 void TileMapLayer::set_pattern(const Vector2i &p_position, const Ref<TileMapPattern> p_pattern) {
3023 ERR_FAIL_COND(tile_set.is_null());
3024 ERR_FAIL_COND(p_pattern.is_null());
3025
3026 TypedArray<Vector2i> used_cells = p_pattern->get_used_cells();
3027 for (int i = 0; i < used_cells.size(); i++) {
3028 Vector2i coords = tile_set->map_pattern(p_position, used_cells[i], p_pattern);
3029 set_cell(coords, p_pattern->get_cell_source_id(used_cells[i]), p_pattern->get_cell_atlas_coords(used_cells[i]), p_pattern->get_cell_alternative_tile(used_cells[i]));
3030 }
3031 }
3032
3033 void TileMapLayer::set_cells_terrain_connect(TypedArray<Vector2i> p_cells, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
3034 ERR_FAIL_COND(tile_set.is_null());
3035 ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
3036
3037 Vector<Vector2i> cells_vector;
3038 HashSet<Vector2i> painted_set;
3039 for (int i = 0; i < p_cells.size(); i++) {
3040 cells_vector.push_back(p_cells[i]);
3041 painted_set.insert(p_cells[i]);
3042 }
3043 HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_connect(cells_vector, p_terrain_set, p_terrain, p_ignore_empty_terrains);
3044 for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
3045 if (painted_set.has(kv.key)) {
3046 // Paint a random tile with the correct terrain for the painted path.
3047 TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
3048 set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
3049 } else {
3050 // Avoids updating the painted path from the output if the new pattern is the same as before.
3051 TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
3052 TileMapCell cell = get_cell(kv.key);
3053 if (cell.source_id != TileSet::INVALID_SOURCE) {
3054 TileSetSource *source = *tile_set->get_source(cell.source_id);
3055 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
3056 if (atlas_source) {
3057 // Get tile data.
3058 TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
3059 if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
3060 in_map_terrain_pattern = tile_data->get_terrains_pattern();
3061 }
3062 }
3063 }
3064 if (in_map_terrain_pattern != kv.value) {
3065 TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
3066 set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
3067 }
3068 }
3069 }
3070 }
3071
3072 void TileMapLayer::set_cells_terrain_path(TypedArray<Vector2i> p_path, int p_terrain_set, int p_terrain, bool p_ignore_empty_terrains) {
3073 ERR_FAIL_COND(tile_set.is_null());
3074 ERR_FAIL_INDEX(p_terrain_set, tile_set->get_terrain_sets_count());
3075
3076 Vector<Vector2i> vector_path;
3077 HashSet<Vector2i> painted_set;
3078 for (int i = 0; i < p_path.size(); i++) {
3079 vector_path.push_back(p_path[i]);
3080 painted_set.insert(p_path[i]);
3081 }
3082
3083 HashMap<Vector2i, TileSet::TerrainsPattern> terrain_fill_output = terrain_fill_path(vector_path, p_terrain_set, p_terrain, p_ignore_empty_terrains);
3084 for (const KeyValue<Vector2i, TileSet::TerrainsPattern> &kv : terrain_fill_output) {
3085 if (painted_set.has(kv.key)) {
3086 // Paint a random tile with the correct terrain for the painted path.
3087 TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
3088 set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
3089 } else {
3090 // Avoids updating the painted path from the output if the new pattern is the same as before.
3091 TileSet::TerrainsPattern in_map_terrain_pattern = TileSet::TerrainsPattern(*tile_set, p_terrain_set);
3092 TileMapCell cell = get_cell(kv.key);
3093 if (cell.source_id != TileSet::INVALID_SOURCE) {
3094 TileSetSource *source = *tile_set->get_source(cell.source_id);
3095 TileSetAtlasSource *atlas_source = Object::cast_to<TileSetAtlasSource>(source);
3096 if (atlas_source) {
3097 // Get tile data.
3098 TileData *tile_data = atlas_source->get_tile_data(cell.get_atlas_coords(), cell.alternative_tile);
3099 if (tile_data && tile_data->get_terrain_set() == p_terrain_set) {
3100 in_map_terrain_pattern = tile_data->get_terrains_pattern();
3101 }
3102 }
3103 }
3104 if (in_map_terrain_pattern != kv.value) {
3105 TileMapCell c = tile_set->get_random_tile_from_terrains_pattern(p_terrain_set, kv.value);
3106 set_cell(kv.key, c.source_id, c.get_atlas_coords(), c.alternative_tile);
3107 }
3108 }
3109 }
3110 }
3111
3112 #ifndef PHYSICS_2D_DISABLED
3113 bool TileMapLayer::has_body_rid(RID p_physics_body) const {
3114 return bodies_coords.has(p_physics_body);
3115 }
3116
3117 Vector2i TileMapLayer::get_coords_for_body_rid(RID p_physics_body) const {
3118 const Vector2i *found = bodies_coords.getptr(p_physics_body);
3119 ERR_FAIL_NULL_V(found, Vector2i());
3120 return *found;
3121 }
3122 #endif // PHYSICS_2D_DISABLED
3123
3124 void TileMapLayer::update_internals() {
3125 _internal_update(false);
3126 }
3127
3128 void TileMapLayer::notify_runtime_tile_data_update() {
3129 dirty.flags[TileMapLayer::DIRTY_FLAGS_LAYER_RUNTIME_UPDATE] = true;
3130 _queue_internal_update();
3131 emit_signal(CoreStringName(changed));
3132 }
3133
3134 Vector2i TileMapLayer::map_pattern(const Vector2i &p_position_in_tilemap, const Vector2i &p_coords_in_pattern, Ref<TileMapPattern> p_pattern) {
3135 ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
3136 return tile_set->map_pattern(p_position_in_tilemap, p_coords_in_pattern, p_pattern);
3137 }
3138
3139 TypedArray<Vector2i> TileMapLayer::get_surrounding_cells(const Vector2i &p_coords) {
3140 ERR_FAIL_COND_V(tile_set.is_null(), TypedArray<Vector2i>());
3141 return tile_set->get_surrounding_cells(p_coords);
3142 }
3143
3144 Vector2i TileMapLayer::get_neighbor_cell(const Vector2i &p_coords, TileSet::CellNeighbor p_cell_neighbor) const {
3145 ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
3146 return tile_set->get_neighbor_cell(p_coords, p_cell_neighbor);
3147 }
3148
3149 Vector2 TileMapLayer::map_to_local(const Vector2i &p_pos) const {
3150 ERR_FAIL_COND_V(tile_set.is_null(), Vector2());
3151 return tile_set->map_to_local(p_pos);
3152 }
3153
3154 Vector2i TileMapLayer::local_to_map(const Vector2 &p_pos) const {
3155 ERR_FAIL_COND_V(tile_set.is_null(), Vector2i());
3156 return tile_set->local_to_map(p_pos);
3157 }
3158
3159 void TileMapLayer::set_enabled(bool p_enabled) {
3160 if (enabled == p_enabled) {
3161 return;
3162 }
3163 enabled = p_enabled;
3164 dirty.flags[DIRTY_FLAGS_LAYER_ENABLED] = true;
3165 _queue_internal_update();
3166 emit_signal(CoreStringName(changed));
3167 }
3168
3169 bool TileMapLayer::is_enabled() const {
3170 return enabled;
3171 }
3172
3173 void TileMapLayer::set_tile_set(const Ref<TileSet> &p_tile_set) {
3174 if (p_tile_set == tile_set) {
3175 return;
3176 }
3177
3178 dirty.flags[DIRTY_FLAGS_TILE_SET] = true;
3179 _queue_internal_update();
3180
3181 // Set the TileSet, registering to its changes.
3182 if (tile_set.is_valid()) {
3183 tile_set->disconnect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
3184 }
3185
3186 tile_set = p_tile_set;
3187
3188 if (tile_set.is_valid()) {
3189 tile_set->connect_changed(callable_mp(this, &TileMapLayer::_tile_set_changed));
3190 }
3191
3192 emit_signal(CoreStringName(changed));
3193
3194 // Trigger updates for TileSet's read-only status.
3195 notify_property_list_changed();
3196 }
3197
3198 Ref<TileSet> TileMapLayer::get_tile_set() const {
3199 return tile_set;
3200 }
3201
3202 void TileMapLayer::set_highlight_mode(HighlightMode p_highlight_mode) {
3203 if (p_highlight_mode == highlight_mode) {
3204 return;
3205 }
3206 highlight_mode = p_highlight_mode;
3207 dirty.flags[DIRTY_FLAGS_LAYER_HIGHLIGHT_MODE] = true;
3208 _queue_internal_update();
3209 }
3210
3211 TileMapLayer::HighlightMode TileMapLayer::get_highlight_mode() const {
3212 return highlight_mode;
3213 }
3214
3215 void TileMapLayer::set_tile_map_data_from_array(const Vector<uint8_t> &p_data) {
3216 if (p_data.is_empty()) {
3217 clear();
3218 return;
3219 }
3220
3221 const int cell_data_struct_size = 12;
3222
3223 int size = p_data.size();
3224 const uint8_t *ptr = p_data.ptr();
3225
3226 // Index in the array.
3227 int index = 0;
3228
3229 // First extract the data version.
3230 ERR_FAIL_COND_MSG(size < 2, "Corrupted tile map data: not enough bytes.");
3231 uint16_t format = decode_uint16(&ptr[index]);
3232 index += 2;
3233 ERR_FAIL_COND_MSG(format >= TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX, vformat("Unsupported tile map data format: %s. Expected format ID lower or equal to: %s", format, TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1));
3234
3235 // Clear the TileMap.
3236 clear();
3237
3238 while (index < size) {
3239 ERR_FAIL_COND_MSG(index + cell_data_struct_size > size, vformat("Corrupted tile map data: tiles might be missing."));
3240
3241 // Get a pointer at the start of the cell data.
3242 const uint8_t *cell_data_ptr = &ptr[index];
3243
3244 // Extracts position in TileMap.
3245 int16_t x = decode_uint16(&cell_data_ptr[0]);
3246 int16_t y = decode_uint16(&cell_data_ptr[2]);
3247
3248 // Extracts the tile identifiers.
3249 uint16_t source_id = decode_uint16(&cell_data_ptr[4]);
3250 uint16_t atlas_coords_x = decode_uint16(&cell_data_ptr[6]);
3251 uint16_t atlas_coords_y = decode_uint16(&cell_data_ptr[8]);
3252 uint16_t alternative_tile = decode_uint16(&cell_data_ptr[10]);
3253
3254 set_cell(Vector2i(x, y), source_id, Vector2i(atlas_coords_x, atlas_coords_y), alternative_tile);
3255 index += cell_data_struct_size;
3256 }
3257 }
3258
3259 Vector<uint8_t> TileMapLayer::get_tile_map_data_as_array() const {
3260 const int cell_data_struct_size = 12;
3261
3262 Vector<uint8_t> tile_map_data_array;
3263 if (tile_map_layer_data.is_empty()) {
3264 return tile_map_data_array;
3265 }
3266
3267 tile_map_data_array.resize(2 + tile_map_layer_data.size() * cell_data_struct_size);
3268 uint8_t *ptr = tile_map_data_array.ptrw();
3269
3270 // Index in the array.
3271 int index = 0;
3272
3273 // Save the version.
3274 encode_uint16(TileMapLayerDataFormat::TILE_MAP_LAYER_DATA_FORMAT_MAX - 1, &ptr[index]);
3275 index += 2;
3276
3277 // Save in highest format.
3278 for (const KeyValue<Vector2i, CellData> &E : tile_map_layer_data) {
3279 // Get a pointer at the start of the cell data.
3280 uint8_t *cell_data_ptr = (uint8_t *)&ptr[index];
3281
3282 // Store position in TileMap.
3283 encode_uint16((int16_t)(E.key.x), &cell_data_ptr[0]);
3284 encode_uint16((int16_t)(E.key.y), &cell_data_ptr[2]);
3285
3286 // Store the tile identifiers.
3287 encode_uint16(E.value.cell.source_id, &cell_data_ptr[4]);
3288 encode_uint16(E.value.cell.coord_x, &cell_data_ptr[6]);
3289 encode_uint16(E.value.cell.coord_y, &cell_data_ptr[8]);
3290 encode_uint16(E.value.cell.alternative_tile, &cell_data_ptr[10]);
3291
3292 index += cell_data_struct_size;
3293 }
3294
3295 return tile_map_data_array;
3296 }
3297
3298 void TileMapLayer::set_self_modulate(const Color &p_self_modulate) {
3299 if (get_self_modulate() == p_self_modulate) {
3300 return;
3301 }
3302 CanvasItem::set_self_modulate(p_self_modulate);
3303 dirty.flags[DIRTY_FLAGS_LAYER_SELF_MODULATE] = true;
3304 _queue_internal_update();
3305 emit_signal(CoreStringName(changed));
3306 }
3307
3308 void TileMapLayer::set_y_sort_enabled(bool p_y_sort_enabled) {
3309 if (is_y_sort_enabled() == p_y_sort_enabled) {
3310 return;
3311 }
3312 CanvasItem::set_y_sort_enabled(p_y_sort_enabled);
3313 dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ENABLED] = true;
3314 _queue_internal_update();
3315 emit_signal(CoreStringName(changed));
3316
3317 notify_property_list_changed();
3318 _update_notify_local_transform();
3319 }
3320
3321 void TileMapLayer::set_y_sort_origin(int p_y_sort_origin) {
3322 if (y_sort_origin == p_y_sort_origin) {
3323 return;
3324 }
3325 y_sort_origin = p_y_sort_origin;
3326 dirty.flags[DIRTY_FLAGS_LAYER_Y_SORT_ORIGIN] = true;
3327 _queue_internal_update();
3328 emit_signal(CoreStringName(changed));
3329 }
3330
3331 int TileMapLayer::get_y_sort_origin() const {
3332 return y_sort_origin;
3333 }
3334
3335 void TileMapLayer::set_x_draw_order_reversed(bool p_x_draw_order_reversed) {
3336 if (x_draw_order_reversed == p_x_draw_order_reversed) {
3337 return;
3338 }
3339 x_draw_order_reversed = p_x_draw_order_reversed;
3340 dirty.flags[DIRTY_FLAGS_LAYER_X_DRAW_ORDER_REVERSED] = true;
3341 _queue_internal_update();
3342 emit_signal(CoreStringName(changed));
3343 }
3344
3345 bool TileMapLayer::is_x_draw_order_reversed() const {
3346 return x_draw_order_reversed;
3347 }
3348
3349 void TileMapLayer::set_z_index(int p_z_index) {
3350 if (get_z_index() == p_z_index) {
3351 return;
3352 }
3353 CanvasItem::set_z_index(p_z_index);
3354 dirty.flags[DIRTY_FLAGS_LAYER_Z_INDEX] = true;
3355 _queue_internal_update();
3356 emit_signal(CoreStringName(changed));
3357 }
3358
3359 void TileMapLayer::set_light_mask(int p_light_mask) {
3360 if (get_light_mask() == p_light_mask) {
3361 return;
3362 }
3363 CanvasItem::set_light_mask(p_light_mask);
3364 dirty.flags[DIRTY_FLAGS_LAYER_LIGHT_MASK] = true;
3365 _queue_internal_update();
3366 emit_signal(CoreStringName(changed));
3367 }
3368
3369 void TileMapLayer::set_rendering_quadrant_size(int p_size) {
3370 if (rendering_quadrant_size == p_size) {
3371 return;
3372 }
3373 ERR_FAIL_COND_MSG(p_size < 1, "TileMapQuadrant size cannot be smaller than 1.");
3374 rendering_quadrant_size = p_size;
3375 dirty.flags[DIRTY_FLAGS_LAYER_RENDERING_QUADRANT_SIZE] = true;
3376 _queue_internal_update();
3377 emit_signal(CoreStringName(changed));
3378 }
3379
3380 int TileMapLayer::get_rendering_quadrant_size() const {
3381 return rendering_quadrant_size;
3382 }
3383
3384 void TileMapLayer::set_collision_enabled(bool p_enabled) {
3385 if (collision_enabled == p_enabled) {
3386 return;
3387 }
3388 collision_enabled = p_enabled;
3389 dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_ENABLED] = true;
3390 _queue_internal_update();
3391 emit_signal(CoreStringName(changed));
3392 }
3393
3394 bool TileMapLayer::is_collision_enabled() const {
3395 return collision_enabled;
3396 }
3397
3398 void TileMapLayer::set_use_kinematic_bodies(bool p_use_kinematic_bodies) {
3399 if (use_kinematic_bodies == p_use_kinematic_bodies) {
3400 return;
3401 }
3402 use_kinematic_bodies = p_use_kinematic_bodies;
3403 dirty.flags[DIRTY_FLAGS_LAYER_USE_KINEMATIC_BODIES] = p_use_kinematic_bodies;
3404 _queue_internal_update();
3405 emit_signal(CoreStringName(changed));
3406 }
3407
3408 bool TileMapLayer::is_using_kinematic_bodies() const {
3409 return use_kinematic_bodies;
3410 }
3411
3412 void TileMapLayer::set_collision_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_collision) {
3413 if (collision_visibility_mode == p_show_collision) {
3414 return;
3415 }
3416 collision_visibility_mode = p_show_collision;
3417 dirty.flags[DIRTY_FLAGS_LAYER_COLLISION_VISIBILITY_MODE] = true;
3418 _queue_internal_update();
3419 emit_signal(CoreStringName(changed));
3420 }
3421
3422 TileMapLayer::DebugVisibilityMode TileMapLayer::get_collision_visibility_mode() const {
3423 return collision_visibility_mode;
3424 }
3425
3426 void TileMapLayer::set_physics_quadrant_size(int p_size) {
3427 if (physics_quadrant_size == p_size) {
3428 return;
3429 }
3430 ERR_FAIL_COND_MSG(p_size < 1, "Physics quandrant size cannot be smaller than 1.");
3431 physics_quadrant_size = p_size;
3432
3433 dirty.flags[DIRTY_FLAGS_LAYER_PHYSICS_QUADRANT_SIZE] = true;
3434 _queue_internal_update();
3435 emit_signal(CoreStringName(changed));
3436 }
3437
3438 int TileMapLayer::get_physics_quadrant_size() const {
3439 return physics_quadrant_size;
3440 }
3441
3442 void TileMapLayer::set_occlusion_enabled(bool p_enabled) {
3443 if (occlusion_enabled == p_enabled) {
3444 return;
3445 }
3446 occlusion_enabled = p_enabled;
3447 dirty.flags[DIRTY_FLAGS_LAYER_OCCLUSION_ENABLED] = true;
3448 _queue_internal_update();
3449 emit_signal(CoreStringName(changed));
3450 }
3451
3452 bool TileMapLayer::is_occlusion_enabled() const {
3453 return occlusion_enabled;
3454 }
3455
3456 #ifndef NAVIGATION_2D_DISABLED
3457 void TileMapLayer::set_navigation_enabled(bool p_enabled) {
3458 if (navigation_enabled == p_enabled) {
3459 return;
3460 }
3461 navigation_enabled = p_enabled;
3462 dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_ENABLED] = true;
3463 _queue_internal_update();
3464 emit_signal(CoreStringName(changed));
3465 }
3466
3467 bool TileMapLayer::is_navigation_enabled() const {
3468 return navigation_enabled;
3469 }
3470
3471 void TileMapLayer::set_navigation_map(RID p_map) {
3472 if (navigation_map_override == p_map) {
3473 return;
3474 }
3475 navigation_map_override = p_map;
3476 dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_MAP] = true;
3477 _queue_internal_update();
3478 emit_signal(CoreStringName(changed));
3479 }
3480
3481 RID TileMapLayer::get_navigation_map() const {
3482 if (navigation_map_override.is_valid()) {
3483 return navigation_map_override;
3484 } else if (is_inside_tree()) {
3485 return get_world_2d()->get_navigation_map();
3486 }
3487 return RID();
3488 }
3489
3490 void TileMapLayer::set_navigation_visibility_mode(TileMapLayer::DebugVisibilityMode p_show_navigation) {
3491 if (navigation_visibility_mode == p_show_navigation) {
3492 return;
3493 }
3494 navigation_visibility_mode = p_show_navigation;
3495 dirty.flags[DIRTY_FLAGS_LAYER_NAVIGATION_VISIBILITY_MODE] = true;
3496 _queue_internal_update();
3497 emit_signal(CoreStringName(changed));
3498 }
3499
3500 TileMapLayer::DebugVisibilityMode TileMapLayer::get_navigation_visibility_mode() const {
3501 return navigation_visibility_mode;
3502 }
3503
3504 void TileMapLayer::navmesh_parse_init() {
3505 ERR_FAIL_NULL(NavigationServer2D::get_singleton());
3506 if (!_navmesh_source_geometry_parser.is_valid()) {
3507 _navmesh_source_geometry_parsing_callback = callable_mp_static(&TileMapLayer::navmesh_parse_source_geometry);
3508 _navmesh_source_geometry_parser = NavigationServer2D::get_singleton()->source_geometry_parser_create();
3509 NavigationServer2D::get_singleton()->source_geometry_parser_set_callback(_navmesh_source_geometry_parser, _navmesh_source_geometry_parsing_callback);
3510 }
3511 }
3512
3513 void TileMapLayer::navmesh_parse_source_geometry(const Ref<NavigationPolygon> &p_navigation_mesh, Ref<NavigationMeshSourceGeometryData2D> p_source_geometry_data, Node *p_node) {
3514 TileMapLayer *tile_map_layer = Object::cast_to<TileMapLayer>(p_node);
3515
3516 if (tile_map_layer == nullptr) {
3517 return;
3518 }
3519
3520 Ref<TileSet> tile_set = tile_map_layer->get_tile_set();
3521 if (tile_set.is_null()) {
3522 return;
3523 }
3524
3525 int navigation_layers_count = tile_set->get_navigation_layers_count();
3526 #ifndef PHYSICS_2D_DISABLED
3527 int physics_layers_count = tile_set->get_physics_layers_count();
3528 if (physics_layers_count <= 0 && navigation_layers_count <= 0) {
3529 return;
3530 }
3531 #else
3532 if (navigation_layers_count <= 0) {
3533 return;
3534 }
3535 #endif // PHYSICS_2D_DISABLED
3536
3537 const Transform2D tilemap_xform = p_source_geometry_data->root_node_transform * tile_map_layer->get_global_transform();
3538
3539 for (KeyValue<Vector2i, CellData> kv : tile_map_layer->get_tile_map_layer_data()) {
3540 const Vector2i &cell = kv.key;
3541
3542 const TileData *tile_data = tile_map_layer->get_cell_tile_data(cell);
3543 if (tile_data == nullptr) {
3544 continue;
3545 }
3546
3547 // Transform flags.
3548 const int alternative_id = tile_map_layer->get_cell_alternative_tile(cell);
3549 bool flip_h = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_H);
3550 bool flip_v = (alternative_id & TileSetAtlasSource::TRANSFORM_FLIP_V);
3551 bool transpose = (alternative_id & TileSetAtlasSource::TRANSFORM_TRANSPOSE);
3552
3553 Transform2D tile_transform;
3554 tile_transform.set_origin(tile_map_layer->map_to_local(cell));
3555
3556 const Transform2D tile_transform_offset = tilemap_xform * tile_transform;
3557
3558 // Parse traversable polygons.
3559 for (int navigation_layer = 0; navigation_layer < navigation_layers_count; navigation_layer++) {
3560 Ref<NavigationPolygon> navigation_polygon = tile_data->get_navigation_polygon(navigation_layer, flip_h, flip_v, transpose);
3561 if (navigation_polygon.is_valid()) {
3562 for (int outline_index = 0; outline_index < navigation_polygon->get_outline_count(); outline_index++) {
3563 const Vector<Vector2> &navigation_polygon_outline = navigation_polygon->get_outline(outline_index);
3564 if (navigation_polygon_outline.is_empty()) {
3565 continue;
3566 }
3567
3568 Vector<Vector2> traversable_outline = tile_transform_offset.xform(navigation_polygon_outline);
3569 p_source_geometry_data->_add_traversable_outline(traversable_outline);
3570 }
3571 }
3572 }
3573
3574 #ifndef PHYSICS_2D_DISABLED
3575 NavigationPolygon::ParsedGeometryType parsed_geometry_type = p_navigation_mesh->get_parsed_geometry_type();
3576 uint32_t parsed_collision_mask = p_navigation_mesh->get_parsed_collision_mask();
3577
3578 // Parse obstacles.
3579 for (int physics_layer = 0; physics_layer < physics_layers_count; physics_layer++) {
3580 if ((parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_STATIC_COLLIDERS || parsed_geometry_type == NavigationPolygon::PARSED_GEOMETRY_BOTH) &&
3581 (tile_set->get_physics_layer_collision_layer(physics_layer) & parsed_collision_mask)) {
3582 for (int collision_polygon_index = 0; collision_polygon_index < tile_data->get_collision_polygons_count(physics_layer); collision_polygon_index++) {
3583 PackedVector2Array collision_polygon_points = tile_data->get_collision_polygon_points(physics_layer, collision_polygon_index);
3584 if (collision_polygon_points.is_empty()) {
3585 continue;
3586 }
3587
3588 if (flip_h || flip_v || transpose) {
3589 collision_polygon_points = TileData::get_transformed_vertices(collision_polygon_points, flip_h, flip_v, transpose);
3590 }
3591
3592 Vector<Vector2> obstruction_outline = tile_transform_offset.xform(collision_polygon_points);
3593 p_source_geometry_data->_add_obstruction_outline(obstruction_outline);
3594 }
3595 }
3596 }
3597 #endif // PHYSICS_2D_DISABLED
3598 }
3599 }
3600 #endif // NAVIGATION_2D_DISABLED
3601
3602 TileMapLayer::TileMapLayer() {
3603 set_notify_transform(true);
3604 }
3605
3606 TileMapLayer::~TileMapLayer() {
3607 clear();
3608 _internal_update(true);
3609 }
3610
3611 HashMap<Vector2i, TileSet::CellNeighbor> TerrainConstraint::get_overlapping_coords_and_peering_bits() const {
3612 ERR_FAIL_COND_V(is_center_bit(), (HashMap<Vector2i, TileSet::CellNeighbor>()));
3613 ERR_FAIL_COND_V(tile_set.is_null(), (HashMap<Vector2i, TileSet::CellNeighbor>()));
3614 HashMap<Vector2i, TileSet::CellNeighbor> output;
3615
3616 TileSet::TileShape shape = tile_set->get_tile_shape();
3617 if (shape == TileSet::TILE_SHAPE_SQUARE) {
3618 switch (bit) {
3619 case 1:
3620 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
3621 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
3622 break;
3623 case 2:
3624 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
3625 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
3626 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
3627 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
3628 break;
3629 case 3:
3630 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
3631 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
3632 break;
3633 default:
3634 ERR_FAIL_V(output);
3635 }
3636 } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
3637 switch (bit) {
3638 case 1:
3639 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
3640 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
3641 break;
3642 case 2:
3643 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
3644 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
3645 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_CORNER)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
3646 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
3647 break;
3648 case 3:
3649 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
3650 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
3651 break;
3652 default:
3653 ERR_FAIL_V(output);
3654 }
3655 } else {
3656 // Half offset shapes.
3657 TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
3658 if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
3659 switch (bit) {
3660 case 1:
3661 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_SIDE;
3662 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_SIDE;
3663 break;
3664 case 2:
3665 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
3666 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
3667 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_CORNER;
3668 break;
3669 case 3:
3670 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
3671 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
3672 break;
3673 case 4:
3674 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_CORNER;
3675 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
3676 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER;
3677 break;
3678 case 5:
3679 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
3680 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
3681 break;
3682 default:
3683 ERR_FAIL_V(output);
3684 }
3685 } else {
3686 switch (bit) {
3687 case 1:
3688 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_RIGHT_CORNER;
3689 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER;
3690 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
3691 break;
3692 case 2:
3693 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE;
3694 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE;
3695 break;
3696 case 3:
3697 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER;
3698 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE)] = TileSet::CELL_NEIGHBOR_LEFT_CORNER;
3699 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER;
3700 break;
3701 case 4:
3702 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_SIDE;
3703 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_SIDE;
3704 break;
3705 case 5:
3706 output[base_cell_coords] = TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE;
3707 output[tile_set->get_neighbor_cell(base_cell_coords, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE)] = TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE;
3708 break;
3709 default:
3710 ERR_FAIL_V(output);
3711 }
3712 }
3713 }
3714 return output;
3715 }
3716
3717 TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, int p_terrain) {
3718 ERR_FAIL_COND(p_tile_set.is_null());
3719 tile_set = p_tile_set;
3720 bit = 0;
3721 base_cell_coords = p_position;
3722 terrain = p_terrain;
3723 }
3724
3725 TerrainConstraint::TerrainConstraint(Ref<TileSet> p_tile_set, const Vector2i &p_position, const TileSet::CellNeighbor &p_bit, int p_terrain) {
3726 // The way we build the constraint make it easy to detect conflicting constraints.
3727 ERR_FAIL_COND(p_tile_set.is_null());
3728 tile_set = p_tile_set;
3729
3730 TileSet::TileShape shape = tile_set->get_tile_shape();
3731 if (shape == TileSet::TILE_SHAPE_SQUARE) {
3732 switch (p_bit) {
3733 case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
3734 bit = 1;
3735 base_cell_coords = p_position;
3736 break;
3737 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
3738 bit = 2;
3739 base_cell_coords = p_position;
3740 break;
3741 case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
3742 bit = 3;
3743 base_cell_coords = p_position;
3744 break;
3745 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
3746 bit = 2;
3747 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
3748 break;
3749 case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
3750 bit = 1;
3751 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
3752 break;
3753 case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
3754 bit = 2;
3755 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER);
3756 break;
3757 case TileSet::CELL_NEIGHBOR_TOP_SIDE:
3758 bit = 3;
3759 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
3760 break;
3761 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
3762 bit = 2;
3763 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
3764 break;
3765 default:
3766 ERR_FAIL();
3767 break;
3768 }
3769 } else if (shape == TileSet::TILE_SHAPE_ISOMETRIC) {
3770 switch (p_bit) {
3771 case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
3772 bit = 2;
3773 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
3774 break;
3775 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
3776 bit = 1;
3777 base_cell_coords = p_position;
3778 break;
3779 case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
3780 bit = 2;
3781 base_cell_coords = p_position;
3782 break;
3783 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
3784 bit = 3;
3785 base_cell_coords = p_position;
3786 break;
3787 case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
3788 bit = 2;
3789 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3790 break;
3791 case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
3792 bit = 1;
3793 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3794 break;
3795 case TileSet::CELL_NEIGHBOR_TOP_CORNER:
3796 bit = 2;
3797 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_CORNER);
3798 break;
3799 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
3800 bit = 3;
3801 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
3802 break;
3803 default:
3804 ERR_FAIL();
3805 break;
3806 }
3807 } else {
3808 // Half-offset shapes.
3809 TileSet::TileOffsetAxis offset_axis = tile_set->get_tile_offset_axis();
3810 if (offset_axis == TileSet::TILE_OFFSET_AXIS_HORIZONTAL) {
3811 switch (p_bit) {
3812 case TileSet::CELL_NEIGHBOR_RIGHT_SIDE:
3813 bit = 1;
3814 base_cell_coords = p_position;
3815 break;
3816 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
3817 bit = 2;
3818 base_cell_coords = p_position;
3819 break;
3820 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
3821 bit = 3;
3822 base_cell_coords = p_position;
3823 break;
3824 case TileSet::CELL_NEIGHBOR_BOTTOM_CORNER:
3825 bit = 4;
3826 base_cell_coords = p_position;
3827 break;
3828 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
3829 bit = 5;
3830 base_cell_coords = p_position;
3831 break;
3832 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
3833 bit = 2;
3834 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
3835 break;
3836 case TileSet::CELL_NEIGHBOR_LEFT_SIDE:
3837 bit = 1;
3838 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_LEFT_SIDE);
3839 break;
3840 case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
3841 bit = 4;
3842 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3843 break;
3844 case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
3845 bit = 3;
3846 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3847 break;
3848 case TileSet::CELL_NEIGHBOR_TOP_CORNER:
3849 bit = 2;
3850 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3851 break;
3852 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
3853 bit = 5;
3854 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
3855 break;
3856 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
3857 bit = 4;
3858 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
3859 break;
3860 default:
3861 ERR_FAIL();
3862 break;
3863 }
3864 } else {
3865 switch (p_bit) {
3866 case TileSet::CELL_NEIGHBOR_RIGHT_CORNER:
3867 bit = 1;
3868 base_cell_coords = p_position;
3869 break;
3870 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_SIDE:
3871 bit = 2;
3872 base_cell_coords = p_position;
3873 break;
3874 case TileSet::CELL_NEIGHBOR_BOTTOM_RIGHT_CORNER:
3875 bit = 3;
3876 base_cell_coords = p_position;
3877 break;
3878 case TileSet::CELL_NEIGHBOR_BOTTOM_SIDE:
3879 bit = 4;
3880 base_cell_coords = p_position;
3881 break;
3882 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_CORNER:
3883 bit = 1;
3884 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE);
3885 break;
3886 case TileSet::CELL_NEIGHBOR_BOTTOM_LEFT_SIDE:
3887 bit = 5;
3888 base_cell_coords = p_position;
3889 break;
3890 case TileSet::CELL_NEIGHBOR_LEFT_CORNER:
3891 bit = 3;
3892 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3893 break;
3894 case TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE:
3895 bit = 2;
3896 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3897 break;
3898 case TileSet::CELL_NEIGHBOR_TOP_LEFT_CORNER:
3899 bit = 1;
3900 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_LEFT_SIDE);
3901 break;
3902 case TileSet::CELL_NEIGHBOR_TOP_SIDE:
3903 bit = 4;
3904 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
3905 break;
3906 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_CORNER:
3907 bit = 3;
3908 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_SIDE);
3909 break;
3910 case TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE:
3911 bit = 5;
3912 base_cell_coords = tile_set->get_neighbor_cell(p_position, TileSet::CELL_NEIGHBOR_TOP_RIGHT_SIDE);
3913 break;
3914 default:
3915 ERR_FAIL();
3916 break;
3917 }
3918 }
3919 }
3920 terrain = p_terrain;
3921 }