Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/navigation_2d/2d/nav_map_builder_2d.cpp
11353 views
1
/**************************************************************************/
2
/* nav_map_builder_2d.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 "nav_map_builder_2d.h"
32
33
#include "../nav_link_2d.h"
34
#include "../nav_map_2d.h"
35
#include "../nav_region_2d.h"
36
#include "../triangle2.h"
37
#include "nav_map_iteration_2d.h"
38
#include "nav_region_iteration_2d.h"
39
40
#include "core/config/project_settings.h"
41
42
using namespace Nav2D;
43
44
PointKey NavMapBuilder2D::get_point_key(const Vector2 &p_pos, const Vector2 &p_cell_size) {
45
const int x = static_cast<int>(Math::floor(p_pos.x / p_cell_size.x));
46
const int y = static_cast<int>(Math::floor(p_pos.y / p_cell_size.y));
47
48
PointKey p;
49
p.key = 0;
50
p.x = x;
51
p.y = y;
52
return p;
53
}
54
55
void NavMapBuilder2D::build_navmap_iteration(NavMapIterationBuild2D &r_build) {
56
PerformanceData &performance_data = r_build.performance_data;
57
58
performance_data.pm_polygon_count = 0;
59
performance_data.pm_edge_count = 0;
60
performance_data.pm_edge_merge_count = 0;
61
performance_data.pm_edge_connection_count = 0;
62
performance_data.pm_edge_free_count = 0;
63
64
_build_step_gather_region_polygons(r_build);
65
66
_build_step_find_edge_connection_pairs(r_build);
67
68
_build_step_merge_edge_connection_pairs(r_build);
69
70
_build_step_edge_connection_margin_connections(r_build);
71
72
_build_step_navlink_connections(r_build);
73
74
_build_update_map_iteration(r_build);
75
}
76
77
void NavMapBuilder2D::_build_step_gather_region_polygons(NavMapIterationBuild2D &r_build) {
78
PerformanceData &performance_data = r_build.performance_data;
79
NavMapIteration2D *map_iteration = r_build.map_iteration;
80
81
const LocalVector<Ref<NavRegionIteration2D>> &regions = map_iteration->region_iterations;
82
HashMap<const NavBaseIteration2D *, LocalVector<Connection>> &region_external_connections = map_iteration->external_region_connections;
83
84
map_iteration->navbases_polygons_external_connections.clear();
85
86
// Remove regions connections.
87
region_external_connections.clear();
88
89
// Copy all region polygons in the map.
90
int polygon_count = 0;
91
for (const Ref<NavRegionIteration2D> &region : regions) {
92
const uint32_t polygons_size = region->navmesh_polygons.size();
93
polygon_count += polygons_size;
94
95
region_external_connections[region.ptr()] = LocalVector<Connection>();
96
map_iteration->navbases_polygons_external_connections[region.ptr()] = LocalVector<LocalVector<Connection>>();
97
map_iteration->navbases_polygons_external_connections[region.ptr()].resize(polygons_size);
98
}
99
100
performance_data.pm_polygon_count = polygon_count;
101
r_build.polygon_count = polygon_count;
102
}
103
104
void NavMapBuilder2D::_build_step_find_edge_connection_pairs(NavMapIterationBuild2D &r_build) {
105
PerformanceData &performance_data = r_build.performance_data;
106
NavMapIteration2D *map_iteration = r_build.map_iteration;
107
int polygon_count = r_build.polygon_count;
108
109
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;
110
111
// Group all edges per key.
112
connection_pairs_map.clear();
113
connection_pairs_map.reserve(polygon_count);
114
int free_edges_count = 0; // How many ConnectionPairs have only one Connection.
115
int edge_merge_error_count = 0;
116
117
for (const Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
118
for (const ConnectableEdge &connectable_edge : region->get_external_edges()) {
119
const EdgeKey &ek = connectable_edge.ek;
120
121
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey>::Iterator pair_it = connection_pairs_map.find(ek);
122
if (!pair_it) {
123
pair_it = connection_pairs_map.insert(ek, EdgeConnectionPair());
124
performance_data.pm_edge_count += 1;
125
++free_edges_count;
126
}
127
EdgeConnectionPair &pair = pair_it->value;
128
if (pair.size < 2) {
129
// Add the polygon/edge tuple to this key.
130
Connection new_connection;
131
new_connection.polygon = &region->navmesh_polygons[connectable_edge.polygon_index];
132
new_connection.edge = connectable_edge.edge;
133
new_connection.pathway_start = connectable_edge.pathway_start;
134
new_connection.pathway_end = connectable_edge.pathway_end;
135
136
pair.connections[pair.size] = new_connection;
137
++pair.size;
138
if (pair.size == 2) {
139
--free_edges_count;
140
}
141
142
} else {
143
// The edge is already connected with another edge, skip.
144
edge_merge_error_count++;
145
}
146
}
147
}
148
149
if (edge_merge_error_count > 0 && GLOBAL_GET_CACHED(bool, "navigation/2d/warnings/navmesh_edge_merge_errors")) {
150
WARN_PRINT("Navigation map synchronization had " + itos(edge_merge_error_count) + " edge error(s).\nMore than 2 edges tried to occupy the same map rasterization space.\nThis causes a logical error in the navigation mesh geometry and is commonly caused by overlap or too densely placed edges.\nConsider baking with a higher 'cell_size', greater geometry margin, and less detailed bake objects to cause fewer edges.\nConsider lowering the 'navigation/2d/merge_rasterizer_cell_scale' in the project settings.\nThis warning can be toggled under 'navigation/2d/warnings/navmesh_edge_merge_errors' in the project settings.");
151
}
152
153
r_build.free_edge_count = free_edges_count;
154
}
155
156
void NavMapBuilder2D::_build_step_merge_edge_connection_pairs(NavMapIterationBuild2D &r_build) {
157
PerformanceData &performance_data = r_build.performance_data;
158
159
HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;
160
LocalVector<Connection> &free_edges = r_build.iter_free_edges;
161
int free_edges_count = r_build.free_edge_count;
162
bool use_edge_connections = r_build.use_edge_connections;
163
164
free_edges.clear();
165
free_edges.reserve(free_edges_count);
166
167
NavMapIteration2D *map_iteration = r_build.map_iteration;
168
169
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
170
171
for (const KeyValue<EdgeKey, EdgeConnectionPair> &pair_it : connection_pairs_map) {
172
const EdgeConnectionPair &pair = pair_it.value;
173
if (pair.size == 2) {
174
// Connect edge that are shared in different polygons.
175
const Connection &c1 = pair.connections[0];
176
const Connection &c2 = pair.connections[1];
177
178
navbases_polygons_external_connections[c1.polygon->owner][c1.polygon->id].push_back(c2);
179
navbases_polygons_external_connections[c2.polygon->owner][c2.polygon->id].push_back(c1);
180
performance_data.pm_edge_connection_count += 1;
181
182
} else {
183
CRASH_COND_MSG(pair.size != 1, vformat("Number of connection != 1. Found: %d", pair.size));
184
if (use_edge_connections && pair.connections[0].polygon->owner->get_use_edge_connections()) {
185
free_edges.push_back(pair.connections[0]);
186
}
187
}
188
}
189
}
190
191
void NavMapBuilder2D::_build_step_edge_connection_margin_connections(NavMapIterationBuild2D &r_build) {
192
PerformanceData &performance_data = r_build.performance_data;
193
NavMapIteration2D *map_iteration = r_build.map_iteration;
194
195
real_t edge_connection_margin = r_build.edge_connection_margin;
196
197
LocalVector<Connection> &free_edges = r_build.iter_free_edges;
198
HashMap<const NavBaseIteration2D *, LocalVector<Connection>> &region_external_connections = map_iteration->external_region_connections;
199
200
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
201
202
// Find the compatible near edges.
203
//
204
// Note:
205
// Considering that the edges must be compatible (for obvious reasons)
206
// to be connected, create new polygons to remove that small gap is
207
// not really useful and would result in wasteful computation during
208
// connection, integration and path finding.
209
performance_data.pm_edge_free_count = free_edges.size();
210
211
const real_t edge_connection_margin_squared = edge_connection_margin * edge_connection_margin;
212
213
for (uint32_t i = 0; i < free_edges.size(); i++) {
214
const Connection &free_edge = free_edges[i];
215
const Vector2 &edge_p1 = free_edge.pathway_start;
216
const Vector2 &edge_p2 = free_edge.pathway_end;
217
218
for (uint32_t j = 0; j < free_edges.size(); j++) {
219
const Connection &other_edge = free_edges[j];
220
if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
221
continue;
222
}
223
224
const Vector2 &other_edge_p1 = other_edge.pathway_start;
225
const Vector2 &other_edge_p2 = other_edge.pathway_end;
226
227
// Compute the projection of the opposite edge on the current one
228
Vector2 edge_vector = edge_p2 - edge_p1;
229
real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
230
real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
231
if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
232
continue;
233
}
234
235
// Check if the two edges are close to each other enough and compute a pathway between the two regions.
236
Vector2 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
237
Vector2 other1;
238
if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
239
other1 = other_edge_p1;
240
} else {
241
other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
242
}
243
if (other1.distance_squared_to(self1) > edge_connection_margin_squared) {
244
continue;
245
}
246
247
Vector2 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
248
Vector2 other2;
249
if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
250
other2 = other_edge_p2;
251
} else {
252
other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
253
}
254
if (other2.distance_squared_to(self2) > edge_connection_margin_squared) {
255
continue;
256
}
257
258
// The edges can now be connected.
259
Connection new_connection = other_edge;
260
new_connection.pathway_start = (self1 + other1) / 2.0;
261
new_connection.pathway_end = (self2 + other2) / 2.0;
262
//free_edge.polygon->connections.push_back(new_connection);
263
264
// Add the connection to the region_connection map.
265
region_external_connections[free_edge.polygon->owner].push_back(new_connection);
266
navbases_polygons_external_connections[free_edge.polygon->owner][free_edge.polygon->id].push_back(new_connection);
267
performance_data.pm_edge_connection_count += 1;
268
}
269
}
270
}
271
272
void NavMapBuilder2D::_build_step_navlink_connections(NavMapIterationBuild2D &r_build) {
273
NavMapIteration2D *map_iteration = r_build.map_iteration;
274
275
real_t link_connection_radius = r_build.link_connection_radius;
276
277
const LocalVector<Ref<NavLinkIteration2D>> &links = map_iteration->link_iterations;
278
279
int polygon_count = r_build.polygon_count;
280
281
real_t link_connection_radius_sqr = link_connection_radius * link_connection_radius;
282
283
HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;
284
LocalVector<Nav2D::Polygon> &navlink_polygons = map_iteration->navlink_polygons;
285
navlink_polygons.clear();
286
navlink_polygons.resize(links.size());
287
uint32_t navlink_index = 0;
288
289
// Search for polygons within range of a nav link.
290
for (const Ref<NavLinkIteration2D> &link : links) {
291
polygon_count++;
292
Polygon &new_polygon = navlink_polygons[navlink_index++];
293
294
new_polygon.id = 0;
295
new_polygon.owner = link.ptr();
296
297
const Vector2 link_start_pos = link->get_start_position();
298
const Vector2 link_end_pos = link->get_end_position();
299
300
Polygon *closest_start_polygon = nullptr;
301
real_t closest_start_sqr_dist = link_connection_radius_sqr;
302
Vector2 closest_start_point;
303
304
Polygon *closest_end_polygon = nullptr;
305
real_t closest_end_sqr_dist = link_connection_radius_sqr;
306
Vector2 closest_end_point;
307
308
for (const Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
309
Rect2 region_bounds = region->get_bounds().grow(link_connection_radius);
310
if (!region_bounds.has_point(link_start_pos) && !region_bounds.has_point(link_end_pos)) {
311
continue;
312
}
313
314
for (Polygon &polyon : region->navmesh_polygons) {
315
for (uint32_t point_id = 2; point_id < polyon.vertices.size(); point_id += 1) {
316
const Triangle2 triangle(polyon.vertices[0], polyon.vertices[point_id - 1], polyon.vertices[point_id]);
317
318
{
319
const Vector2 start_point = triangle.get_closest_point_to(link_start_pos);
320
const real_t sqr_dist = start_point.distance_squared_to(link_start_pos);
321
322
// Pick the polygon that is within our radius and is closer than anything we've seen yet.
323
if (sqr_dist < closest_start_sqr_dist) {
324
closest_start_sqr_dist = sqr_dist;
325
closest_start_point = start_point;
326
closest_start_polygon = &polyon;
327
}
328
}
329
330
{
331
const Vector2 end_point = triangle.get_closest_point_to(link_end_pos);
332
const real_t sqr_dist = end_point.distance_squared_to(link_end_pos);
333
334
// Pick the polygon that is within our radius and is closer than anything we've seen yet.
335
if (sqr_dist < closest_end_sqr_dist) {
336
closest_end_sqr_dist = sqr_dist;
337
closest_end_point = end_point;
338
closest_end_polygon = &polyon;
339
}
340
}
341
}
342
}
343
}
344
345
// If we have both a start and end point, then create a synthetic polygon to route through.
346
if (closest_start_polygon && closest_end_polygon) {
347
new_polygon.vertices.resize(4);
348
349
// Build a set of vertices that create a thin polygon going from the start to the end point.
350
new_polygon.vertices[0] = closest_start_point;
351
new_polygon.vertices[1] = closest_start_point;
352
new_polygon.vertices[2] = closest_end_point;
353
new_polygon.vertices[3] = closest_end_point;
354
355
// Setup connections to go forward in the link.
356
{
357
Connection entry_connection;
358
entry_connection.polygon = &new_polygon;
359
entry_connection.edge = -1;
360
entry_connection.pathway_start = new_polygon.vertices[0];
361
entry_connection.pathway_end = new_polygon.vertices[1];
362
navbases_polygons_external_connections[closest_start_polygon->owner][closest_start_polygon->id].push_back(entry_connection);
363
364
Connection exit_connection;
365
exit_connection.polygon = closest_end_polygon;
366
exit_connection.edge = -1;
367
exit_connection.pathway_start = new_polygon.vertices[2];
368
exit_connection.pathway_end = new_polygon.vertices[3];
369
navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());
370
navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);
371
}
372
373
// If the link is bi-directional, create connections from the end to the start.
374
if (link->is_bidirectional()) {
375
Connection entry_connection;
376
entry_connection.polygon = &new_polygon;
377
entry_connection.edge = -1;
378
entry_connection.pathway_start = new_polygon.vertices[2];
379
entry_connection.pathway_end = new_polygon.vertices[3];
380
navbases_polygons_external_connections[closest_end_polygon->owner][closest_end_polygon->id].push_back(entry_connection);
381
382
Connection exit_connection;
383
exit_connection.polygon = closest_start_polygon;
384
exit_connection.edge = -1;
385
exit_connection.pathway_start = new_polygon.vertices[0];
386
exit_connection.pathway_end = new_polygon.vertices[1];
387
navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());
388
navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);
389
}
390
}
391
}
392
393
r_build.polygon_count = polygon_count;
394
}
395
396
void NavMapBuilder2D::_build_update_map_iteration(NavMapIterationBuild2D &r_build) {
397
NavMapIteration2D *map_iteration = r_build.map_iteration;
398
399
map_iteration->navmesh_polygon_count = r_build.polygon_count;
400
401
uint32_t navmesh_polygon_count = r_build.polygon_count;
402
uint32_t total_polygon_count = navmesh_polygon_count;
403
404
map_iteration->path_query_slots_mutex.lock();
405
for (NavMeshQueries2D::PathQuerySlot &p_path_query_slot : map_iteration->path_query_slots) {
406
p_path_query_slot.traversable_polys.clear();
407
p_path_query_slot.traversable_polys.reserve(navmesh_polygon_count * 0.25);
408
p_path_query_slot.path_corridor.clear();
409
410
p_path_query_slot.path_corridor.resize(total_polygon_count);
411
412
p_path_query_slot.poly_to_id.clear();
413
p_path_query_slot.poly_to_id.reserve(total_polygon_count);
414
415
int polygon_id = 0;
416
for (Ref<NavRegionIteration2D> &region : map_iteration->region_iterations) {
417
for (const Polygon &polygon : region->navmesh_polygons) {
418
p_path_query_slot.poly_to_id[&polygon] = polygon_id;
419
polygon_id++;
420
}
421
}
422
423
for (const Polygon &polygon : map_iteration->navlink_polygons) {
424
p_path_query_slot.poly_to_id[&polygon] = polygon_id;
425
polygon_id++;
426
}
427
428
DEV_ASSERT(p_path_query_slot.path_corridor.size() == p_path_query_slot.poly_to_id.size());
429
}
430
431
map_iteration->path_query_slots_mutex.unlock();
432
}
433
434