nav_map.cpp 46 KB

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