nav_map.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. /*************************************************************************/
  2. /* nav_map.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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 "core/object/worker_thread_pool.h"
  32. #include "nav_region.h"
  33. #include "rvo_agent.h"
  34. #include <algorithm>
  35. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  36. void NavMap::set_up(Vector3 p_up) {
  37. up = p_up;
  38. regenerate_polygons = true;
  39. }
  40. void NavMap::set_cell_size(float p_cell_size) {
  41. cell_size = p_cell_size;
  42. regenerate_polygons = true;
  43. }
  44. void NavMap::set_edge_connection_margin(float p_edge_connection_margin) {
  45. edge_connection_margin = p_edge_connection_margin;
  46. regenerate_links = true;
  47. }
  48. gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
  49. const int x = int(Math::floor(p_pos.x / cell_size));
  50. const int y = int(Math::floor(p_pos.y / cell_size));
  51. const int z = int(Math::floor(p_pos.z / cell_size));
  52. gd::PointKey p;
  53. p.key = 0;
  54. p.x = x;
  55. p.y = y;
  56. p.z = z;
  57. return p;
  58. }
  59. Vector<Vector3> NavMap::get_path(Vector3 p_origin, Vector3 p_destination, bool p_optimize, uint32_t p_navigation_layers) const {
  60. // Find the start poly and the end poly on this map.
  61. const gd::Polygon *begin_poly = nullptr;
  62. const gd::Polygon *end_poly = nullptr;
  63. Vector3 begin_point;
  64. Vector3 end_point;
  65. float begin_d = 1e20;
  66. float end_d = 1e20;
  67. // Find the initial poly and the end poly on this map.
  68. for (size_t i(0); i < polygons.size(); i++) {
  69. const gd::Polygon &p = polygons[i];
  70. // Only consider the polygon if it in a region with compatible layers.
  71. if ((p_navigation_layers & p.owner->get_navigation_layers()) == 0) {
  72. continue;
  73. }
  74. // For each face check the distance between the origin/destination
  75. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  76. const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  77. Vector3 point = face.get_closest_point_to(p_origin);
  78. float distance_to_point = point.distance_to(p_origin);
  79. if (distance_to_point < begin_d) {
  80. begin_d = distance_to_point;
  81. begin_poly = &p;
  82. begin_point = point;
  83. }
  84. point = face.get_closest_point_to(p_destination);
  85. distance_to_point = point.distance_to(p_destination);
  86. if (distance_to_point < end_d) {
  87. end_d = distance_to_point;
  88. end_poly = &p;
  89. end_point = point;
  90. }
  91. }
  92. }
  93. // Check for trivial cases
  94. if (!begin_poly || !end_poly) {
  95. return Vector<Vector3>();
  96. }
  97. if (begin_poly == end_poly) {
  98. Vector<Vector3> path;
  99. path.resize(2);
  100. path.write[0] = begin_point;
  101. path.write[1] = end_point;
  102. return path;
  103. }
  104. // List of all reachable navigation polys.
  105. LocalVector<gd::NavigationPoly> navigation_polys;
  106. navigation_polys.reserve(polygons.size() * 0.75);
  107. // Add the start polygon to the reachable navigation polygons.
  108. gd::NavigationPoly begin_navigation_poly = gd::NavigationPoly(begin_poly);
  109. begin_navigation_poly.self_id = 0;
  110. begin_navigation_poly.entry = begin_point;
  111. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  112. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  113. navigation_polys.push_back(begin_navigation_poly);
  114. // List of polygon IDs to visit.
  115. List<uint32_t> to_visit;
  116. to_visit.push_back(0);
  117. // This is an implementation of the A* algorithm.
  118. int least_cost_id = 0;
  119. bool found_route = false;
  120. const gd::Polygon *reachable_end = nullptr;
  121. float reachable_d = 1e30;
  122. bool is_reachable = true;
  123. gd::NavigationPoly *prev_least_cost_poly = nullptr;
  124. while (true) {
  125. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  126. for (size_t i = 0; i < navigation_polys[least_cost_id].poly->edges.size(); i++) {
  127. gd::NavigationPoly *least_cost_poly = &navigation_polys[least_cost_id];
  128. const gd::Edge &edge = least_cost_poly->poly->edges[i];
  129. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  130. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  131. const gd::Edge::Connection &connection = edge.connections[connection_index];
  132. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  133. if ((p_navigation_layers & connection.polygon->owner->get_navigation_layers()) == 0) {
  134. continue;
  135. }
  136. float region_enter_cost = 0.0;
  137. float region_travel_cost = least_cost_poly->poly->owner->get_travel_cost();
  138. if (prev_least_cost_poly != nullptr && !(prev_least_cost_poly->poly->owner->get_self() == least_cost_poly->poly->owner->get_self())) {
  139. region_enter_cost = least_cost_poly->poly->owner->get_enter_cost();
  140. }
  141. prev_least_cost_poly = least_cost_poly;
  142. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  143. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly->entry, pathway);
  144. const float new_distance = (least_cost_poly->entry.distance_to(new_entry) * region_travel_cost) + region_enter_cost + least_cost_poly->traveled_distance;
  145. int64_t already_visited_polygon_index = navigation_polys.find(gd::NavigationPoly(connection.polygon));
  146. if (already_visited_polygon_index != -1) {
  147. // Polygon already visited, check if we can reduce the travel cost.
  148. gd::NavigationPoly &avp = navigation_polys[already_visited_polygon_index];
  149. if (new_distance < avp.traveled_distance) {
  150. avp.back_navigation_poly_id = least_cost_id;
  151. avp.back_navigation_edge = connection.edge;
  152. avp.back_navigation_edge_pathway_start = connection.pathway_start;
  153. avp.back_navigation_edge_pathway_end = connection.pathway_end;
  154. avp.traveled_distance = new_distance;
  155. avp.entry = new_entry;
  156. }
  157. } else {
  158. // Add the neighbour polygon to the reachable ones.
  159. gd::NavigationPoly new_navigation_poly = gd::NavigationPoly(connection.polygon);
  160. new_navigation_poly.self_id = navigation_polys.size();
  161. new_navigation_poly.back_navigation_poly_id = least_cost_id;
  162. new_navigation_poly.back_navigation_edge = connection.edge;
  163. new_navigation_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  164. new_navigation_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  165. new_navigation_poly.traveled_distance = new_distance;
  166. new_navigation_poly.entry = new_entry;
  167. navigation_polys.push_back(new_navigation_poly);
  168. // Add the neighbour polygon to the polygons to visit.
  169. to_visit.push_back(navigation_polys.size() - 1);
  170. }
  171. }
  172. }
  173. // Removes the least cost polygon from the list of polygons to visit so we can advance.
  174. to_visit.erase(least_cost_id);
  175. // When the list of polygons to visit is empty at this point it means the End Polygon is not reachable
  176. if (to_visit.size() == 0) {
  177. // Thus use the further reachable polygon
  178. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  179. is_reachable = false;
  180. if (reachable_end == nullptr) {
  181. // The path is not found and there is not a way out.
  182. break;
  183. }
  184. // Set as end point the furthest reachable point.
  185. end_poly = reachable_end;
  186. end_d = 1e20;
  187. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  188. Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  189. Vector3 spoint = f.get_closest_point_to(p_destination);
  190. float dpoint = spoint.distance_to(p_destination);
  191. if (dpoint < end_d) {
  192. end_point = spoint;
  193. end_d = dpoint;
  194. }
  195. }
  196. // Reset open and navigation_polys
  197. gd::NavigationPoly np = navigation_polys[0];
  198. navigation_polys.clear();
  199. navigation_polys.push_back(np);
  200. to_visit.clear();
  201. to_visit.push_back(0);
  202. least_cost_id = 0;
  203. reachable_end = nullptr;
  204. continue;
  205. }
  206. // Find the polygon with the minimum cost from the list of polygons to visit.
  207. least_cost_id = -1;
  208. float least_cost = 1e30;
  209. for (List<uint32_t>::Element *element = to_visit.front(); element != nullptr; element = element->next()) {
  210. gd::NavigationPoly *np = &navigation_polys[element->get()];
  211. float cost = np->traveled_distance;
  212. cost += (np->entry.distance_to(end_point) * np->poly->owner->get_travel_cost());
  213. if (cost < least_cost) {
  214. least_cost_id = np->self_id;
  215. least_cost = cost;
  216. }
  217. }
  218. ERR_BREAK(least_cost_id == -1);
  219. // Stores the further reachable end polygon, in case our goal is not reachable.
  220. if (is_reachable) {
  221. float d = navigation_polys[least_cost_id].entry.distance_to(p_destination) * navigation_polys[least_cost_id].poly->owner->get_travel_cost();
  222. if (reachable_d > d) {
  223. reachable_d = d;
  224. reachable_end = navigation_polys[least_cost_id].poly;
  225. }
  226. }
  227. // Check if we reached the end
  228. if (navigation_polys[least_cost_id].poly == end_poly) {
  229. found_route = true;
  230. break;
  231. }
  232. }
  233. // If we did not find a route, return an empty path.
  234. if (!found_route) {
  235. return Vector<Vector3>();
  236. }
  237. Vector<Vector3> path;
  238. // Optimize the path.
  239. if (p_optimize) {
  240. // Set the apex poly/point to the end point
  241. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  242. Vector3 apex_point = end_point;
  243. gd::NavigationPoly *left_poly = apex_poly;
  244. Vector3 left_portal = apex_point;
  245. gd::NavigationPoly *right_poly = apex_poly;
  246. Vector3 right_portal = apex_point;
  247. gd::NavigationPoly *p = apex_poly;
  248. path.push_back(end_point);
  249. while (p) {
  250. // Set left and right points of the pathway between polygons.
  251. Vector3 left = p->back_navigation_edge_pathway_start;
  252. Vector3 right = p->back_navigation_edge_pathway_end;
  253. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(up) < 0) {
  254. SWAP(left, right);
  255. }
  256. bool skip = false;
  257. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(up) >= 0) {
  258. //process
  259. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(up) > 0) {
  260. left_poly = p;
  261. left_portal = left;
  262. } else {
  263. clip_path(navigation_polys, path, apex_poly, right_portal, right_poly);
  264. apex_point = right_portal;
  265. p = right_poly;
  266. left_poly = p;
  267. apex_poly = p;
  268. left_portal = apex_point;
  269. right_portal = apex_point;
  270. path.push_back(apex_point);
  271. skip = true;
  272. }
  273. }
  274. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(up) <= 0) {
  275. //process
  276. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(up) < 0) {
  277. right_poly = p;
  278. right_portal = right;
  279. } else {
  280. clip_path(navigation_polys, path, apex_poly, left_portal, left_poly);
  281. apex_point = left_portal;
  282. p = left_poly;
  283. right_poly = p;
  284. apex_poly = p;
  285. right_portal = apex_point;
  286. left_portal = apex_point;
  287. path.push_back(apex_point);
  288. }
  289. }
  290. // Go to the previous polygon.
  291. if (p->back_navigation_poly_id != -1) {
  292. p = &navigation_polys[p->back_navigation_poly_id];
  293. } else {
  294. // The end
  295. p = nullptr;
  296. }
  297. }
  298. // If the last point is not the begin point, add it to the list.
  299. if (path[path.size() - 1] != begin_point) {
  300. path.push_back(begin_point);
  301. }
  302. path.reverse();
  303. } else {
  304. path.push_back(end_point);
  305. // Add mid points
  306. int np_id = least_cost_id;
  307. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  308. int prev = navigation_polys[np_id].back_navigation_edge;
  309. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  310. Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  311. path.push_back(point);
  312. np_id = navigation_polys[np_id].back_navigation_poly_id;
  313. }
  314. path.push_back(begin_point);
  315. path.reverse();
  316. }
  317. return path;
  318. }
  319. Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
  320. bool use_collision = p_use_collision;
  321. Vector3 closest_point;
  322. real_t closest_point_d = 1e20;
  323. for (size_t i(0); i < polygons.size(); i++) {
  324. const gd::Polygon &p = polygons[i];
  325. // For each face check the distance to the segment
  326. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  327. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  328. Vector3 inters;
  329. if (f.intersects_segment(p_from, p_to, &inters)) {
  330. const real_t d = closest_point_d = p_from.distance_to(inters);
  331. if (use_collision == false) {
  332. closest_point = inters;
  333. use_collision = true;
  334. closest_point_d = d;
  335. } else if (closest_point_d > d) {
  336. closest_point = inters;
  337. closest_point_d = d;
  338. }
  339. }
  340. }
  341. if (use_collision == false) {
  342. for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
  343. Vector3 a, b;
  344. Geometry3D::get_closest_points_between_segments(
  345. p_from,
  346. p_to,
  347. p.points[point_id].pos,
  348. p.points[(point_id + 1) % p.points.size()].pos,
  349. a,
  350. b);
  351. const real_t d = a.distance_to(b);
  352. if (d < closest_point_d) {
  353. closest_point_d = d;
  354. closest_point = b;
  355. }
  356. }
  357. }
  358. }
  359. return closest_point;
  360. }
  361. Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
  362. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  363. return cp.point;
  364. }
  365. Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
  366. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  367. return cp.normal;
  368. }
  369. RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
  370. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  371. return cp.owner;
  372. }
  373. gd::ClosestPointQueryResult NavMap::get_closest_point_info(const Vector3 &p_point) const {
  374. gd::ClosestPointQueryResult result;
  375. real_t closest_point_ds = 1e20;
  376. for (size_t i(0); i < polygons.size(); i++) {
  377. const gd::Polygon &p = polygons[i];
  378. // For each face check the distance to the point
  379. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  380. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  381. const Vector3 inters = f.get_closest_point_to(p_point);
  382. const real_t ds = inters.distance_squared_to(p_point);
  383. if (ds < closest_point_ds) {
  384. result.point = inters;
  385. result.normal = f.get_plane().normal;
  386. result.owner = p.owner->get_self();
  387. closest_point_ds = ds;
  388. }
  389. }
  390. }
  391. return result;
  392. }
  393. void NavMap::add_region(NavRegion *p_region) {
  394. regions.push_back(p_region);
  395. regenerate_links = true;
  396. }
  397. void NavMap::remove_region(NavRegion *p_region) {
  398. int64_t region_index = regions.find(p_region);
  399. if (region_index != -1) {
  400. regions.remove_at_unordered(region_index);
  401. regenerate_links = true;
  402. }
  403. }
  404. bool NavMap::has_agent(RvoAgent *agent) const {
  405. return (agents.find(agent) != -1);
  406. }
  407. void NavMap::add_agent(RvoAgent *agent) {
  408. if (!has_agent(agent)) {
  409. agents.push_back(agent);
  410. agents_dirty = true;
  411. }
  412. }
  413. void NavMap::remove_agent(RvoAgent *agent) {
  414. remove_agent_as_controlled(agent);
  415. int64_t agent_index = agents.find(agent);
  416. if (agent_index != -1) {
  417. agents.remove_at_unordered(agent_index);
  418. agents_dirty = true;
  419. }
  420. }
  421. void NavMap::set_agent_as_controlled(RvoAgent *agent) {
  422. const bool exist = (controlled_agents.find(agent) != -1);
  423. if (!exist) {
  424. ERR_FAIL_COND(!has_agent(agent));
  425. controlled_agents.push_back(agent);
  426. }
  427. }
  428. void NavMap::remove_agent_as_controlled(RvoAgent *agent) {
  429. int64_t active_avoidance_agent_index = controlled_agents.find(agent);
  430. if (active_avoidance_agent_index != -1) {
  431. controlled_agents.remove_at_unordered(active_avoidance_agent_index);
  432. agents_dirty = true;
  433. }
  434. }
  435. void NavMap::sync() {
  436. // Check if we need to update the links.
  437. if (regenerate_polygons) {
  438. for (uint32_t r = 0; r < regions.size(); r++) {
  439. regions[r]->scratch_polygons();
  440. }
  441. regenerate_links = true;
  442. }
  443. for (uint32_t r = 0; r < regions.size(); r++) {
  444. if (regions[r]->sync()) {
  445. regenerate_links = true;
  446. }
  447. }
  448. if (regenerate_links) {
  449. // Remove regions connections.
  450. for (uint32_t r = 0; r < regions.size(); r++) {
  451. regions[r]->get_connections().clear();
  452. }
  453. // Resize the polygon count.
  454. int count = 0;
  455. for (uint32_t r = 0; r < regions.size(); r++) {
  456. count += regions[r]->get_polygons().size();
  457. }
  458. polygons.resize(count);
  459. // Copy all region polygons in the map.
  460. count = 0;
  461. for (uint32_t r = 0; r < regions.size(); r++) {
  462. const LocalVector<gd::Polygon> &polygons_source = regions[r]->get_polygons();
  463. for (uint32_t n = 0; n < polygons_source.size(); n++) {
  464. polygons[count + n] = polygons_source[n];
  465. }
  466. count += regions[r]->get_polygons().size();
  467. }
  468. // Group all edges per key.
  469. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections;
  470. for (uint32_t poly_id = 0; poly_id < polygons.size(); poly_id++) {
  471. gd::Polygon &poly(polygons[poly_id]);
  472. for (uint32_t p = 0; p < poly.points.size(); p++) {
  473. int next_point = (p + 1) % poly.points.size();
  474. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  475. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek);
  476. if (!connection) {
  477. connections[ek] = Vector<gd::Edge::Connection>();
  478. }
  479. if (connections[ek].size() <= 1) {
  480. // Add the polygon/edge tuple to this key.
  481. gd::Edge::Connection new_connection;
  482. new_connection.polygon = &poly;
  483. new_connection.edge = p;
  484. new_connection.pathway_start = poly.points[p].pos;
  485. new_connection.pathway_end = poly.points[next_point].pos;
  486. connections[ek].push_back(new_connection);
  487. } else {
  488. // The edge is already connected with another edge, skip.
  489. ERR_PRINT_ONCE("Attempted to merge a navigation mesh triangle edge with another already-merged edge. This happens when the current `cell_size` is different from the one used to generate the navigation mesh. This will cause navigation problems.");
  490. }
  491. }
  492. }
  493. Vector<gd::Edge::Connection> free_edges;
  494. for (KeyValue<gd::EdgeKey, Vector<gd::Edge::Connection>> &E : connections) {
  495. if (E.value.size() == 2) {
  496. // Connect edge that are shared in different polygons.
  497. gd::Edge::Connection &c1 = E.value.write[0];
  498. gd::Edge::Connection &c2 = E.value.write[1];
  499. c1.polygon->edges[c1.edge].connections.push_back(c2);
  500. c2.polygon->edges[c2.edge].connections.push_back(c1);
  501. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  502. } else {
  503. CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size()));
  504. free_edges.push_back(E.value[0]);
  505. }
  506. }
  507. // Find the compatible near edges.
  508. //
  509. // Note:
  510. // Considering that the edges must be compatible (for obvious reasons)
  511. // to be connected, create new polygons to remove that small gap is
  512. // not really useful and would result in wasteful computation during
  513. // connection, integration and path finding.
  514. for (int i = 0; i < free_edges.size(); i++) {
  515. const gd::Edge::Connection &free_edge = free_edges[i];
  516. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  517. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  518. for (int j = 0; j < free_edges.size(); j++) {
  519. const gd::Edge::Connection &other_edge = free_edges[j];
  520. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  521. continue;
  522. }
  523. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  524. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  525. // Compute the projection of the opposite edge on the current one
  526. Vector3 edge_vector = edge_p2 - edge_p1;
  527. float projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  528. float projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  529. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  530. continue;
  531. }
  532. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  533. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  534. Vector3 other1;
  535. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  536. other1 = other_edge_p1;
  537. } else {
  538. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  539. }
  540. if (other1.distance_to(self1) > edge_connection_margin) {
  541. continue;
  542. }
  543. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  544. Vector3 other2;
  545. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  546. other2 = other_edge_p2;
  547. } else {
  548. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  549. }
  550. if (other2.distance_to(self2) > edge_connection_margin) {
  551. continue;
  552. }
  553. // The edges can now be connected.
  554. gd::Edge::Connection new_connection = other_edge;
  555. new_connection.pathway_start = (self1 + other1) / 2.0;
  556. new_connection.pathway_end = (self2 + other2) / 2.0;
  557. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  558. // Add the connection to the region_connection map.
  559. free_edge.polygon->owner->get_connections().push_back(new_connection);
  560. }
  561. }
  562. // Update the update ID.
  563. map_update_id = (map_update_id + 1) % 9999999;
  564. }
  565. // Update agents tree.
  566. if (agents_dirty) {
  567. // cannot use LocalVector here as RVO library expects std::vector to build KdTree
  568. std::vector<RVO::Agent *> raw_agents;
  569. raw_agents.reserve(agents.size());
  570. for (size_t i(0); i < agents.size(); i++) {
  571. raw_agents.push_back(agents[i]->get_agent());
  572. }
  573. rvo.buildAgentTree(raw_agents);
  574. }
  575. regenerate_polygons = false;
  576. regenerate_links = false;
  577. agents_dirty = false;
  578. }
  579. void NavMap::compute_single_step(uint32_t index, RvoAgent **agent) {
  580. (*(agent + index))->get_agent()->computeNeighbors(&rvo);
  581. (*(agent + index))->get_agent()->computeNewVelocity(deltatime);
  582. }
  583. void NavMap::step(real_t p_deltatime) {
  584. deltatime = p_deltatime;
  585. if (controlled_agents.size() > 0) {
  586. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &NavMap::compute_single_step, controlled_agents.ptr(), controlled_agents.size(), -1, true, SNAME("NavigationMapAgents"));
  587. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  588. }
  589. }
  590. void NavMap::dispatch_callbacks() {
  591. for (int i(0); i < static_cast<int>(controlled_agents.size()); i++) {
  592. controlled_agents[i]->dispatch_callback();
  593. }
  594. }
  595. 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) const {
  596. Vector3 from = path[path.size() - 1];
  597. if (from.is_equal_approx(p_to_point)) {
  598. return;
  599. }
  600. Plane cut_plane;
  601. cut_plane.normal = (from - p_to_point).cross(up);
  602. if (cut_plane.normal == Vector3()) {
  603. return;
  604. }
  605. cut_plane.normal.normalize();
  606. cut_plane.d = cut_plane.normal.dot(from);
  607. while (from_poly != p_to_poly) {
  608. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  609. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  610. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  611. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  612. if (!pathway_start.is_equal_approx(pathway_end)) {
  613. Vector3 inters;
  614. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  615. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) {
  616. path.push_back(inters);
  617. }
  618. }
  619. }
  620. }
  621. }
  622. NavMap::NavMap() {
  623. }
  624. NavMap::~NavMap() {
  625. }