nav_map.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. /**************************************************************************/
  2. /* nav_map.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. #include "nav_map.h"
  31. #include "nav_agent.h"
  32. #include "nav_link.h"
  33. #include "nav_obstacle.h"
  34. #include "nav_region.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/object/worker_thread_pool.h"
  37. #include <Obstacle2d.h>
  38. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  39. // Helper macro
  40. #define APPEND_METADATA(poly) \
  41. if (r_path_types) { \
  42. r_path_types->push_back(poly->owner->get_type()); \
  43. } \
  44. if (r_path_rids) { \
  45. r_path_rids->push_back(poly->owner->get_self()); \
  46. } \
  47. if (r_path_owners) { \
  48. r_path_owners->push_back(poly->owner->get_owner_id()); \
  49. }
  50. #ifdef DEBUG_ENABLED
  51. #define NAVMAP_ITERATION_ZERO_ERROR_MSG() \
  52. ERR_PRINT_ONCE("NavigationServer navigation map query failed because it was made before first map synchronization.\n\
  53. NavigationServer 'map_changed' signal can be used to receive update notifications.\n\
  54. NavigationServer 'map_get_iteration_id()' can be used to check if a map has finished its newest iteration.");
  55. #else
  56. #define NAVMAP_ITERATION_ZERO_ERROR_MSG()
  57. #endif // DEBUG_ENABLED
  58. void NavMap::set_up(Vector3 p_up) {
  59. if (up == p_up) {
  60. return;
  61. }
  62. up = p_up;
  63. regenerate_polygons = true;
  64. }
  65. void NavMap::set_cell_size(real_t p_cell_size) {
  66. if (cell_size == p_cell_size) {
  67. return;
  68. }
  69. cell_size = p_cell_size;
  70. _update_merge_rasterizer_cell_dimensions();
  71. regenerate_polygons = true;
  72. }
  73. void NavMap::set_cell_height(real_t p_cell_height) {
  74. if (cell_height == p_cell_height) {
  75. return;
  76. }
  77. cell_height = p_cell_height;
  78. _update_merge_rasterizer_cell_dimensions();
  79. regenerate_polygons = true;
  80. }
  81. void NavMap::set_merge_rasterizer_cell_scale(float p_value) {
  82. if (merge_rasterizer_cell_scale == p_value) {
  83. return;
  84. }
  85. merge_rasterizer_cell_scale = p_value;
  86. _update_merge_rasterizer_cell_dimensions();
  87. regenerate_polygons = true;
  88. }
  89. void NavMap::set_use_edge_connections(bool p_enabled) {
  90. if (use_edge_connections == p_enabled) {
  91. return;
  92. }
  93. use_edge_connections = p_enabled;
  94. regenerate_links = true;
  95. }
  96. void NavMap::set_edge_connection_margin(real_t p_edge_connection_margin) {
  97. if (edge_connection_margin == p_edge_connection_margin) {
  98. return;
  99. }
  100. edge_connection_margin = p_edge_connection_margin;
  101. regenerate_links = true;
  102. }
  103. void NavMap::set_link_connection_radius(real_t p_link_connection_radius) {
  104. if (link_connection_radius == p_link_connection_radius) {
  105. return;
  106. }
  107. link_connection_radius = p_link_connection_radius;
  108. regenerate_links = true;
  109. }
  110. gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
  111. const int x = static_cast<int>(Math::floor(p_pos.x / merge_rasterizer_cell_size));
  112. const int y = static_cast<int>(Math::floor(p_pos.y / merge_rasterizer_cell_height));
  113. const int z = static_cast<int>(Math::floor(p_pos.z / merge_rasterizer_cell_size));
  114. gd::PointKey p;
  115. p.key = 0;
  116. p.x = x;
  117. p.y = y;
  118. p.z = z;
  119. return p;
  120. }
  121. Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_navigation_layers, Vector<int32_t> *r_path_types, TypedArray<RID> *r_path_rids, Vector<int64_t> *r_path_owners) const {
  122. RWLockRead read_lock(map_rwlock);
  123. if (iteration_id == 0) {
  124. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  125. return Vector<Vector3>();
  126. }
  127. // Clear metadata outputs.
  128. if (r_path_types) {
  129. r_path_types->clear();
  130. }
  131. if (r_path_rids) {
  132. r_path_rids->clear();
  133. }
  134. if (r_path_owners) {
  135. r_path_owners->clear();
  136. }
  137. // Find the start poly and the end poly on this map.
  138. const gd::Polygon *begin_poly = nullptr;
  139. const gd::Polygon *end_poly = nullptr;
  140. Vector3 begin_point;
  141. Vector3 end_point;
  142. real_t begin_d = FLT_MAX;
  143. real_t end_d = FLT_MAX;
  144. // Find the initial poly and the end poly on this map.
  145. for (const gd::Polygon &p : polygons) {
  146. // Only consider the polygon if it in a region with compatible layers.
  147. if ((p_navigation_layers & p.owner->get_navigation_layers()) == 0) {
  148. continue;
  149. }
  150. // For each face check the distance between the origin/destination
  151. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  152. const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  153. Vector3 point = face.get_closest_point_to(p_origin);
  154. real_t distance_to_point = point.distance_to(p_origin);
  155. if (distance_to_point < begin_d) {
  156. begin_d = distance_to_point;
  157. begin_poly = &p;
  158. begin_point = point;
  159. }
  160. point = face.get_closest_point_to(p_destination);
  161. distance_to_point = point.distance_to(p_destination);
  162. if (distance_to_point < end_d) {
  163. end_d = distance_to_point;
  164. end_poly = &p;
  165. end_point = point;
  166. }
  167. }
  168. }
  169. // Check for trivial cases
  170. if (!begin_poly || !end_poly) {
  171. return Vector<Vector3>();
  172. }
  173. if (begin_poly == end_poly) {
  174. if (r_path_types) {
  175. r_path_types->resize(2);
  176. r_path_types->write[0] = begin_poly->owner->get_type();
  177. r_path_types->write[1] = end_poly->owner->get_type();
  178. }
  179. if (r_path_rids) {
  180. r_path_rids->resize(2);
  181. (*r_path_rids)[0] = begin_poly->owner->get_self();
  182. (*r_path_rids)[1] = end_poly->owner->get_self();
  183. }
  184. if (r_path_owners) {
  185. r_path_owners->resize(2);
  186. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  187. r_path_owners->write[1] = end_poly->owner->get_owner_id();
  188. }
  189. Vector<Vector3> path;
  190. path.resize(2);
  191. path.write[0] = begin_point;
  192. path.write[1] = end_point;
  193. return path;
  194. }
  195. // List of all reachable navigation polys.
  196. LocalVector<gd::NavigationPoly> navigation_polys;
  197. navigation_polys.reserve(polygons.size() * 0.75);
  198. // Add the start polygon to the reachable navigation polygons.
  199. gd::NavigationPoly begin_navigation_poly = gd::NavigationPoly(begin_poly);
  200. begin_navigation_poly.self_id = 0;
  201. begin_navigation_poly.entry = begin_point;
  202. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  203. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  204. navigation_polys.push_back(begin_navigation_poly);
  205. // List of polygon IDs to visit.
  206. List<uint32_t> to_visit;
  207. to_visit.push_back(0);
  208. // This is an implementation of the A* algorithm.
  209. int least_cost_id = 0;
  210. int prev_least_cost_id = -1;
  211. bool found_route = false;
  212. const gd::Polygon *reachable_end = nullptr;
  213. real_t reachable_d = FLT_MAX;
  214. bool is_reachable = true;
  215. while (true) {
  216. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  217. for (const gd::Edge &edge : navigation_polys[least_cost_id].poly->edges) {
  218. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  219. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  220. const gd::Edge::Connection &connection = edge.connections[connection_index];
  221. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  222. if ((p_navigation_layers & connection.polygon->owner->get_navigation_layers()) == 0) {
  223. continue;
  224. }
  225. const gd::NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
  226. real_t poly_enter_cost = 0.0;
  227. real_t poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost();
  228. if (prev_least_cost_id != -1 && (navigation_polys[prev_least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self())) {
  229. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  230. }
  231. prev_least_cost_id = least_cost_id;
  232. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  233. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly.entry, pathway);
  234. const real_t new_distance = (least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost) + poly_enter_cost + least_cost_poly.traveled_distance;
  235. int64_t already_visited_polygon_index = navigation_polys.find(gd::NavigationPoly(connection.polygon));
  236. if (already_visited_polygon_index != -1) {
  237. // Polygon already visited, check if we can reduce the travel cost.
  238. gd::NavigationPoly &avp = navigation_polys[already_visited_polygon_index];
  239. if (new_distance < avp.traveled_distance) {
  240. avp.back_navigation_poly_id = least_cost_id;
  241. avp.back_navigation_edge = connection.edge;
  242. avp.back_navigation_edge_pathway_start = connection.pathway_start;
  243. avp.back_navigation_edge_pathway_end = connection.pathway_end;
  244. avp.traveled_distance = new_distance;
  245. avp.entry = new_entry;
  246. }
  247. } else {
  248. // Add the neighbor polygon to the reachable ones.
  249. gd::NavigationPoly new_navigation_poly = gd::NavigationPoly(connection.polygon);
  250. new_navigation_poly.self_id = navigation_polys.size();
  251. new_navigation_poly.back_navigation_poly_id = least_cost_id;
  252. new_navigation_poly.back_navigation_edge = connection.edge;
  253. new_navigation_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  254. new_navigation_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  255. new_navigation_poly.traveled_distance = new_distance;
  256. new_navigation_poly.entry = new_entry;
  257. navigation_polys.push_back(new_navigation_poly);
  258. // Add the neighbor polygon to the polygons to visit.
  259. to_visit.push_back(navigation_polys.size() - 1);
  260. }
  261. }
  262. }
  263. // Removes the least cost polygon from the list of polygons to visit so we can advance.
  264. to_visit.erase(least_cost_id);
  265. // When the list of polygons to visit is empty at this point it means the End Polygon is not reachable
  266. if (to_visit.size() == 0) {
  267. // Thus use the further reachable polygon
  268. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  269. is_reachable = false;
  270. if (reachable_end == nullptr) {
  271. // The path is not found and there is not a way out.
  272. break;
  273. }
  274. // Set as end point the furthest reachable point.
  275. end_poly = reachable_end;
  276. end_d = FLT_MAX;
  277. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  278. Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  279. Vector3 spoint = f.get_closest_point_to(p_destination);
  280. real_t dpoint = spoint.distance_to(p_destination);
  281. if (dpoint < end_d) {
  282. end_point = spoint;
  283. end_d = dpoint;
  284. }
  285. }
  286. // Search all faces of start polygon as well.
  287. bool closest_point_on_start_poly = false;
  288. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  289. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  290. Vector3 spoint = f.get_closest_point_to(p_destination);
  291. real_t dpoint = spoint.distance_to(p_destination);
  292. if (dpoint < end_d) {
  293. end_point = spoint;
  294. end_d = dpoint;
  295. closest_point_on_start_poly = true;
  296. }
  297. }
  298. if (closest_point_on_start_poly) {
  299. // No point to run PostProcessing when start and end convex polygon is the same.
  300. if (r_path_types) {
  301. r_path_types->resize(2);
  302. r_path_types->write[0] = begin_poly->owner->get_type();
  303. r_path_types->write[1] = begin_poly->owner->get_type();
  304. }
  305. if (r_path_rids) {
  306. r_path_rids->resize(2);
  307. (*r_path_rids)[0] = begin_poly->owner->get_self();
  308. (*r_path_rids)[1] = begin_poly->owner->get_self();
  309. }
  310. if (r_path_owners) {
  311. r_path_owners->resize(2);
  312. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  313. r_path_owners->write[1] = begin_poly->owner->get_owner_id();
  314. }
  315. Vector<Vector3> path;
  316. path.resize(2);
  317. path.write[0] = begin_point;
  318. path.write[1] = end_point;
  319. return path;
  320. }
  321. // Reset open and navigation_polys
  322. gd::NavigationPoly np = navigation_polys[0];
  323. navigation_polys.clear();
  324. navigation_polys.push_back(np);
  325. to_visit.clear();
  326. to_visit.push_back(0);
  327. least_cost_id = 0;
  328. prev_least_cost_id = -1;
  329. reachable_end = nullptr;
  330. continue;
  331. }
  332. // Find the polygon with the minimum cost from the list of polygons to visit.
  333. least_cost_id = -1;
  334. real_t least_cost = FLT_MAX;
  335. for (List<uint32_t>::Element *element = to_visit.front(); element != nullptr; element = element->next()) {
  336. gd::NavigationPoly *np = &navigation_polys[element->get()];
  337. real_t cost = np->traveled_distance;
  338. cost += (np->entry.distance_to(end_point) * np->poly->owner->get_travel_cost());
  339. if (cost < least_cost) {
  340. least_cost_id = np->self_id;
  341. least_cost = cost;
  342. }
  343. }
  344. ERR_BREAK(least_cost_id == -1);
  345. // Stores the further reachable end polygon, in case our goal is not reachable.
  346. if (is_reachable) {
  347. real_t d = navigation_polys[least_cost_id].entry.distance_to(p_destination);
  348. if (reachable_d > d) {
  349. reachable_d = d;
  350. reachable_end = navigation_polys[least_cost_id].poly;
  351. }
  352. }
  353. // Check if we reached the end
  354. if (navigation_polys[least_cost_id].poly == end_poly) {
  355. found_route = true;
  356. break;
  357. }
  358. }
  359. // We did not find a route but we have both a start polygon and an end polygon at this point.
  360. // Usually this happens because there was not a single external or internal connected edge, e.g. our start polygon is an isolated, single convex polygon.
  361. if (!found_route) {
  362. end_d = FLT_MAX;
  363. // Search all faces of the start polygon for the closest point to our target position.
  364. for (size_t point_id = 2; point_id < begin_poly->points.size(); point_id++) {
  365. Face3 f(begin_poly->points[0].pos, begin_poly->points[point_id - 1].pos, begin_poly->points[point_id].pos);
  366. Vector3 spoint = f.get_closest_point_to(p_destination);
  367. real_t dpoint = spoint.distance_to(p_destination);
  368. if (dpoint < end_d) {
  369. end_point = spoint;
  370. end_d = dpoint;
  371. }
  372. }
  373. if (r_path_types) {
  374. r_path_types->resize(2);
  375. r_path_types->write[0] = begin_poly->owner->get_type();
  376. r_path_types->write[1] = begin_poly->owner->get_type();
  377. }
  378. if (r_path_rids) {
  379. r_path_rids->resize(2);
  380. (*r_path_rids)[0] = begin_poly->owner->get_self();
  381. (*r_path_rids)[1] = begin_poly->owner->get_self();
  382. }
  383. if (r_path_owners) {
  384. r_path_owners->resize(2);
  385. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  386. r_path_owners->write[1] = begin_poly->owner->get_owner_id();
  387. }
  388. Vector<Vector3> path;
  389. path.resize(2);
  390. path.write[0] = begin_point;
  391. path.write[1] = end_point;
  392. return path;
  393. }
  394. Vector<Vector3> path;
  395. // Optimize the path.
  396. if (p_optimize) {
  397. // Set the apex poly/point to the end point
  398. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  399. Vector3 back_pathway[2] = { apex_poly->back_navigation_edge_pathway_start, apex_poly->back_navigation_edge_pathway_end };
  400. const Vector3 back_edge_closest_point = Geometry3D::get_closest_point_to_segment(end_point, back_pathway);
  401. if (end_point.is_equal_approx(back_edge_closest_point)) {
  402. // The end point is basically on top of the last crossed edge, funneling around the corners would at best do nothing.
  403. // At worst it would add an unwanted path point before the last point due to precision issues so skip to the next polygon.
  404. if (apex_poly->back_navigation_poly_id != -1) {
  405. apex_poly = &navigation_polys[apex_poly->back_navigation_poly_id];
  406. }
  407. }
  408. Vector3 apex_point = end_point;
  409. gd::NavigationPoly *left_poly = apex_poly;
  410. Vector3 left_portal = apex_point;
  411. gd::NavigationPoly *right_poly = apex_poly;
  412. Vector3 right_portal = apex_point;
  413. gd::NavigationPoly *p = apex_poly;
  414. path.push_back(end_point);
  415. APPEND_METADATA(end_poly);
  416. while (p) {
  417. // Set left and right points of the pathway between polygons.
  418. Vector3 left = p->back_navigation_edge_pathway_start;
  419. Vector3 right = p->back_navigation_edge_pathway_end;
  420. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(up) < 0) {
  421. SWAP(left, right);
  422. }
  423. bool skip = false;
  424. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(up) >= 0) {
  425. //process
  426. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(up) > 0) {
  427. left_poly = p;
  428. left_portal = left;
  429. } else {
  430. clip_path(navigation_polys, path, apex_poly, right_portal, right_poly, r_path_types, r_path_rids, r_path_owners);
  431. apex_point = right_portal;
  432. p = right_poly;
  433. left_poly = p;
  434. apex_poly = p;
  435. left_portal = apex_point;
  436. right_portal = apex_point;
  437. path.push_back(apex_point);
  438. APPEND_METADATA(apex_poly->poly);
  439. skip = true;
  440. }
  441. }
  442. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(up) <= 0) {
  443. //process
  444. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(up) < 0) {
  445. right_poly = p;
  446. right_portal = right;
  447. } else {
  448. clip_path(navigation_polys, path, apex_poly, left_portal, left_poly, r_path_types, r_path_rids, r_path_owners);
  449. apex_point = left_portal;
  450. p = left_poly;
  451. right_poly = p;
  452. apex_poly = p;
  453. right_portal = apex_point;
  454. left_portal = apex_point;
  455. path.push_back(apex_point);
  456. APPEND_METADATA(apex_poly->poly);
  457. }
  458. }
  459. // Go to the previous polygon.
  460. if (p->back_navigation_poly_id != -1) {
  461. p = &navigation_polys[p->back_navigation_poly_id];
  462. } else {
  463. // The end
  464. p = nullptr;
  465. }
  466. }
  467. // If the last point is not the begin point, add it to the list.
  468. if (path[path.size() - 1] != begin_point) {
  469. path.push_back(begin_point);
  470. APPEND_METADATA(begin_poly);
  471. }
  472. path.reverse();
  473. if (r_path_types) {
  474. r_path_types->reverse();
  475. }
  476. if (r_path_rids) {
  477. r_path_rids->reverse();
  478. }
  479. if (r_path_owners) {
  480. r_path_owners->reverse();
  481. }
  482. } else {
  483. path.push_back(end_point);
  484. APPEND_METADATA(end_poly);
  485. // Add mid points
  486. int np_id = least_cost_id;
  487. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  488. if (navigation_polys[np_id].back_navigation_edge != -1) {
  489. int prev = navigation_polys[np_id].back_navigation_edge;
  490. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  491. Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  492. path.push_back(point);
  493. APPEND_METADATA(navigation_polys[np_id].poly);
  494. } else {
  495. path.push_back(navigation_polys[np_id].entry);
  496. APPEND_METADATA(navigation_polys[np_id].poly);
  497. }
  498. np_id = navigation_polys[np_id].back_navigation_poly_id;
  499. }
  500. path.push_back(begin_point);
  501. APPEND_METADATA(begin_poly);
  502. path.reverse();
  503. if (r_path_types) {
  504. r_path_types->reverse();
  505. }
  506. if (r_path_rids) {
  507. r_path_rids->reverse();
  508. }
  509. if (r_path_owners) {
  510. r_path_owners->reverse();
  511. }
  512. }
  513. // Ensure post conditions (path arrays MUST match in size).
  514. CRASH_COND(r_path_types && path.size() != r_path_types->size());
  515. CRASH_COND(r_path_rids && path.size() != r_path_rids->size());
  516. CRASH_COND(r_path_owners && path.size() != r_path_owners->size());
  517. return path;
  518. }
  519. Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
  520. RWLockRead read_lock(map_rwlock);
  521. if (iteration_id == 0) {
  522. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  523. return Vector3();
  524. }
  525. bool use_collision = p_use_collision;
  526. Vector3 closest_point;
  527. real_t closest_point_d = FLT_MAX;
  528. for (const gd::Polygon &p : polygons) {
  529. // For each face check the distance to the segment
  530. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  531. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  532. Vector3 inters;
  533. if (f.intersects_segment(p_from, p_to, &inters)) {
  534. const real_t d = p_from.distance_to(inters);
  535. if (use_collision == false) {
  536. closest_point = inters;
  537. use_collision = true;
  538. closest_point_d = d;
  539. } else if (closest_point_d > d) {
  540. closest_point = inters;
  541. closest_point_d = d;
  542. }
  543. }
  544. // If segment does not itersect face, check the distance from segment's endpoints.
  545. else if (!use_collision) {
  546. const Vector3 p_from_closest = f.get_closest_point_to(p_from);
  547. const real_t d_p_from = p_from.distance_to(p_from_closest);
  548. if (closest_point_d > d_p_from) {
  549. closest_point = p_from_closest;
  550. closest_point_d = d_p_from;
  551. }
  552. const Vector3 p_to_closest = f.get_closest_point_to(p_to);
  553. const real_t d_p_to = p_to.distance_to(p_to_closest);
  554. if (closest_point_d > d_p_to) {
  555. closest_point = p_to_closest;
  556. closest_point_d = d_p_to;
  557. }
  558. }
  559. }
  560. // Finally, check for a case when shortest distance is between some point located on a face's edge and some point located on a line segment.
  561. if (!use_collision) {
  562. for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
  563. Vector3 a, b;
  564. Geometry3D::get_closest_points_between_segments(
  565. p_from,
  566. p_to,
  567. p.points[point_id].pos,
  568. p.points[(point_id + 1) % p.points.size()].pos,
  569. a,
  570. b);
  571. const real_t d = a.distance_to(b);
  572. if (d < closest_point_d) {
  573. closest_point_d = d;
  574. closest_point = b;
  575. }
  576. }
  577. }
  578. }
  579. return closest_point;
  580. }
  581. Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
  582. RWLockRead read_lock(map_rwlock);
  583. if (iteration_id == 0) {
  584. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  585. return Vector3();
  586. }
  587. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  588. return cp.point;
  589. }
  590. Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
  591. RWLockRead read_lock(map_rwlock);
  592. if (iteration_id == 0) {
  593. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  594. return Vector3();
  595. }
  596. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  597. return cp.normal;
  598. }
  599. RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
  600. RWLockRead read_lock(map_rwlock);
  601. if (iteration_id == 0) {
  602. NAVMAP_ITERATION_ZERO_ERROR_MSG();
  603. return RID();
  604. }
  605. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  606. return cp.owner;
  607. }
  608. gd::ClosestPointQueryResult NavMap::get_closest_point_info(const Vector3 &p_point) const {
  609. RWLockRead read_lock(map_rwlock);
  610. gd::ClosestPointQueryResult result;
  611. real_t closest_point_ds = FLT_MAX;
  612. for (const gd::Polygon &p : polygons) {
  613. // For each face check the distance to the point
  614. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  615. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  616. const Vector3 inters = f.get_closest_point_to(p_point);
  617. const real_t ds = inters.distance_squared_to(p_point);
  618. if (ds < closest_point_ds) {
  619. result.point = inters;
  620. result.normal = f.get_plane().normal;
  621. result.owner = p.owner->get_self();
  622. closest_point_ds = ds;
  623. }
  624. }
  625. }
  626. return result;
  627. }
  628. void NavMap::add_region(NavRegion *p_region) {
  629. regions.push_back(p_region);
  630. regenerate_links = true;
  631. }
  632. void NavMap::remove_region(NavRegion *p_region) {
  633. int64_t region_index = regions.find(p_region);
  634. if (region_index >= 0) {
  635. regions.remove_at_unordered(region_index);
  636. regenerate_links = true;
  637. }
  638. }
  639. void NavMap::add_link(NavLink *p_link) {
  640. links.push_back(p_link);
  641. regenerate_links = true;
  642. }
  643. void NavMap::remove_link(NavLink *p_link) {
  644. int64_t link_index = links.find(p_link);
  645. if (link_index >= 0) {
  646. links.remove_at_unordered(link_index);
  647. regenerate_links = true;
  648. }
  649. }
  650. bool NavMap::has_agent(NavAgent *agent) const {
  651. return agents.has(agent);
  652. }
  653. void NavMap::add_agent(NavAgent *agent) {
  654. if (!has_agent(agent)) {
  655. agents.push_back(agent);
  656. agents_dirty = true;
  657. }
  658. }
  659. void NavMap::remove_agent(NavAgent *agent) {
  660. remove_agent_as_controlled(agent);
  661. int64_t agent_index = agents.find(agent);
  662. if (agent_index >= 0) {
  663. agents.remove_at_unordered(agent_index);
  664. agents_dirty = true;
  665. }
  666. }
  667. bool NavMap::has_obstacle(NavObstacle *obstacle) const {
  668. return obstacles.has(obstacle);
  669. }
  670. void NavMap::add_obstacle(NavObstacle *obstacle) {
  671. if (obstacle->get_paused()) {
  672. // No point in adding a paused obstacle, it will add itself when unpaused again.
  673. return;
  674. }
  675. if (!has_obstacle(obstacle)) {
  676. obstacles.push_back(obstacle);
  677. obstacles_dirty = true;
  678. }
  679. }
  680. void NavMap::remove_obstacle(NavObstacle *obstacle) {
  681. int64_t obstacle_index = obstacles.find(obstacle);
  682. if (obstacle_index >= 0) {
  683. obstacles.remove_at_unordered(obstacle_index);
  684. obstacles_dirty = true;
  685. }
  686. }
  687. void NavMap::set_agent_as_controlled(NavAgent *agent) {
  688. remove_agent_as_controlled(agent);
  689. if (agent->get_paused()) {
  690. // No point in adding a paused agent, it will add itself when unpaused again.
  691. return;
  692. }
  693. if (agent->get_use_3d_avoidance()) {
  694. int64_t agent_3d_index = active_3d_avoidance_agents.find(agent);
  695. if (agent_3d_index < 0) {
  696. active_3d_avoidance_agents.push_back(agent);
  697. agents_dirty = true;
  698. }
  699. } else {
  700. int64_t agent_2d_index = active_2d_avoidance_agents.find(agent);
  701. if (agent_2d_index < 0) {
  702. active_2d_avoidance_agents.push_back(agent);
  703. agents_dirty = true;
  704. }
  705. }
  706. }
  707. void NavMap::remove_agent_as_controlled(NavAgent *agent) {
  708. int64_t agent_3d_index = active_3d_avoidance_agents.find(agent);
  709. if (agent_3d_index >= 0) {
  710. active_3d_avoidance_agents.remove_at_unordered(agent_3d_index);
  711. agents_dirty = true;
  712. }
  713. int64_t agent_2d_index = active_2d_avoidance_agents.find(agent);
  714. if (agent_2d_index >= 0) {
  715. active_2d_avoidance_agents.remove_at_unordered(agent_2d_index);
  716. agents_dirty = true;
  717. }
  718. }
  719. Vector3 NavMap::get_random_point(uint32_t p_navigation_layers, bool p_uniformly) const {
  720. RWLockRead read_lock(map_rwlock);
  721. const LocalVector<NavRegion *> map_regions = get_regions();
  722. if (map_regions.is_empty()) {
  723. return Vector3();
  724. }
  725. LocalVector<const NavRegion *> accessible_regions;
  726. for (const NavRegion *region : map_regions) {
  727. if (!region->get_enabled() || (p_navigation_layers & region->get_navigation_layers()) == 0) {
  728. continue;
  729. }
  730. accessible_regions.push_back(region);
  731. }
  732. if (accessible_regions.is_empty()) {
  733. // All existing region polygons are disabled.
  734. return Vector3();
  735. }
  736. if (p_uniformly) {
  737. real_t accumulated_region_surface_area = 0;
  738. RBMap<real_t, uint32_t> accessible_regions_area_map;
  739. for (uint32_t accessible_region_index = 0; accessible_region_index < accessible_regions.size(); accessible_region_index++) {
  740. const NavRegion *region = accessible_regions[accessible_region_index];
  741. real_t region_surface_area = region->get_surface_area();
  742. if (region_surface_area == 0.0f) {
  743. continue;
  744. }
  745. accessible_regions_area_map[accumulated_region_surface_area] = accessible_region_index;
  746. accumulated_region_surface_area += region_surface_area;
  747. }
  748. if (accessible_regions_area_map.is_empty() || accumulated_region_surface_area == 0) {
  749. // All faces have no real surface / no area.
  750. return Vector3();
  751. }
  752. real_t random_accessible_regions_area_map = Math::random(real_t(0), accumulated_region_surface_area);
  753. RBMap<real_t, uint32_t>::Iterator E = accessible_regions_area_map.find_closest(random_accessible_regions_area_map);
  754. ERR_FAIL_COND_V(!E, Vector3());
  755. uint32_t random_region_index = E->value;
  756. ERR_FAIL_UNSIGNED_INDEX_V(random_region_index, accessible_regions.size(), Vector3());
  757. const NavRegion *random_region = accessible_regions[random_region_index];
  758. ERR_FAIL_NULL_V(random_region, Vector3());
  759. return random_region->get_random_point(p_navigation_layers, p_uniformly);
  760. } else {
  761. uint32_t random_region_index = Math::random(int(0), accessible_regions.size() - 1);
  762. const NavRegion *random_region = accessible_regions[random_region_index];
  763. ERR_FAIL_NULL_V(random_region, Vector3());
  764. return random_region->get_random_point(p_navigation_layers, p_uniformly);
  765. }
  766. }
  767. void NavMap::sync() {
  768. RWLockWrite write_lock(map_rwlock);
  769. // Performance Monitor
  770. int _new_pm_region_count = regions.size();
  771. int _new_pm_agent_count = agents.size();
  772. int _new_pm_link_count = links.size();
  773. int _new_pm_polygon_count = pm_polygon_count;
  774. int _new_pm_edge_count = pm_edge_count;
  775. int _new_pm_edge_merge_count = pm_edge_merge_count;
  776. int _new_pm_edge_connection_count = pm_edge_connection_count;
  777. int _new_pm_edge_free_count = pm_edge_free_count;
  778. // Check if we need to update the links.
  779. if (regenerate_polygons) {
  780. for (NavRegion *region : regions) {
  781. region->scratch_polygons();
  782. }
  783. regenerate_links = true;
  784. }
  785. for (NavRegion *region : regions) {
  786. if (region->sync()) {
  787. regenerate_links = true;
  788. }
  789. }
  790. for (NavLink *link : links) {
  791. if (link->check_dirty()) {
  792. regenerate_links = true;
  793. }
  794. }
  795. if (regenerate_links) {
  796. _new_pm_polygon_count = 0;
  797. _new_pm_edge_count = 0;
  798. _new_pm_edge_merge_count = 0;
  799. _new_pm_edge_connection_count = 0;
  800. _new_pm_edge_free_count = 0;
  801. // Remove regions connections.
  802. for (NavRegion *region : regions) {
  803. region->get_connections().clear();
  804. }
  805. // Resize the polygon count.
  806. int count = 0;
  807. for (const NavRegion *region : regions) {
  808. if (!region->get_enabled()) {
  809. continue;
  810. }
  811. count += region->get_polygons().size();
  812. }
  813. polygons.resize(count);
  814. // Copy all region polygons in the map.
  815. count = 0;
  816. for (const NavRegion *region : regions) {
  817. if (!region->get_enabled()) {
  818. continue;
  819. }
  820. const LocalVector<gd::Polygon> &polygons_source = region->get_polygons();
  821. for (uint32_t n = 0; n < polygons_source.size(); n++) {
  822. polygons[count + n] = polygons_source[n];
  823. }
  824. count += region->get_polygons().size();
  825. }
  826. _new_pm_polygon_count = polygons.size();
  827. // Group all edges per key.
  828. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections;
  829. for (gd::Polygon &poly : polygons) {
  830. for (uint32_t p = 0; p < poly.points.size(); p++) {
  831. int next_point = (p + 1) % poly.points.size();
  832. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  833. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek);
  834. if (!connection) {
  835. connections[ek] = Vector<gd::Edge::Connection>();
  836. _new_pm_edge_count += 1;
  837. }
  838. if (connections[ek].size() <= 1) {
  839. // Add the polygon/edge tuple to this key.
  840. gd::Edge::Connection new_connection;
  841. new_connection.polygon = &poly;
  842. new_connection.edge = p;
  843. new_connection.pathway_start = poly.points[p].pos;
  844. new_connection.pathway_end = poly.points[next_point].pos;
  845. connections[ek].push_back(new_connection);
  846. } else {
  847. // The edge is already connected with another edge, skip.
  848. ERR_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.");
  849. }
  850. }
  851. }
  852. Vector<gd::Edge::Connection> free_edges;
  853. for (KeyValue<gd::EdgeKey, Vector<gd::Edge::Connection>> &E : connections) {
  854. if (E.value.size() == 2) {
  855. // Connect edge that are shared in different polygons.
  856. gd::Edge::Connection &c1 = E.value.write[0];
  857. gd::Edge::Connection &c2 = E.value.write[1];
  858. c1.polygon->edges[c1.edge].connections.push_back(c2);
  859. c2.polygon->edges[c2.edge].connections.push_back(c1);
  860. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  861. _new_pm_edge_merge_count += 1;
  862. } else {
  863. CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size()));
  864. if (use_edge_connections && E.value[0].polygon->owner->get_use_edge_connections()) {
  865. free_edges.push_back(E.value[0]);
  866. }
  867. }
  868. }
  869. // Find the compatible near edges.
  870. //
  871. // Note:
  872. // Considering that the edges must be compatible (for obvious reasons)
  873. // to be connected, create new polygons to remove that small gap is
  874. // not really useful and would result in wasteful computation during
  875. // connection, integration and path finding.
  876. _new_pm_edge_free_count = free_edges.size();
  877. for (int i = 0; i < free_edges.size(); i++) {
  878. const gd::Edge::Connection &free_edge = free_edges[i];
  879. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  880. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  881. for (int j = 0; j < free_edges.size(); j++) {
  882. const gd::Edge::Connection &other_edge = free_edges[j];
  883. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  884. continue;
  885. }
  886. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  887. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  888. // Compute the projection of the opposite edge on the current one
  889. Vector3 edge_vector = edge_p2 - edge_p1;
  890. real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  891. real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  892. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  893. continue;
  894. }
  895. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  896. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  897. Vector3 other1;
  898. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  899. other1 = other_edge_p1;
  900. } else {
  901. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  902. }
  903. if (other1.distance_to(self1) > edge_connection_margin) {
  904. continue;
  905. }
  906. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  907. Vector3 other2;
  908. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  909. other2 = other_edge_p2;
  910. } else {
  911. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  912. }
  913. if (other2.distance_to(self2) > edge_connection_margin) {
  914. continue;
  915. }
  916. // The edges can now be connected.
  917. gd::Edge::Connection new_connection = other_edge;
  918. new_connection.pathway_start = (self1 + other1) / 2.0;
  919. new_connection.pathway_end = (self2 + other2) / 2.0;
  920. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  921. // Add the connection to the region_connection map.
  922. ((NavRegion *)free_edge.polygon->owner)->get_connections().push_back(new_connection);
  923. _new_pm_edge_connection_count += 1;
  924. }
  925. }
  926. uint32_t link_poly_idx = 0;
  927. link_polygons.resize(links.size());
  928. // Search for polygons within range of a nav link.
  929. for (const NavLink *link : links) {
  930. if (!link->get_enabled()) {
  931. continue;
  932. }
  933. const Vector3 start = link->get_start_position();
  934. const Vector3 end = link->get_end_position();
  935. gd::Polygon *closest_start_polygon = nullptr;
  936. real_t closest_start_distance = link_connection_radius;
  937. Vector3 closest_start_point;
  938. gd::Polygon *closest_end_polygon = nullptr;
  939. real_t closest_end_distance = link_connection_radius;
  940. Vector3 closest_end_point;
  941. // Create link to any polygons within the search radius of the start point.
  942. for (uint32_t start_index = 0; start_index < polygons.size(); start_index++) {
  943. gd::Polygon &start_poly = polygons[start_index];
  944. // For each face check the distance to the start
  945. for (uint32_t start_point_id = 2; start_point_id < start_poly.points.size(); start_point_id += 1) {
  946. const Face3 start_face(start_poly.points[0].pos, start_poly.points[start_point_id - 1].pos, start_poly.points[start_point_id].pos);
  947. const Vector3 start_point = start_face.get_closest_point_to(start);
  948. const real_t start_distance = start_point.distance_to(start);
  949. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  950. if (start_distance <= link_connection_radius && start_distance < closest_start_distance) {
  951. closest_start_distance = start_distance;
  952. closest_start_point = start_point;
  953. closest_start_polygon = &start_poly;
  954. }
  955. }
  956. }
  957. // Find any polygons within the search radius of the end point.
  958. for (gd::Polygon &end_poly : polygons) {
  959. // For each face check the distance to the end
  960. for (uint32_t end_point_id = 2; end_point_id < end_poly.points.size(); end_point_id += 1) {
  961. const Face3 end_face(end_poly.points[0].pos, end_poly.points[end_point_id - 1].pos, end_poly.points[end_point_id].pos);
  962. const Vector3 end_point = end_face.get_closest_point_to(end);
  963. const real_t end_distance = end_point.distance_to(end);
  964. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  965. if (end_distance <= link_connection_radius && end_distance < closest_end_distance) {
  966. closest_end_distance = end_distance;
  967. closest_end_point = end_point;
  968. closest_end_polygon = &end_poly;
  969. }
  970. }
  971. }
  972. // If we have both a start and end point, then create a synthetic polygon to route through.
  973. if (closest_start_polygon && closest_end_polygon) {
  974. gd::Polygon &new_polygon = link_polygons[link_poly_idx++];
  975. new_polygon.owner = link;
  976. new_polygon.edges.clear();
  977. new_polygon.edges.resize(4);
  978. new_polygon.points.clear();
  979. new_polygon.points.reserve(4);
  980. // Build a set of vertices that create a thin polygon going from the start to the end point.
  981. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  982. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  983. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  984. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  985. // Setup connections to go forward in the link.
  986. {
  987. gd::Edge::Connection entry_connection;
  988. entry_connection.polygon = &new_polygon;
  989. entry_connection.edge = -1;
  990. entry_connection.pathway_start = new_polygon.points[0].pos;
  991. entry_connection.pathway_end = new_polygon.points[1].pos;
  992. closest_start_polygon->edges[0].connections.push_back(entry_connection);
  993. gd::Edge::Connection exit_connection;
  994. exit_connection.polygon = closest_end_polygon;
  995. exit_connection.edge = -1;
  996. exit_connection.pathway_start = new_polygon.points[2].pos;
  997. exit_connection.pathway_end = new_polygon.points[3].pos;
  998. new_polygon.edges[2].connections.push_back(exit_connection);
  999. }
  1000. // If the link is bi-directional, create connections from the end to the start.
  1001. if (link->is_bidirectional()) {
  1002. gd::Edge::Connection entry_connection;
  1003. entry_connection.polygon = &new_polygon;
  1004. entry_connection.edge = -1;
  1005. entry_connection.pathway_start = new_polygon.points[2].pos;
  1006. entry_connection.pathway_end = new_polygon.points[3].pos;
  1007. closest_end_polygon->edges[0].connections.push_back(entry_connection);
  1008. gd::Edge::Connection exit_connection;
  1009. exit_connection.polygon = closest_start_polygon;
  1010. exit_connection.edge = -1;
  1011. exit_connection.pathway_start = new_polygon.points[0].pos;
  1012. exit_connection.pathway_end = new_polygon.points[1].pos;
  1013. new_polygon.edges[0].connections.push_back(exit_connection);
  1014. }
  1015. }
  1016. }
  1017. // Some code treats 0 as a failure case, so we avoid returning 0 and modulo wrap UINT32_MAX manually.
  1018. iteration_id = iteration_id % UINT32_MAX + 1;
  1019. }
  1020. // Do we have modified obstacle positions?
  1021. for (NavObstacle *obstacle : obstacles) {
  1022. if (obstacle->check_dirty()) {
  1023. obstacles_dirty = true;
  1024. }
  1025. }
  1026. // Do we have modified agent arrays?
  1027. for (NavAgent *agent : agents) {
  1028. if (agent->check_dirty()) {
  1029. agents_dirty = true;
  1030. }
  1031. }
  1032. // Update avoidance worlds.
  1033. if (obstacles_dirty || agents_dirty) {
  1034. _update_rvo_simulation();
  1035. }
  1036. regenerate_polygons = false;
  1037. regenerate_links = false;
  1038. obstacles_dirty = false;
  1039. agents_dirty = false;
  1040. // Performance Monitor.
  1041. pm_region_count = _new_pm_region_count;
  1042. pm_agent_count = _new_pm_agent_count;
  1043. pm_link_count = _new_pm_link_count;
  1044. pm_polygon_count = _new_pm_polygon_count;
  1045. pm_edge_count = _new_pm_edge_count;
  1046. pm_edge_merge_count = _new_pm_edge_merge_count;
  1047. pm_edge_connection_count = _new_pm_edge_connection_count;
  1048. pm_edge_free_count = _new_pm_edge_free_count;
  1049. }
  1050. void NavMap::_update_rvo_obstacles_tree_2d() {
  1051. int obstacle_vertex_count = 0;
  1052. for (NavObstacle *obstacle : obstacles) {
  1053. obstacle_vertex_count += obstacle->get_vertices().size();
  1054. }
  1055. // Cleaning old obstacles.
  1056. for (size_t i = 0; i < rvo_simulation_2d.obstacles_.size(); ++i) {
  1057. delete rvo_simulation_2d.obstacles_[i];
  1058. }
  1059. rvo_simulation_2d.obstacles_.clear();
  1060. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree
  1061. std::vector<RVO2D::Obstacle2D *> &raw_obstacles = rvo_simulation_2d.obstacles_;
  1062. raw_obstacles.reserve(obstacle_vertex_count);
  1063. // The following block is modified copy from RVO2D::AddObstacle()
  1064. // Obstacles are linked and depend on all other obstacles.
  1065. for (NavObstacle *obstacle : obstacles) {
  1066. const Vector3 &_obstacle_position = obstacle->get_position();
  1067. const Vector<Vector3> &_obstacle_vertices = obstacle->get_vertices();
  1068. if (_obstacle_vertices.size() < 2) {
  1069. continue;
  1070. }
  1071. std::vector<RVO2D::Vector2> rvo_2d_vertices;
  1072. rvo_2d_vertices.reserve(_obstacle_vertices.size());
  1073. uint32_t _obstacle_avoidance_layers = obstacle->get_avoidance_layers();
  1074. real_t _obstacle_height = obstacle->get_height();
  1075. for (const Vector3 &_obstacle_vertex : _obstacle_vertices) {
  1076. #ifdef TOOLS_ENABLED
  1077. if (_obstacle_vertex.y != 0) {
  1078. WARN_PRINT_ONCE("Y coordinates of static obstacle vertices are ignored. Please use obstacle position Y to change elevation of obstacle.");
  1079. }
  1080. #endif
  1081. rvo_2d_vertices.push_back(RVO2D::Vector2(_obstacle_vertex.x + _obstacle_position.x, _obstacle_vertex.z + _obstacle_position.z));
  1082. }
  1083. const size_t obstacleNo = raw_obstacles.size();
  1084. for (size_t i = 0; i < rvo_2d_vertices.size(); i++) {
  1085. RVO2D::Obstacle2D *rvo_2d_obstacle = new RVO2D::Obstacle2D();
  1086. rvo_2d_obstacle->point_ = rvo_2d_vertices[i];
  1087. rvo_2d_obstacle->height_ = _obstacle_height;
  1088. rvo_2d_obstacle->elevation_ = _obstacle_position.y;
  1089. rvo_2d_obstacle->avoidance_layers_ = _obstacle_avoidance_layers;
  1090. if (i != 0) {
  1091. rvo_2d_obstacle->prevObstacle_ = raw_obstacles.back();
  1092. rvo_2d_obstacle->prevObstacle_->nextObstacle_ = rvo_2d_obstacle;
  1093. }
  1094. if (i == rvo_2d_vertices.size() - 1) {
  1095. rvo_2d_obstacle->nextObstacle_ = raw_obstacles[obstacleNo];
  1096. rvo_2d_obstacle->nextObstacle_->prevObstacle_ = rvo_2d_obstacle;
  1097. }
  1098. rvo_2d_obstacle->unitDir_ = normalize(rvo_2d_vertices[(i == rvo_2d_vertices.size() - 1 ? 0 : i + 1)] - rvo_2d_vertices[i]);
  1099. if (rvo_2d_vertices.size() == 2) {
  1100. rvo_2d_obstacle->isConvex_ = true;
  1101. } else {
  1102. rvo_2d_obstacle->isConvex_ = (leftOf(rvo_2d_vertices[(i == 0 ? rvo_2d_vertices.size() - 1 : i - 1)], rvo_2d_vertices[i], rvo_2d_vertices[(i == rvo_2d_vertices.size() - 1 ? 0 : i + 1)]) >= 0.0f);
  1103. }
  1104. rvo_2d_obstacle->id_ = raw_obstacles.size();
  1105. raw_obstacles.push_back(rvo_2d_obstacle);
  1106. }
  1107. }
  1108. rvo_simulation_2d.kdTree_->buildObstacleTree(raw_obstacles);
  1109. }
  1110. void NavMap::_update_rvo_agents_tree_2d() {
  1111. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1112. std::vector<RVO2D::Agent2D *> raw_agents;
  1113. raw_agents.reserve(active_2d_avoidance_agents.size());
  1114. for (NavAgent *agent : active_2d_avoidance_agents) {
  1115. raw_agents.push_back(agent->get_rvo_agent_2d());
  1116. }
  1117. rvo_simulation_2d.kdTree_->buildAgentTree(raw_agents);
  1118. }
  1119. void NavMap::_update_rvo_agents_tree_3d() {
  1120. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1121. std::vector<RVO3D::Agent3D *> raw_agents;
  1122. raw_agents.reserve(active_3d_avoidance_agents.size());
  1123. for (NavAgent *agent : active_3d_avoidance_agents) {
  1124. raw_agents.push_back(agent->get_rvo_agent_3d());
  1125. }
  1126. rvo_simulation_3d.kdTree_->buildAgentTree(raw_agents);
  1127. }
  1128. void NavMap::_update_rvo_simulation() {
  1129. if (obstacles_dirty) {
  1130. _update_rvo_obstacles_tree_2d();
  1131. }
  1132. if (agents_dirty) {
  1133. _update_rvo_agents_tree_2d();
  1134. _update_rvo_agents_tree_3d();
  1135. }
  1136. }
  1137. void NavMap::compute_single_avoidance_step_2d(uint32_t index, NavAgent **agent) {
  1138. (*(agent + index))->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1139. (*(agent + index))->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1140. (*(agent + index))->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1141. (*(agent + index))->update();
  1142. }
  1143. void NavMap::compute_single_avoidance_step_3d(uint32_t index, NavAgent **agent) {
  1144. (*(agent + index))->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1145. (*(agent + index))->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1146. (*(agent + index))->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1147. (*(agent + index))->update();
  1148. }
  1149. void NavMap::step(real_t p_deltatime) {
  1150. deltatime = p_deltatime;
  1151. rvo_simulation_2d.setTimeStep(float(deltatime));
  1152. rvo_simulation_3d.setTimeStep(float(deltatime));
  1153. if (active_2d_avoidance_agents.size() > 0) {
  1154. if (use_threads && avoidance_use_multiple_threads) {
  1155. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &NavMap::compute_single_avoidance_step_2d, active_2d_avoidance_agents.ptr(), active_2d_avoidance_agents.size(), -1, true, SNAME("RVOAvoidanceAgents2D"));
  1156. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1157. } else {
  1158. for (NavAgent *agent : active_2d_avoidance_agents) {
  1159. agent->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1160. agent->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1161. agent->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1162. agent->update();
  1163. }
  1164. }
  1165. }
  1166. if (active_3d_avoidance_agents.size() > 0) {
  1167. if (use_threads && avoidance_use_multiple_threads) {
  1168. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &NavMap::compute_single_avoidance_step_3d, active_3d_avoidance_agents.ptr(), active_3d_avoidance_agents.size(), -1, true, SNAME("RVOAvoidanceAgents3D"));
  1169. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1170. } else {
  1171. for (NavAgent *agent : active_3d_avoidance_agents) {
  1172. agent->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1173. agent->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1174. agent->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1175. agent->update();
  1176. }
  1177. }
  1178. }
  1179. }
  1180. void NavMap::dispatch_callbacks() {
  1181. for (NavAgent *agent : active_2d_avoidance_agents) {
  1182. agent->dispatch_avoidance_callback();
  1183. }
  1184. for (NavAgent *agent : active_3d_avoidance_agents) {
  1185. agent->dispatch_avoidance_callback();
  1186. }
  1187. }
  1188. void NavMap::clip_path(const LocalVector<gd::NavigationPoly> &p_navigation_polys, Vector<Vector3> &path, const gd::NavigationPoly *from_poly, const Vector3 &p_to_point, const gd::NavigationPoly *p_to_poly, Vector<int32_t> *r_path_types, TypedArray<RID> *r_path_rids, Vector<int64_t> *r_path_owners) const {
  1189. Vector3 from = path[path.size() - 1];
  1190. if (from.is_equal_approx(p_to_point)) {
  1191. return;
  1192. }
  1193. Plane cut_plane;
  1194. cut_plane.normal = (from - p_to_point).cross(up);
  1195. if (cut_plane.normal == Vector3()) {
  1196. return;
  1197. }
  1198. cut_plane.normal.normalize();
  1199. cut_plane.d = cut_plane.normal.dot(from);
  1200. while (from_poly != p_to_poly) {
  1201. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  1202. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  1203. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  1204. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  1205. if (!pathway_start.is_equal_approx(pathway_end)) {
  1206. Vector3 inters;
  1207. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  1208. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) {
  1209. path.push_back(inters);
  1210. APPEND_METADATA(from_poly->poly);
  1211. }
  1212. }
  1213. }
  1214. }
  1215. }
  1216. void NavMap::_update_merge_rasterizer_cell_dimensions() {
  1217. merge_rasterizer_cell_size = cell_size * merge_rasterizer_cell_scale;
  1218. merge_rasterizer_cell_height = cell_height * merge_rasterizer_cell_scale;
  1219. }
  1220. NavMap::NavMap() {
  1221. avoidance_use_multiple_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_multiple_threads");
  1222. avoidance_use_high_priority_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_high_priority_threads");
  1223. }
  1224. NavMap::~NavMap() {
  1225. }