Path: blob/master/modules/navigation_3d/3d/nav_map_builder_3d.cpp
10278 views
/**************************************************************************/1/* nav_map_builder_3d.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_3d.h"3132#include "../nav_link_3d.h"33#include "../nav_map_3d.h"34#include "../nav_region_3d.h"35#include "nav_map_iteration_3d.h"36#include "nav_region_iteration_3d.h"3738using namespace Nav3D;3940PointKey NavMapBuilder3D::get_point_key(const Vector3 &p_pos, const Vector3 &p_cell_size) {41const int x = static_cast<int>(Math::floor(p_pos.x / p_cell_size.x));42const int y = static_cast<int>(Math::floor(p_pos.y / p_cell_size.y));43const int z = static_cast<int>(Math::floor(p_pos.z / p_cell_size.z));4445PointKey p;46p.key = 0;47p.x = x;48p.y = y;49p.z = z;50return p;51}5253void NavMapBuilder3D::build_navmap_iteration(NavMapIterationBuild3D &r_build) {54PerformanceData &performance_data = r_build.performance_data;5556performance_data.pm_polygon_count = 0;57performance_data.pm_edge_count = 0;58performance_data.pm_edge_merge_count = 0;59performance_data.pm_edge_connection_count = 0;60performance_data.pm_edge_free_count = 0;6162_build_step_gather_region_polygons(r_build);6364_build_step_find_edge_connection_pairs(r_build);6566_build_step_merge_edge_connection_pairs(r_build);6768_build_step_edge_connection_margin_connections(r_build);6970_build_step_navlink_connections(r_build);7172_build_update_map_iteration(r_build);73}7475void NavMapBuilder3D::_build_step_gather_region_polygons(NavMapIterationBuild3D &r_build) {76PerformanceData &performance_data = r_build.performance_data;77NavMapIteration3D *map_iteration = r_build.map_iteration;7879const LocalVector<Ref<NavRegionIteration3D>> ®ions = map_iteration->region_iterations;80HashMap<const NavBaseIteration3D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;8182map_iteration->navbases_polygons_external_connections.clear();8384// Remove regions connections.85region_external_connections.clear();8687// Copy all region polygons in the map.88int polygon_count = 0;89for (const Ref<NavRegionIteration3D> ®ion : regions) {90const uint32_t polygons_size = region->navmesh_polygons.size();91polygon_count += polygons_size;9293region_external_connections[region.ptr()] = LocalVector<Connection>();94map_iteration->navbases_polygons_external_connections[region.ptr()] = LocalVector<LocalVector<Connection>>();95map_iteration->navbases_polygons_external_connections[region.ptr()].resize(polygons_size);96}9798performance_data.pm_polygon_count = polygon_count;99r_build.polygon_count = polygon_count;100}101102void NavMapBuilder3D::_build_step_find_edge_connection_pairs(NavMapIterationBuild3D &r_build) {103PerformanceData &performance_data = r_build.performance_data;104NavMapIteration3D *map_iteration = r_build.map_iteration;105int polygon_count = r_build.polygon_count;106107HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;108109// Group all edges per key.110connection_pairs_map.clear();111connection_pairs_map.reserve(polygon_count);112int free_edges_count = 0; // How many ConnectionPairs have only one Connection.113114for (const Ref<NavRegionIteration3D> ®ion : map_iteration->region_iterations) {115for (const ConnectableEdge &connectable_edge : region->get_external_edges()) {116const EdgeKey &ek = connectable_edge.ek;117118HashMap<EdgeKey, EdgeConnectionPair, EdgeKey>::Iterator pair_it = connection_pairs_map.find(ek);119if (!pair_it) {120pair_it = connection_pairs_map.insert(ek, EdgeConnectionPair());121performance_data.pm_edge_count += 1;122++free_edges_count;123}124EdgeConnectionPair &pair = pair_it->value;125if (pair.size < 2) {126// Add the polygon/edge tuple to this key.127Connection new_connection;128new_connection.polygon = ®ion->navmesh_polygons[connectable_edge.polygon_index];129new_connection.edge = connectable_edge.edge;130new_connection.pathway_start = connectable_edge.pathway_start;131new_connection.pathway_end = connectable_edge.pathway_end;132133pair.connections[pair.size] = new_connection;134++pair.size;135if (pair.size == 2) {136--free_edges_count;137}138139} else {140// The edge is already connected with another edge, skip.141ERR_PRINT_ONCE("Navigation map synchronization error. Attempted to merge a navigation mesh polygon edge with another already-merged edge. This is usually caused by crossing edges, overlapping polygons, or a mismatch of the NavigationMesh / NavigationPolygon baked 'cell_size' and navigation map 'cell_size'. If you're certain none of above is the case, change 'navigation/3d/merge_rasterizer_cell_scale' to 0.001.");142}143}144}145146r_build.free_edge_count = free_edges_count;147}148149void NavMapBuilder3D::_build_step_merge_edge_connection_pairs(NavMapIterationBuild3D &r_build) {150PerformanceData &performance_data = r_build.performance_data;151152HashMap<EdgeKey, EdgeConnectionPair, EdgeKey> &connection_pairs_map = r_build.iter_connection_pairs_map;153LocalVector<Connection> &free_edges = r_build.iter_free_edges;154int free_edges_count = r_build.free_edge_count;155bool use_edge_connections = r_build.use_edge_connections;156157free_edges.clear();158free_edges.reserve(free_edges_count);159160NavMapIteration3D *map_iteration = r_build.map_iteration;161162HashMap<const NavBaseIteration3D *, LocalVector<LocalVector<Nav3D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;163164for (const KeyValue<EdgeKey, EdgeConnectionPair> &pair_it : connection_pairs_map) {165const EdgeConnectionPair &pair = pair_it.value;166if (pair.size == 2) {167// Connect edge that are shared in different polygons.168const Connection &c1 = pair.connections[0];169const Connection &c2 = pair.connections[1];170171navbases_polygons_external_connections[c1.polygon->owner][c1.polygon->id].push_back(c2);172navbases_polygons_external_connections[c2.polygon->owner][c2.polygon->id].push_back(c1);173performance_data.pm_edge_connection_count += 1;174175} else {176CRASH_COND_MSG(pair.size != 1, vformat("Number of connection != 1. Found: %d", pair.size));177if (use_edge_connections && pair.connections[0].polygon->owner->get_use_edge_connections()) {178free_edges.push_back(pair.connections[0]);179}180}181}182}183184void NavMapBuilder3D::_build_step_edge_connection_margin_connections(NavMapIterationBuild3D &r_build) {185PerformanceData &performance_data = r_build.performance_data;186NavMapIteration3D *map_iteration = r_build.map_iteration;187188real_t edge_connection_margin = r_build.edge_connection_margin;189190LocalVector<Connection> &free_edges = r_build.iter_free_edges;191HashMap<const NavBaseIteration3D *, LocalVector<Connection>> ®ion_external_connections = map_iteration->external_region_connections;192193HashMap<const NavBaseIteration3D *, LocalVector<LocalVector<Nav3D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;194195// Find the compatible near edges.196//197// Note:198// Considering that the edges must be compatible (for obvious reasons)199// to be connected, create new polygons to remove that small gap is200// not really useful and would result in wasteful computation during201// connection, integration and path finding.202performance_data.pm_edge_free_count = free_edges.size();203204const real_t edge_connection_margin_squared = edge_connection_margin * edge_connection_margin;205206for (uint32_t i = 0; i < free_edges.size(); i++) {207const Connection &free_edge = free_edges[i];208const Vector3 &edge_p1 = free_edge.pathway_start;209const Vector3 &edge_p2 = free_edge.pathway_end;210211for (uint32_t j = 0; j < free_edges.size(); j++) {212const Connection &other_edge = free_edges[j];213if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {214continue;215}216217const Vector3 &other_edge_p1 = other_edge.pathway_start;218const Vector3 &other_edge_p2 = other_edge.pathway_end;219220// Compute the projection of the opposite edge on the current one221Vector3 edge_vector = edge_p2 - edge_p1;222real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());223real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());224if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {225continue;226}227228// Check if the two edges are close to each other enough and compute a pathway between the two regions.229Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;230Vector3 other1;231if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {232other1 = other_edge_p1;233} else {234other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));235}236if (other1.distance_squared_to(self1) > edge_connection_margin_squared) {237continue;238}239240Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;241Vector3 other2;242if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {243other2 = other_edge_p2;244} else {245other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));246}247if (other2.distance_squared_to(self2) > edge_connection_margin_squared) {248continue;249}250251// The edges can now be connected.252Connection new_connection = other_edge;253new_connection.pathway_start = (self1 + other1) / 2.0;254new_connection.pathway_end = (self2 + other2) / 2.0;255//free_edge.polygon->connections.push_back(new_connection);256257// Add the connection to the region_connection map.258region_external_connections[free_edge.polygon->owner].push_back(new_connection);259navbases_polygons_external_connections[free_edge.polygon->owner][free_edge.polygon->id].push_back(new_connection);260performance_data.pm_edge_connection_count += 1;261}262}263}264265void NavMapBuilder3D::_build_step_navlink_connections(NavMapIterationBuild3D &r_build) {266NavMapIteration3D *map_iteration = r_build.map_iteration;267268real_t link_connection_radius = r_build.link_connection_radius;269270const LocalVector<Ref<NavLinkIteration3D>> &links = map_iteration->link_iterations;271272int polygon_count = r_build.polygon_count;273274real_t link_connection_radius_sqr = link_connection_radius * link_connection_radius;275276HashMap<const NavBaseIteration3D *, LocalVector<LocalVector<Nav3D::Connection>>> &navbases_polygons_external_connections = map_iteration->navbases_polygons_external_connections;277LocalVector<Nav3D::Polygon> &navlink_polygons = map_iteration->navlink_polygons;278navlink_polygons.clear();279navlink_polygons.resize(links.size());280uint32_t navlink_index = 0;281282// Search for polygons within range of a nav link.283for (const Ref<NavLinkIteration3D> &link : links) {284polygon_count++;285Polygon &new_polygon = navlink_polygons[navlink_index++];286287new_polygon.id = 0;288new_polygon.owner = link.ptr();289290const Vector3 link_start_pos = link->get_start_position();291const Vector3 link_end_pos = link->get_end_position();292293Polygon *closest_start_polygon = nullptr;294real_t closest_start_sqr_dist = link_connection_radius_sqr;295Vector3 closest_start_point;296297Polygon *closest_end_polygon = nullptr;298real_t closest_end_sqr_dist = link_connection_radius_sqr;299Vector3 closest_end_point;300301for (const Ref<NavRegionIteration3D> ®ion : map_iteration->region_iterations) {302AABB region_bounds = region->get_bounds().grow(link_connection_radius);303if (!region_bounds.has_point(link_start_pos) && !region_bounds.has_point(link_end_pos)) {304continue;305}306307for (Polygon &polyon : region->navmesh_polygons) {308for (uint32_t point_id = 2; point_id < polyon.vertices.size(); point_id += 1) {309const Face3 face(polyon.vertices[0], polyon.vertices[point_id - 1], polyon.vertices[point_id]);310311{312const Vector3 start_point = face.get_closest_point_to(link_start_pos);313const real_t sqr_dist = start_point.distance_squared_to(link_start_pos);314315// Pick the polygon that is within our radius and is closer than anything we've seen yet.316if (sqr_dist < closest_start_sqr_dist) {317closest_start_sqr_dist = sqr_dist;318closest_start_point = start_point;319closest_start_polygon = &polyon;320}321}322323{324const Vector3 end_point = face.get_closest_point_to(link_end_pos);325const real_t sqr_dist = end_point.distance_squared_to(link_end_pos);326327// Pick the polygon that is within our radius and is closer than anything we've seen yet.328if (sqr_dist < closest_end_sqr_dist) {329closest_end_sqr_dist = sqr_dist;330closest_end_point = end_point;331closest_end_polygon = &polyon;332}333}334}335}336}337338// If we have both a start and end point, then create a synthetic polygon to route through.339if (closest_start_polygon && closest_end_polygon) {340new_polygon.vertices.resize(4);341342// Build a set of vertices that create a thin polygon going from the start to the end point.343new_polygon.vertices[0] = closest_start_point;344new_polygon.vertices[1] = closest_start_point;345new_polygon.vertices[2] = closest_end_point;346new_polygon.vertices[3] = closest_end_point;347348// Setup connections to go forward in the link.349{350Connection entry_connection;351entry_connection.polygon = &new_polygon;352entry_connection.edge = -1;353entry_connection.pathway_start = new_polygon.vertices[0];354entry_connection.pathway_end = new_polygon.vertices[1];355navbases_polygons_external_connections[closest_start_polygon->owner][closest_start_polygon->id].push_back(entry_connection);356357Connection exit_connection;358exit_connection.polygon = closest_end_polygon;359exit_connection.edge = -1;360exit_connection.pathway_start = new_polygon.vertices[2];361exit_connection.pathway_end = new_polygon.vertices[3];362navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav3D::Connection>());363navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);364}365366// If the link is bi-directional, create connections from the end to the start.367if (link->is_bidirectional()) {368Connection entry_connection;369entry_connection.polygon = &new_polygon;370entry_connection.edge = -1;371entry_connection.pathway_start = new_polygon.vertices[2];372entry_connection.pathway_end = new_polygon.vertices[3];373navbases_polygons_external_connections[closest_end_polygon->owner][closest_end_polygon->id].push_back(entry_connection);374375Connection exit_connection;376exit_connection.polygon = closest_start_polygon;377exit_connection.edge = -1;378exit_connection.pathway_start = new_polygon.vertices[0];379exit_connection.pathway_end = new_polygon.vertices[1];380navbases_polygons_external_connections[link.ptr()].push_back(LocalVector<Nav3D::Connection>());381navbases_polygons_external_connections[link.ptr()][new_polygon.id].push_back(exit_connection);382}383}384}385386r_build.polygon_count = polygon_count;387}388389void NavMapBuilder3D::_build_update_map_iteration(NavMapIterationBuild3D &r_build) {390NavMapIteration3D *map_iteration = r_build.map_iteration;391392map_iteration->navmesh_polygon_count = r_build.polygon_count;393394uint32_t navmesh_polygon_count = r_build.polygon_count;395uint32_t total_polygon_count = navmesh_polygon_count;396397map_iteration->path_query_slots_mutex.lock();398for (NavMeshQueries3D::PathQuerySlot &p_path_query_slot : map_iteration->path_query_slots) {399p_path_query_slot.traversable_polys.clear();400p_path_query_slot.traversable_polys.reserve(navmesh_polygon_count * 0.25);401p_path_query_slot.path_corridor.clear();402403p_path_query_slot.path_corridor.resize(total_polygon_count);404405p_path_query_slot.poly_to_id.clear();406p_path_query_slot.poly_to_id.reserve(total_polygon_count);407408int polygon_id = 0;409for (Ref<NavRegionIteration3D> ®ion : map_iteration->region_iterations) {410for (const Polygon &polygon : region->navmesh_polygons) {411p_path_query_slot.poly_to_id[&polygon] = polygon_id;412polygon_id++;413}414}415416for (const Polygon &polygon : map_iteration->navlink_polygons) {417p_path_query_slot.poly_to_id[&polygon] = polygon_id;418polygon_id++;419}420421DEV_ASSERT(p_path_query_slot.path_corridor.size() == p_path_query_slot.poly_to_id.size());422}423424map_iteration->path_query_slots_mutex.unlock();425}426427428