Path: blob/master/modules/navigation_2d/2d/nav_map_builder_2d.cpp
11353 views
/**************************************************************************/1/* nav_map_builder_2d.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "nav_map_builder_2d.h"3132#include "../nav_link_2d.h"33#include "../nav_map_2d.h"34#include "../nav_region_2d.h"35#include "../triangle2.h"36#include "nav_map_iteration_2d.h"37#include "nav_region_iteration_2d.h"3839#include "core/config/project_settings.h"4041using namespace Nav2D;4243PointKey NavMapBuilder2D::get_point_key(const Vector2 &p_pos, const Vector2 &p_cell_size) {44const int x = static_cast<int>(Math::floor(p_pos.x / p_cell_size.x));45const int y = static_cast<int>(Math::floor(p_pos.y / p_cell_size.y));4647PointKey p;48p.key = 0;49p.x = x;50p.y = y;51return p;52}5354void NavMapBuilder2D::build_navmap_iteration(NavMapIterationBuild2D &r_build) {55PerformanceData &performance_data = r_build.performance_data;5657performance_data.pm_polygon_count = 0;58performance_data.pm_edge_count = 0;59performance_data.pm_edge_merge_count = 0;60performance_data.pm_edge_connection_count = 0;61performance_data.pm_edge_free_count = 0;6263_build_step_gather_region_polygons(r_build);6465_build_step_find_edge_connection_pairs(r_build);6667_build_step_merge_edge_connection_pairs(r_build);6869_build_step_edge_connection_margin_connections(r_build);7071_build_step_navlink_connections(r_build);7273_build_update_map_iteration(r_build);74}7576void NavMapBuilder2D::_build_step_gather_region_polygons(NavMapIterationBuild2D &r_build) {77PerformanceData &performance_data = r_build.performance_data;78NavMapIteration2D *map_iteration = r_build.map_iteration;7980const LocalVector<Ref<NavRegionIteration2D>> ®ions = map_iteration->region_iterations;81HashMap<const NavBaseIteration2D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;8283map_iteration->navbases_polygons_external_connections.clear();8485// Remove regions connections.86region_external_connections.clear();8788// Copy all region polygons in the map.89int polygon_count = 0;90for (const Ref<NavRegionIteration2D> ®ion : regions) {91const uint32_t polygons_size = region->navmesh_polygons.size();92polygon_count += polygons_size;9394region_external_connections[region.ptr()] = LocalVector<Connection>();95map_iteration->navbases_polygons_external_connections[region.ptr()] = LocalVector<LocalVector<Connection>>();96map_iteration->navbases_polygons_external_connections[region.ptr()].resize(polygons_size);97}9899performance_data.pm_polygon_count = polygon_count;100r_build.polygon_count = polygon_count;101}102103void NavMapBuilder2D::_build_step_find_edge_connection_pairs(NavMapIterationBuild2D &r_build) {104PerformanceData &performance_data = r_build.performance_data;105NavMapIteration2D *map_iteration = r_build.map_iteration;106int polygon_count = r_build.polygon_count;107108HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;109110// Group all edges per key.111connection_pairs_map.clear();112connection_pairs_map.reserve(polygon_count);113int free_edges_count = 0; // How many ConnectionPairs have only one Connection.114int edge_merge_error_count = 0;115116for (const Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {117for (const ConnectableEdge &connectable_edge : region->get_external_edges()) {118const EdgeKey &ek = connectable_edge.ek;119120HashMap<EdgeKey, EdgeConnectionPair, EdgeKey>::Iterator pair_it = connection_pairs_map.find(ek);121if (!pair_it) {122pair_it = connection_pairs_map.insert(ek, EdgeConnectionPair());123performance_data.pm_edge_count += 1;124++free_edges_count;125}126EdgeConnectionPair &pair = pair_it->value;127if (pair.size < 2) {128// Add the polygon/edge tuple to this key.129Connection new_connection;130new_connection.polygon = ®ion->navmesh_polygons[connectable_edge.polygon_index];131new_connection.edge = connectable_edge.edge;132new_connection.pathway_start = connectable_edge.pathway_start;133new_connection.pathway_end = connectable_edge.pathway_end;134135pair.connections[pair.size] = new_connection;136++pair.size;137if (pair.size == 2) {138--free_edges_count;139}140141} else {142// The edge is already connected with another edge, skip.143edge_merge_error_count++;144}145}146}147148if (edge_merge_error_count > 0 && GLOBAL_GET_CACHED(bool, "navigation/2d/warnings/navmesh_edge_merge_errors")) {149WARN_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.");150}151152r_build.free_edge_count = free_edges_count;153}154155void NavMapBuilder2D::_build_step_merge_edge_connection_pairs(NavMapIterationBuild2D &r_build) {156PerformanceData &performance_data = r_build.performance_data;157158HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;159LocalVector<Connection> &free_edges = r_build.iter_free_edges;160int free_edges_count = r_build.free_edge_count;161bool use_edge_connections = r_build.use_edge_connections;162163free_edges.clear();164free_edges.reserve(free_edges_count);165166NavMapIteration2D *map_iteration = r_build.map_iteration;167168HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;169170for (const KeyValue<EdgeKey, EdgeConnectionPair> &pair_it : connection_pairs_map) {171const EdgeConnectionPair &pair = pair_it.value;172if (pair.size == 2) {173// Connect edge that are shared in different polygons.174const Connection &c1 = pair.connections[0];175const Connection &c2 = pair.connections[1];176177navbases_polygons_external_connections[c1.polygon->owner][c1.polygon->id].push_back(c2);178navbases_polygons_external_connections[c2.polygon->owner][c2.polygon->id].push_back(c1);179performance_data.pm_edge_connection_count += 1;180181} else {182CRASH_COND_MSG(pair.size != 1, vformat("Number of connection != 1. Found: %d", pair.size));183if (use_edge_connections && pair.connections[0].polygon->owner->get_use_edge_connections()) {184free_edges.push_back(pair.connections[0]);185}186}187}188}189190void NavMapBuilder2D::_build_step_edge_connection_margin_connections(NavMapIterationBuild2D &r_build) {191PerformanceData &performance_data = r_build.performance_data;192NavMapIteration2D *map_iteration = r_build.map_iteration;193194real_t edge_connection_margin = r_build.edge_connection_margin;195196LocalVector<Connection> &free_edges = r_build.iter_free_edges;197HashMap<const NavBaseIteration2D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;198199HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;200201// Find the compatible near edges.202//203// Note:204// Considering that the edges must be compatible (for obvious reasons)205// to be connected, create new polygons to remove that small gap is206// not really useful and would result in wasteful computation during207// connection, integration and path finding.208performance_data.pm_edge_free_count = free_edges.size();209210const real_t edge_connection_margin_squared = edge_connection_margin * edge_connection_margin;211212for (uint32_t i = 0; i < free_edges.size(); i++) {213const Connection &free_edge = free_edges[i];214const Vector2 &edge_p1 = free_edge.pathway_start;215const Vector2 &edge_p2 = free_edge.pathway_end;216217for (uint32_t j = 0; j < free_edges.size(); j++) {218const Connection &other_edge = free_edges[j];219if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {220continue;221}222223const Vector2 &other_edge_p1 = other_edge.pathway_start;224const Vector2 &other_edge_p2 = other_edge.pathway_end;225226// Compute the projection of the opposite edge on the current one227Vector2 edge_vector = edge_p2 - edge_p1;228real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());229real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());230if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {231continue;232}233234// Check if the two edges are close to each other enough and compute a pathway between the two regions.235Vector2 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;236Vector2 other1;237if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {238other1 = other_edge_p1;239} else {240other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));241}242if (other1.distance_squared_to(self1) > edge_connection_margin_squared) {243continue;244}245246Vector2 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;247Vector2 other2;248if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {249other2 = other_edge_p2;250} else {251other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));252}253if (other2.distance_squared_to(self2) > edge_connection_margin_squared) {254continue;255}256257// The edges can now be connected.258Connection new_connection = other_edge;259new_connection.pathway_start = (self1 + other1) / 2.0;260new_connection.pathway_end = (self2 + other2) / 2.0;261//free_edge.polygon->connections.push_back(new_connection);262263// Add the connection to the region_connection map.264region_external_connections[free_edge.polygon->owner].push_back(new_connection);265navbases_polygons_external_connections[free_edge.polygon->owner][free_edge.polygon->id].push_back(new_connection);266performance_data.pm_edge_connection_count += 1;267}268}269}270271void NavMapBuilder2D::_build_step_navlink_connections(NavMapIterationBuild2D &r_build) {272NavMapIteration2D *map_iteration = r_build.map_iteration;273274real_t link_connection_radius = r_build.link_connection_radius;275276const LocalVector<Ref<NavLinkIteration2D>> &links = map_iteration->link_iterations;277278int polygon_count = r_build.polygon_count;279280real_t link_connection_radius_sqr = link_connection_radius * link_connection_radius;281282HashMap<const NavBaseIteration2D *, LocalVector<LocalVector<Nav2D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;283LocalVector<Nav2D::Polygon> &navlink_polygons = map_iteration->navlink_polygons;284navlink_polygons.clear();285navlink_polygons.resize(links.size());286uint32_t navlink_index = 0;287288// Search for polygons within range of a nav link.289for (const Ref<NavLinkIteration2D> &link : links) {290polygon_count++;291Polygon &new_polygon = navlink_polygons[navlink_index++];292293new_polygon.id = 0;294new_polygon.owner = link.ptr();295296const Vector2 link_start_pos = link->get_start_position();297const Vector2 link_end_pos = link->get_end_position();298299Polygon *closest_start_polygon = nullptr;300real_t closest_start_sqr_dist = link_connection_radius_sqr;301Vector2 closest_start_point;302303Polygon *closest_end_polygon = nullptr;304real_t closest_end_sqr_dist = link_connection_radius_sqr;305Vector2 closest_end_point;306307for (const Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {308Rect2 region_bounds = region->get_bounds().grow(link_connection_radius);309if (!region_bounds.has_point(link_start_pos) && !region_bounds.has_point(link_end_pos)) {310continue;311}312313for (Polygon &polyon : region->navmesh_polygons) {314for (uint32_t point_id = 2; point_id < polyon.vertices.size(); point_id += 1) {315const Triangle2 triangle(polyon.vertices[0], polyon.vertices[point_id - 1], polyon.vertices[point_id]);316317{318const Vector2 start_point = triangle.get_closest_point_to(link_start_pos);319const real_t sqr_dist = start_point.distance_squared_to(link_start_pos);320321// Pick the polygon that is within our radius and is closer than anything we've seen yet.322if (sqr_dist < closest_start_sqr_dist) {323closest_start_sqr_dist = sqr_dist;324closest_start_point = start_point;325closest_start_polygon = &polyon;326}327}328329{330const Vector2 end_point = triangle.get_closest_point_to(link_end_pos);331const real_t sqr_dist = end_point.distance_squared_to(link_end_pos);332333// Pick the polygon that is within our radius and is closer than anything we've seen yet.334if (sqr_dist < closest_end_sqr_dist) {335closest_end_sqr_dist = sqr_dist;336closest_end_point = end_point;337closest_end_polygon = &polyon;338}339}340}341}342}343344// If we have both a start and end point, then create a synthetic polygon to route through.345if (closest_start_polygon && closest_end_polygon) {346new_polygon.vertices.resize(4);347348// Build a set of vertices that create a thin polygon going from the start to the end point.349new_polygon.vertices[0] = closest_start_point;350new_polygon.vertices[1] = closest_start_point;351new_polygon.vertices[2] = closest_end_point;352new_polygon.vertices[3] = closest_end_point;353354// Setup connections to go forward in the link.355{356Connection entry_connection;357entry_connection.polygon = &new_polygon;358entry_connection.edge = -1;359entry_connection.pathway_start = new_polygon.vertices[0];360entry_connection.pathway_end = new_polygon.vertices[1];361navbases_polygons_external_connections[closest_start_polygon->owner][closest_start_polygon->id].push_back(entry_connection);362363Connection exit_connection;364exit_connection.polygon = closest_end_polygon;365exit_connection.edge = -1;366exit_connection.pathway_start = new_polygon.vertices[2];367exit_connection.pathway_end = new_polygon.vertices[3];368navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());369navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);370}371372// If the link is bi-directional, create connections from the end to the start.373if (link->is_bidirectional()) {374Connection entry_connection;375entry_connection.polygon = &new_polygon;376entry_connection.edge = -1;377entry_connection.pathway_start = new_polygon.vertices[2];378entry_connection.pathway_end = new_polygon.vertices[3];379navbases_polygons_external_connections[closest_end_polygon->owner][closest_end_polygon->id].push_back(entry_connection);380381Connection exit_connection;382exit_connection.polygon = closest_start_polygon;383exit_connection.edge = -1;384exit_connection.pathway_start = new_polygon.vertices[0];385exit_connection.pathway_end = new_polygon.vertices[1];386navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav2D::Connection>());387navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);388}389}390}391392r_build.polygon_count = polygon_count;393}394395void NavMapBuilder2D::_build_update_map_iteration(NavMapIterationBuild2D &r_build) {396NavMapIteration2D *map_iteration = r_build.map_iteration;397398map_iteration->navmesh_polygon_count = r_build.polygon_count;399400uint32_t navmesh_polygon_count = r_build.polygon_count;401uint32_t total_polygon_count = navmesh_polygon_count;402403map_iteration->path_query_slots_mutex.lock();404for (NavMeshQueries2D::PathQuerySlot &p_path_query_slot : map_iteration->path_query_slots) {405p_path_query_slot.traversable_polys.clear();406p_path_query_slot.traversable_polys.reserve(navmesh_polygon_count * 0.25);407p_path_query_slot.path_corridor.clear();408409p_path_query_slot.path_corridor.resize(total_polygon_count);410411p_path_query_slot.poly_to_id.clear();412p_path_query_slot.poly_to_id.reserve(total_polygon_count);413414int polygon_id = 0;415for (Ref<NavRegionIteration2D> ®ion : map_iteration->region_iterations) {416for (const Polygon &polygon : region->navmesh_polygons) {417p_path_query_slot.poly_to_id[&polygon] = polygon_id;418polygon_id++;419}420}421422for (const Polygon &polygon : map_iteration->navlink_polygons) {423p_path_query_slot.poly_to_id[&polygon] = polygon_id;424polygon_id++;425}426427DEV_ASSERT(p_path_query_slot.path_corridor.size() == p_path_query_slot.poly_to_id.size());428}429430map_iteration->path_query_slots_mutex.unlock();431}432433434