nav_map.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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 "core/object/worker_thread_pool.h"
  32. #include "nav_agent.h"
  33. #include "nav_link.h"
  34. #include "nav_region.h"
  35. #include <algorithm>
  36. #define THREE_POINTS_CROSS_PRODUCT(m_a, m_b, m_c) (((m_c) - (m_a)).cross((m_b) - (m_a)))
  37. // Helper macro
  38. #define APPEND_METADATA(poly) \
  39. if (r_path_types) { \
  40. r_path_types->push_back(poly->owner->get_type()); \
  41. } \
  42. if (r_path_rids) { \
  43. r_path_rids->push_back(poly->owner->get_self()); \
  44. } \
  45. if (r_path_owners) { \
  46. r_path_owners->push_back(poly->owner->get_owner_id()); \
  47. }
  48. void NavMap::set_up(Vector3 p_up) {
  49. up = p_up;
  50. regenerate_polygons = true;
  51. }
  52. void NavMap::set_cell_size(float p_cell_size) {
  53. cell_size = p_cell_size;
  54. regenerate_polygons = true;
  55. }
  56. void NavMap::set_edge_connection_margin(float p_edge_connection_margin) {
  57. edge_connection_margin = p_edge_connection_margin;
  58. regenerate_links = true;
  59. }
  60. void NavMap::set_link_connection_radius(float p_link_connection_radius) {
  61. link_connection_radius = p_link_connection_radius;
  62. regenerate_links = true;
  63. }
  64. gd::PointKey NavMap::get_point_key(const Vector3 &p_pos) const {
  65. const int x = int(Math::floor(p_pos.x / cell_size));
  66. const int y = int(Math::floor(p_pos.y / cell_size));
  67. const int z = int(Math::floor(p_pos.z / cell_size));
  68. gd::PointKey p;
  69. p.key = 0;
  70. p.x = x;
  71. p.y = y;
  72. p.z = z;
  73. return p;
  74. }
  75. 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 {
  76. // Clear metadata outputs.
  77. if (r_path_types) {
  78. r_path_types->clear();
  79. }
  80. if (r_path_rids) {
  81. r_path_rids->clear();
  82. }
  83. if (r_path_owners) {
  84. r_path_owners->clear();
  85. }
  86. // Find the start poly and the end poly on this map.
  87. const gd::Polygon *begin_poly = nullptr;
  88. const gd::Polygon *end_poly = nullptr;
  89. Vector3 begin_point;
  90. Vector3 end_point;
  91. float begin_d = 1e20;
  92. float end_d = 1e20;
  93. // Find the initial poly and the end poly on this map.
  94. for (const gd::Polygon &p : polygons) {
  95. // Only consider the polygon if it in a region with compatible layers.
  96. if ((p_navigation_layers & p.owner->get_navigation_layers()) == 0) {
  97. continue;
  98. }
  99. // For each face check the distance between the origin/destination
  100. for (size_t point_id = 2; point_id < p.points.size(); point_id++) {
  101. const Face3 face(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  102. Vector3 point = face.get_closest_point_to(p_origin);
  103. float distance_to_point = point.distance_to(p_origin);
  104. if (distance_to_point < begin_d) {
  105. begin_d = distance_to_point;
  106. begin_poly = &p;
  107. begin_point = point;
  108. }
  109. point = face.get_closest_point_to(p_destination);
  110. distance_to_point = point.distance_to(p_destination);
  111. if (distance_to_point < end_d) {
  112. end_d = distance_to_point;
  113. end_poly = &p;
  114. end_point = point;
  115. }
  116. }
  117. }
  118. // Check for trivial cases
  119. if (!begin_poly || !end_poly) {
  120. return Vector<Vector3>();
  121. }
  122. if (begin_poly == end_poly) {
  123. if (r_path_types) {
  124. r_path_types->resize(2);
  125. r_path_types->write[0] = begin_poly->owner->get_type();
  126. r_path_types->write[1] = end_poly->owner->get_type();
  127. }
  128. if (r_path_rids) {
  129. r_path_rids->resize(2);
  130. (*r_path_rids)[0] = begin_poly->owner->get_self();
  131. (*r_path_rids)[1] = end_poly->owner->get_self();
  132. }
  133. if (r_path_owners) {
  134. r_path_owners->resize(2);
  135. r_path_owners->write[0] = begin_poly->owner->get_owner_id();
  136. r_path_owners->write[1] = end_poly->owner->get_owner_id();
  137. }
  138. Vector<Vector3> path;
  139. path.resize(2);
  140. path.write[0] = begin_point;
  141. path.write[1] = end_point;
  142. return path;
  143. }
  144. // List of all reachable navigation polys.
  145. LocalVector<gd::NavigationPoly> navigation_polys;
  146. navigation_polys.reserve(polygons.size() * 0.75);
  147. // Add the start polygon to the reachable navigation polygons.
  148. gd::NavigationPoly begin_navigation_poly = gd::NavigationPoly(begin_poly);
  149. begin_navigation_poly.self_id = 0;
  150. begin_navigation_poly.entry = begin_point;
  151. begin_navigation_poly.back_navigation_edge_pathway_start = begin_point;
  152. begin_navigation_poly.back_navigation_edge_pathway_end = begin_point;
  153. navigation_polys.push_back(begin_navigation_poly);
  154. // List of polygon IDs to visit.
  155. List<uint32_t> to_visit;
  156. to_visit.push_back(0);
  157. // This is an implementation of the A* algorithm.
  158. int least_cost_id = 0;
  159. int prev_least_cost_id = -1;
  160. bool found_route = false;
  161. const gd::Polygon *reachable_end = nullptr;
  162. float reachable_d = 1e30;
  163. bool is_reachable = true;
  164. while (true) {
  165. // Takes the current least_cost_poly neighbors (iterating over its edges) and compute the traveled_distance.
  166. for (const gd::Edge &edge : navigation_polys[least_cost_id].poly->edges) {
  167. // Iterate over connections in this edge, then compute the new optimized travel distance assigned to this polygon.
  168. for (int connection_index = 0; connection_index < edge.connections.size(); connection_index++) {
  169. const gd::Edge::Connection &connection = edge.connections[connection_index];
  170. // Only consider the connection to another polygon if this polygon is in a region with compatible layers.
  171. if ((p_navigation_layers & connection.polygon->owner->get_navigation_layers()) == 0) {
  172. continue;
  173. }
  174. const gd::NavigationPoly &least_cost_poly = navigation_polys[least_cost_id];
  175. float poly_enter_cost = 0.0;
  176. float poly_travel_cost = least_cost_poly.poly->owner->get_travel_cost();
  177. if (prev_least_cost_id != -1 && (navigation_polys[prev_least_cost_id].poly->owner->get_self() != least_cost_poly.poly->owner->get_self())) {
  178. poly_enter_cost = least_cost_poly.poly->owner->get_enter_cost();
  179. }
  180. prev_least_cost_id = least_cost_id;
  181. Vector3 pathway[2] = { connection.pathway_start, connection.pathway_end };
  182. const Vector3 new_entry = Geometry3D::get_closest_point_to_segment(least_cost_poly.entry, pathway);
  183. const float new_distance = (least_cost_poly.entry.distance_to(new_entry) * poly_travel_cost) + poly_enter_cost + least_cost_poly.traveled_distance;
  184. int64_t already_visited_polygon_index = navigation_polys.find(gd::NavigationPoly(connection.polygon));
  185. if (already_visited_polygon_index != -1) {
  186. // Polygon already visited, check if we can reduce the travel cost.
  187. gd::NavigationPoly &avp = navigation_polys[already_visited_polygon_index];
  188. if (new_distance < avp.traveled_distance) {
  189. avp.back_navigation_poly_id = least_cost_id;
  190. avp.back_navigation_edge = connection.edge;
  191. avp.back_navigation_edge_pathway_start = connection.pathway_start;
  192. avp.back_navigation_edge_pathway_end = connection.pathway_end;
  193. avp.traveled_distance = new_distance;
  194. avp.entry = new_entry;
  195. }
  196. } else {
  197. // Add the neighbor polygon to the reachable ones.
  198. gd::NavigationPoly new_navigation_poly = gd::NavigationPoly(connection.polygon);
  199. new_navigation_poly.self_id = navigation_polys.size();
  200. new_navigation_poly.back_navigation_poly_id = least_cost_id;
  201. new_navigation_poly.back_navigation_edge = connection.edge;
  202. new_navigation_poly.back_navigation_edge_pathway_start = connection.pathway_start;
  203. new_navigation_poly.back_navigation_edge_pathway_end = connection.pathway_end;
  204. new_navigation_poly.traveled_distance = new_distance;
  205. new_navigation_poly.entry = new_entry;
  206. navigation_polys.push_back(new_navigation_poly);
  207. // Add the neighbor polygon to the polygons to visit.
  208. to_visit.push_back(navigation_polys.size() - 1);
  209. }
  210. }
  211. }
  212. // Removes the least cost polygon from the list of polygons to visit so we can advance.
  213. to_visit.erase(least_cost_id);
  214. // When the list of polygons to visit is empty at this point it means the End Polygon is not reachable
  215. if (to_visit.size() == 0) {
  216. // Thus use the further reachable polygon
  217. ERR_BREAK_MSG(is_reachable == false, "It's not expect to not find the most reachable polygons");
  218. is_reachable = false;
  219. if (reachable_end == nullptr) {
  220. // The path is not found and there is not a way out.
  221. break;
  222. }
  223. // Set as end point the furthest reachable point.
  224. end_poly = reachable_end;
  225. end_d = 1e20;
  226. for (size_t point_id = 2; point_id < end_poly->points.size(); point_id++) {
  227. Face3 f(end_poly->points[0].pos, end_poly->points[point_id - 1].pos, end_poly->points[point_id].pos);
  228. Vector3 spoint = f.get_closest_point_to(p_destination);
  229. float dpoint = spoint.distance_to(p_destination);
  230. if (dpoint < end_d) {
  231. end_point = spoint;
  232. end_d = dpoint;
  233. }
  234. }
  235. // Reset open and navigation_polys
  236. gd::NavigationPoly np = navigation_polys[0];
  237. navigation_polys.clear();
  238. navigation_polys.push_back(np);
  239. to_visit.clear();
  240. to_visit.push_back(0);
  241. least_cost_id = 0;
  242. prev_least_cost_id = -1;
  243. reachable_end = nullptr;
  244. continue;
  245. }
  246. // Find the polygon with the minimum cost from the list of polygons to visit.
  247. least_cost_id = -1;
  248. float least_cost = 1e30;
  249. for (List<uint32_t>::Element *element = to_visit.front(); element != nullptr; element = element->next()) {
  250. gd::NavigationPoly *np = &navigation_polys[element->get()];
  251. float cost = np->traveled_distance;
  252. cost += (np->entry.distance_to(end_point) * np->poly->owner->get_travel_cost());
  253. if (cost < least_cost) {
  254. least_cost_id = np->self_id;
  255. least_cost = cost;
  256. }
  257. }
  258. ERR_BREAK(least_cost_id == -1);
  259. // Stores the further reachable end polygon, in case our goal is not reachable.
  260. if (is_reachable) {
  261. float d = navigation_polys[least_cost_id].entry.distance_to(p_destination) * navigation_polys[least_cost_id].poly->owner->get_travel_cost();
  262. if (reachable_d > d) {
  263. reachable_d = d;
  264. reachable_end = navigation_polys[least_cost_id].poly;
  265. }
  266. }
  267. // Check if we reached the end
  268. if (navigation_polys[least_cost_id].poly == end_poly) {
  269. found_route = true;
  270. break;
  271. }
  272. }
  273. // If we did not find a route, return an empty path.
  274. if (!found_route) {
  275. return Vector<Vector3>();
  276. }
  277. Vector<Vector3> path;
  278. // Optimize the path.
  279. if (p_optimize) {
  280. // Set the apex poly/point to the end point
  281. gd::NavigationPoly *apex_poly = &navigation_polys[least_cost_id];
  282. Vector3 apex_point = end_point;
  283. gd::NavigationPoly *left_poly = apex_poly;
  284. Vector3 left_portal = apex_point;
  285. gd::NavigationPoly *right_poly = apex_poly;
  286. Vector3 right_portal = apex_point;
  287. gd::NavigationPoly *p = apex_poly;
  288. path.push_back(end_point);
  289. APPEND_METADATA(end_poly);
  290. while (p) {
  291. // Set left and right points of the pathway between polygons.
  292. Vector3 left = p->back_navigation_edge_pathway_start;
  293. Vector3 right = p->back_navigation_edge_pathway_end;
  294. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left, right).dot(up) < 0) {
  295. SWAP(left, right);
  296. }
  297. bool skip = false;
  298. if (THREE_POINTS_CROSS_PRODUCT(apex_point, left_portal, left).dot(up) >= 0) {
  299. //process
  300. if (left_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, left, right_portal).dot(up) > 0) {
  301. left_poly = p;
  302. left_portal = left;
  303. } else {
  304. clip_path(navigation_polys, path, apex_poly, right_portal, right_poly, r_path_types, r_path_rids, r_path_owners);
  305. apex_point = right_portal;
  306. p = right_poly;
  307. left_poly = p;
  308. apex_poly = p;
  309. left_portal = apex_point;
  310. right_portal = apex_point;
  311. path.push_back(apex_point);
  312. APPEND_METADATA(apex_poly->poly);
  313. skip = true;
  314. }
  315. }
  316. if (!skip && THREE_POINTS_CROSS_PRODUCT(apex_point, right_portal, right).dot(up) <= 0) {
  317. //process
  318. if (right_portal == apex_point || THREE_POINTS_CROSS_PRODUCT(apex_point, right, left_portal).dot(up) < 0) {
  319. right_poly = p;
  320. right_portal = right;
  321. } else {
  322. clip_path(navigation_polys, path, apex_poly, left_portal, left_poly, r_path_types, r_path_rids, r_path_owners);
  323. apex_point = left_portal;
  324. p = left_poly;
  325. right_poly = p;
  326. apex_poly = p;
  327. right_portal = apex_point;
  328. left_portal = apex_point;
  329. path.push_back(apex_point);
  330. APPEND_METADATA(apex_poly->poly);
  331. }
  332. }
  333. // Go to the previous polygon.
  334. if (p->back_navigation_poly_id != -1) {
  335. p = &navigation_polys[p->back_navigation_poly_id];
  336. } else {
  337. // The end
  338. p = nullptr;
  339. }
  340. }
  341. // If the last point is not the begin point, add it to the list.
  342. if (path[path.size() - 1] != begin_point) {
  343. path.push_back(begin_point);
  344. APPEND_METADATA(begin_poly);
  345. }
  346. path.reverse();
  347. if (r_path_types) {
  348. r_path_types->reverse();
  349. }
  350. if (r_path_rids) {
  351. r_path_rids->reverse();
  352. }
  353. if (r_path_owners) {
  354. r_path_owners->reverse();
  355. }
  356. } else {
  357. path.push_back(end_point);
  358. APPEND_METADATA(end_poly);
  359. // Add mid points
  360. int np_id = least_cost_id;
  361. while (np_id != -1 && navigation_polys[np_id].back_navigation_poly_id != -1) {
  362. if (navigation_polys[np_id].back_navigation_edge != -1) {
  363. int prev = navigation_polys[np_id].back_navigation_edge;
  364. int prev_n = (navigation_polys[np_id].back_navigation_edge + 1) % navigation_polys[np_id].poly->points.size();
  365. Vector3 point = (navigation_polys[np_id].poly->points[prev].pos + navigation_polys[np_id].poly->points[prev_n].pos) * 0.5;
  366. path.push_back(point);
  367. APPEND_METADATA(navigation_polys[np_id].poly);
  368. } else {
  369. path.push_back(navigation_polys[np_id].entry);
  370. APPEND_METADATA(navigation_polys[np_id].poly);
  371. }
  372. np_id = navigation_polys[np_id].back_navigation_poly_id;
  373. }
  374. path.push_back(begin_point);
  375. APPEND_METADATA(begin_poly);
  376. path.reverse();
  377. if (r_path_types) {
  378. r_path_types->reverse();
  379. }
  380. if (r_path_rids) {
  381. r_path_rids->reverse();
  382. }
  383. if (r_path_owners) {
  384. r_path_owners->reverse();
  385. }
  386. }
  387. // Ensure post conditions (path arrays MUST match in size).
  388. CRASH_COND(r_path_types && path.size() != r_path_types->size());
  389. CRASH_COND(r_path_rids && path.size() != r_path_rids->size());
  390. CRASH_COND(r_path_owners && path.size() != r_path_owners->size());
  391. return path;
  392. }
  393. Vector3 NavMap::get_closest_point_to_segment(const Vector3 &p_from, const Vector3 &p_to, const bool p_use_collision) const {
  394. bool use_collision = p_use_collision;
  395. Vector3 closest_point;
  396. real_t closest_point_d = 1e20;
  397. for (const gd::Polygon &p : polygons) {
  398. // For each face check the distance to the segment
  399. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  400. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  401. Vector3 inters;
  402. if (f.intersects_segment(p_from, p_to, &inters)) {
  403. const real_t d = closest_point_d = p_from.distance_to(inters);
  404. if (use_collision == false) {
  405. closest_point = inters;
  406. use_collision = true;
  407. closest_point_d = d;
  408. } else if (closest_point_d > d) {
  409. closest_point = inters;
  410. closest_point_d = d;
  411. }
  412. }
  413. }
  414. if (use_collision == false) {
  415. for (size_t point_id = 0; point_id < p.points.size(); point_id += 1) {
  416. Vector3 a, b;
  417. Geometry3D::get_closest_points_between_segments(
  418. p_from,
  419. p_to,
  420. p.points[point_id].pos,
  421. p.points[(point_id + 1) % p.points.size()].pos,
  422. a,
  423. b);
  424. const real_t d = a.distance_to(b);
  425. if (d < closest_point_d) {
  426. closest_point_d = d;
  427. closest_point = b;
  428. }
  429. }
  430. }
  431. }
  432. return closest_point;
  433. }
  434. Vector3 NavMap::get_closest_point(const Vector3 &p_point) const {
  435. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  436. return cp.point;
  437. }
  438. Vector3 NavMap::get_closest_point_normal(const Vector3 &p_point) const {
  439. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  440. return cp.normal;
  441. }
  442. RID NavMap::get_closest_point_owner(const Vector3 &p_point) const {
  443. gd::ClosestPointQueryResult cp = get_closest_point_info(p_point);
  444. return cp.owner;
  445. }
  446. gd::ClosestPointQueryResult NavMap::get_closest_point_info(const Vector3 &p_point) const {
  447. gd::ClosestPointQueryResult result;
  448. real_t closest_point_ds = 1e20;
  449. for (size_t i(0); i < polygons.size(); i++) {
  450. const gd::Polygon &p = polygons[i];
  451. // For each face check the distance to the point
  452. for (size_t point_id = 2; point_id < p.points.size(); point_id += 1) {
  453. const Face3 f(p.points[0].pos, p.points[point_id - 1].pos, p.points[point_id].pos);
  454. const Vector3 inters = f.get_closest_point_to(p_point);
  455. const real_t ds = inters.distance_squared_to(p_point);
  456. if (ds < closest_point_ds) {
  457. result.point = inters;
  458. result.normal = f.get_plane().normal;
  459. result.owner = p.owner->get_self();
  460. closest_point_ds = ds;
  461. }
  462. }
  463. }
  464. return result;
  465. }
  466. void NavMap::add_region(NavRegion *p_region) {
  467. regions.push_back(p_region);
  468. regenerate_links = true;
  469. }
  470. void NavMap::remove_region(NavRegion *p_region) {
  471. int64_t region_index = regions.find(p_region);
  472. if (region_index != -1) {
  473. regions.remove_at_unordered(region_index);
  474. regenerate_links = true;
  475. }
  476. }
  477. void NavMap::add_link(NavLink *p_link) {
  478. links.push_back(p_link);
  479. regenerate_links = true;
  480. }
  481. void NavMap::remove_link(NavLink *p_link) {
  482. int64_t link_index = links.find(p_link);
  483. if (link_index != -1) {
  484. links.remove_at_unordered(link_index);
  485. regenerate_links = true;
  486. }
  487. }
  488. bool NavMap::has_agent(NavAgent *agent) const {
  489. return (agents.find(agent) != -1);
  490. }
  491. void NavMap::add_agent(NavAgent *agent) {
  492. if (!has_agent(agent)) {
  493. agents.push_back(agent);
  494. agents_dirty = true;
  495. }
  496. }
  497. void NavMap::remove_agent(NavAgent *agent) {
  498. remove_agent_as_controlled(agent);
  499. int64_t agent_index = agents.find(agent);
  500. if (agent_index != -1) {
  501. agents.remove_at_unordered(agent_index);
  502. agents_dirty = true;
  503. }
  504. }
  505. void NavMap::set_agent_as_controlled(NavAgent *agent) {
  506. const bool exist = (controlled_agents.find(agent) != -1);
  507. if (!exist) {
  508. ERR_FAIL_COND(!has_agent(agent));
  509. controlled_agents.push_back(agent);
  510. }
  511. }
  512. void NavMap::remove_agent_as_controlled(NavAgent *agent) {
  513. int64_t active_avoidance_agent_index = controlled_agents.find(agent);
  514. if (active_avoidance_agent_index != -1) {
  515. controlled_agents.remove_at_unordered(active_avoidance_agent_index);
  516. agents_dirty = true;
  517. }
  518. }
  519. void NavMap::sync() {
  520. // Performance Monitor
  521. int _new_pm_region_count = regions.size();
  522. int _new_pm_agent_count = agents.size();
  523. int _new_pm_link_count = links.size();
  524. int _new_pm_polygon_count = pm_polygon_count;
  525. int _new_pm_edge_count = pm_edge_count;
  526. int _new_pm_edge_merge_count = pm_edge_merge_count;
  527. int _new_pm_edge_connection_count = pm_edge_connection_count;
  528. int _new_pm_edge_free_count = pm_edge_free_count;
  529. // Check if we need to update the links.
  530. if (regenerate_polygons) {
  531. for (NavRegion *region : regions) {
  532. region->scratch_polygons();
  533. }
  534. regenerate_links = true;
  535. }
  536. for (NavRegion *region : regions) {
  537. if (region->sync()) {
  538. regenerate_links = true;
  539. }
  540. }
  541. for (NavLink *link : links) {
  542. if (link->check_dirty()) {
  543. regenerate_links = true;
  544. }
  545. }
  546. if (regenerate_links) {
  547. _new_pm_polygon_count = 0;
  548. _new_pm_edge_count = 0;
  549. _new_pm_edge_merge_count = 0;
  550. _new_pm_edge_connection_count = 0;
  551. _new_pm_edge_free_count = 0;
  552. // Remove regions connections.
  553. for (NavRegion *region : regions) {
  554. region->get_connections().clear();
  555. }
  556. // Resize the polygon count.
  557. int count = 0;
  558. for (const NavRegion *region : regions) {
  559. count += region->get_polygons().size();
  560. }
  561. polygons.resize(count);
  562. // Copy all region polygons in the map.
  563. count = 0;
  564. for (const NavRegion *region : regions) {
  565. const LocalVector<gd::Polygon> &polygons_source = region->get_polygons();
  566. for (uint32_t n = 0; n < polygons_source.size(); n++) {
  567. polygons[count + n] = polygons_source[n];
  568. }
  569. count += region->get_polygons().size();
  570. }
  571. _new_pm_polygon_count = polygons.size();
  572. // Group all edges per key.
  573. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections;
  574. for (gd::Polygon &poly : polygons) {
  575. for (uint32_t p = 0; p < poly.points.size(); p++) {
  576. int next_point = (p + 1) % poly.points.size();
  577. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  578. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek);
  579. if (!connection) {
  580. connections[ek] = Vector<gd::Edge::Connection>();
  581. _new_pm_edge_count += 1;
  582. }
  583. if (connections[ek].size() <= 1) {
  584. // Add the polygon/edge tuple to this key.
  585. gd::Edge::Connection new_connection;
  586. new_connection.polygon = &poly;
  587. new_connection.edge = p;
  588. new_connection.pathway_start = poly.points[p].pos;
  589. new_connection.pathway_end = poly.points[next_point].pos;
  590. connections[ek].push_back(new_connection);
  591. } else {
  592. // The edge is already connected with another edge, skip.
  593. 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.");
  594. }
  595. }
  596. }
  597. Vector<gd::Edge::Connection> free_edges;
  598. for (KeyValue<gd::EdgeKey, Vector<gd::Edge::Connection>> &E : connections) {
  599. if (E.value.size() == 2) {
  600. // Connect edge that are shared in different polygons.
  601. gd::Edge::Connection &c1 = E.value.write[0];
  602. gd::Edge::Connection &c2 = E.value.write[1];
  603. c1.polygon->edges[c1.edge].connections.push_back(c2);
  604. c2.polygon->edges[c2.edge].connections.push_back(c1);
  605. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  606. _new_pm_edge_merge_count += 1;
  607. } else {
  608. CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size()));
  609. free_edges.push_back(E.value[0]);
  610. }
  611. }
  612. // Find the compatible near edges.
  613. //
  614. // Note:
  615. // Considering that the edges must be compatible (for obvious reasons)
  616. // to be connected, create new polygons to remove that small gap is
  617. // not really useful and would result in wasteful computation during
  618. // connection, integration and path finding.
  619. _new_pm_edge_free_count = free_edges.size();
  620. for (int i = 0; i < free_edges.size(); i++) {
  621. const gd::Edge::Connection &free_edge = free_edges[i];
  622. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  623. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  624. for (int j = 0; j < free_edges.size(); j++) {
  625. const gd::Edge::Connection &other_edge = free_edges[j];
  626. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  627. continue;
  628. }
  629. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  630. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  631. // Compute the projection of the opposite edge on the current one
  632. Vector3 edge_vector = edge_p2 - edge_p1;
  633. float projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  634. float projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  635. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  636. continue;
  637. }
  638. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  639. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  640. Vector3 other1;
  641. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  642. other1 = other_edge_p1;
  643. } else {
  644. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  645. }
  646. if (other1.distance_to(self1) > edge_connection_margin) {
  647. continue;
  648. }
  649. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  650. Vector3 other2;
  651. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  652. other2 = other_edge_p2;
  653. } else {
  654. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  655. }
  656. if (other2.distance_to(self2) > edge_connection_margin) {
  657. continue;
  658. }
  659. // The edges can now be connected.
  660. gd::Edge::Connection new_connection = other_edge;
  661. new_connection.pathway_start = (self1 + other1) / 2.0;
  662. new_connection.pathway_end = (self2 + other2) / 2.0;
  663. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  664. // Add the connection to the region_connection map.
  665. ((NavRegion *)free_edge.polygon->owner)->get_connections().push_back(new_connection);
  666. _new_pm_edge_connection_count += 1;
  667. }
  668. }
  669. uint32_t link_poly_idx = 0;
  670. link_polygons.resize(links.size());
  671. // Search for polygons within range of a nav link.
  672. for (const NavLink *link : links) {
  673. const Vector3 start = link->get_start_position();
  674. const Vector3 end = link->get_end_position();
  675. gd::Polygon *closest_start_polygon = nullptr;
  676. real_t closest_start_distance = link_connection_radius;
  677. Vector3 closest_start_point;
  678. gd::Polygon *closest_end_polygon = nullptr;
  679. real_t closest_end_distance = link_connection_radius;
  680. Vector3 closest_end_point;
  681. // Create link to any polygons within the search radius of the start point.
  682. for (uint32_t start_index = 0; start_index < polygons.size(); start_index++) {
  683. gd::Polygon &start_poly = polygons[start_index];
  684. // For each face check the distance to the start
  685. for (uint32_t start_point_id = 2; start_point_id < start_poly.points.size(); start_point_id += 1) {
  686. const Face3 start_face(start_poly.points[0].pos, start_poly.points[start_point_id - 1].pos, start_poly.points[start_point_id].pos);
  687. const Vector3 start_point = start_face.get_closest_point_to(start);
  688. const real_t start_distance = start_point.distance_to(start);
  689. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  690. if (start_distance <= link_connection_radius && start_distance < closest_start_distance) {
  691. closest_start_distance = start_distance;
  692. closest_start_point = start_point;
  693. closest_start_polygon = &start_poly;
  694. }
  695. }
  696. }
  697. // Find any polygons within the search radius of the end point.
  698. for (gd::Polygon &end_poly : polygons) {
  699. // For each face check the distance to the end
  700. for (uint32_t end_point_id = 2; end_point_id < end_poly.points.size(); end_point_id += 1) {
  701. const Face3 end_face(end_poly.points[0].pos, end_poly.points[end_point_id - 1].pos, end_poly.points[end_point_id].pos);
  702. const Vector3 end_point = end_face.get_closest_point_to(end);
  703. const real_t end_distance = end_point.distance_to(end);
  704. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  705. if (end_distance <= link_connection_radius && end_distance < closest_end_distance) {
  706. closest_end_distance = end_distance;
  707. closest_end_point = end_point;
  708. closest_end_polygon = &end_poly;
  709. }
  710. }
  711. }
  712. // If we have both a start and end point, then create a synthetic polygon to route through.
  713. if (closest_start_polygon && closest_end_polygon) {
  714. gd::Polygon &new_polygon = link_polygons[link_poly_idx++];
  715. new_polygon.owner = link;
  716. new_polygon.edges.clear();
  717. new_polygon.edges.resize(4);
  718. new_polygon.points.clear();
  719. new_polygon.points.reserve(4);
  720. // Build a set of vertices that create a thin polygon going from the start to the end point.
  721. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  722. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  723. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  724. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  725. Vector3 center;
  726. for (int p = 0; p < 4; ++p) {
  727. center += new_polygon.points[p].pos;
  728. }
  729. new_polygon.center = center / real_t(new_polygon.points.size());
  730. new_polygon.clockwise = true;
  731. // Setup connections to go forward in the link.
  732. {
  733. gd::Edge::Connection entry_connection;
  734. entry_connection.polygon = &new_polygon;
  735. entry_connection.edge = -1;
  736. entry_connection.pathway_start = new_polygon.points[0].pos;
  737. entry_connection.pathway_end = new_polygon.points[1].pos;
  738. closest_start_polygon->edges[0].connections.push_back(entry_connection);
  739. gd::Edge::Connection exit_connection;
  740. exit_connection.polygon = closest_end_polygon;
  741. exit_connection.edge = -1;
  742. exit_connection.pathway_start = new_polygon.points[2].pos;
  743. exit_connection.pathway_end = new_polygon.points[3].pos;
  744. new_polygon.edges[2].connections.push_back(exit_connection);
  745. }
  746. // If the link is bi-directional, create connections from the end to the start.
  747. if (link->is_bidirectional()) {
  748. gd::Edge::Connection entry_connection;
  749. entry_connection.polygon = &new_polygon;
  750. entry_connection.edge = -1;
  751. entry_connection.pathway_start = new_polygon.points[2].pos;
  752. entry_connection.pathway_end = new_polygon.points[3].pos;
  753. closest_end_polygon->edges[0].connections.push_back(entry_connection);
  754. gd::Edge::Connection exit_connection;
  755. exit_connection.polygon = closest_start_polygon;
  756. exit_connection.edge = -1;
  757. exit_connection.pathway_start = new_polygon.points[0].pos;
  758. exit_connection.pathway_end = new_polygon.points[1].pos;
  759. new_polygon.edges[0].connections.push_back(exit_connection);
  760. }
  761. }
  762. }
  763. // Update the update ID.
  764. map_update_id = (map_update_id + 1) % 9999999;
  765. }
  766. // Update agents tree.
  767. if (agents_dirty) {
  768. // cannot use LocalVector here as RVO library expects std::vector to build KdTree
  769. std::vector<RVO::Agent *> raw_agents;
  770. raw_agents.reserve(agents.size());
  771. for (NavAgent *agent : agents) {
  772. raw_agents.push_back(agent->get_agent());
  773. }
  774. rvo.buildAgentTree(raw_agents);
  775. }
  776. regenerate_polygons = false;
  777. regenerate_links = false;
  778. agents_dirty = false;
  779. // Performance Monitor
  780. pm_region_count = _new_pm_region_count;
  781. pm_agent_count = _new_pm_agent_count;
  782. pm_link_count = _new_pm_link_count;
  783. pm_polygon_count = _new_pm_polygon_count;
  784. pm_edge_count = _new_pm_edge_count;
  785. pm_edge_merge_count = _new_pm_edge_merge_count;
  786. pm_edge_connection_count = _new_pm_edge_connection_count;
  787. pm_edge_free_count = _new_pm_edge_free_count;
  788. }
  789. void NavMap::compute_single_step(uint32_t index, NavAgent **agent) {
  790. (*(agent + index))->get_agent()->computeNeighbors(&rvo);
  791. (*(agent + index))->get_agent()->computeNewVelocity(deltatime);
  792. }
  793. void NavMap::step(real_t p_deltatime) {
  794. deltatime = p_deltatime;
  795. if (controlled_agents.size() > 0) {
  796. 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"));
  797. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  798. }
  799. }
  800. void NavMap::dispatch_callbacks() {
  801. for (NavAgent *agent : controlled_agents) {
  802. agent->dispatch_callback();
  803. }
  804. }
  805. 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 {
  806. Vector3 from = path[path.size() - 1];
  807. if (from.is_equal_approx(p_to_point)) {
  808. return;
  809. }
  810. Plane cut_plane;
  811. cut_plane.normal = (from - p_to_point).cross(up);
  812. if (cut_plane.normal == Vector3()) {
  813. return;
  814. }
  815. cut_plane.normal.normalize();
  816. cut_plane.d = cut_plane.normal.dot(from);
  817. while (from_poly != p_to_poly) {
  818. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  819. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  820. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  821. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  822. if (!pathway_start.is_equal_approx(pathway_end)) {
  823. Vector3 inters;
  824. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  825. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) {
  826. path.push_back(inters);
  827. APPEND_METADATA(from_poly->poly);
  828. }
  829. }
  830. }
  831. }
  832. }
  833. NavMap::NavMap() {
  834. }
  835. NavMap::~NavMap() {
  836. }