nav_map.cpp 26 KB

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