nav_map.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. if (!region->get_enabled()) {
  705. continue;
  706. }
  707. count += region->get_polygons().size();
  708. }
  709. polygons.resize(count);
  710. // Copy all region polygons in the map.
  711. count = 0;
  712. for (const NavRegion *region : regions) {
  713. if (!region->get_enabled()) {
  714. continue;
  715. }
  716. const LocalVector<gd::Polygon> &polygons_source = region->get_polygons();
  717. for (uint32_t n = 0; n < polygons_source.size(); n++) {
  718. polygons[count + n] = polygons_source[n];
  719. }
  720. count += region->get_polygons().size();
  721. }
  722. _new_pm_polygon_count = polygons.size();
  723. // Group all edges per key.
  724. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey> connections;
  725. for (gd::Polygon &poly : polygons) {
  726. for (uint32_t p = 0; p < poly.points.size(); p++) {
  727. int next_point = (p + 1) % poly.points.size();
  728. gd::EdgeKey ek(poly.points[p].key, poly.points[next_point].key);
  729. HashMap<gd::EdgeKey, Vector<gd::Edge::Connection>, gd::EdgeKey>::Iterator connection = connections.find(ek);
  730. if (!connection) {
  731. connections[ek] = Vector<gd::Edge::Connection>();
  732. _new_pm_edge_count += 1;
  733. }
  734. if (connections[ek].size() <= 1) {
  735. // Add the polygon/edge tuple to this key.
  736. gd::Edge::Connection new_connection;
  737. new_connection.polygon = &poly;
  738. new_connection.edge = p;
  739. new_connection.pathway_start = poly.points[p].pos;
  740. new_connection.pathway_end = poly.points[next_point].pos;
  741. connections[ek].push_back(new_connection);
  742. } else {
  743. // The edge is already connected with another edge, skip.
  744. 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'.");
  745. }
  746. }
  747. }
  748. Vector<gd::Edge::Connection> free_edges;
  749. for (KeyValue<gd::EdgeKey, Vector<gd::Edge::Connection>> &E : connections) {
  750. if (E.value.size() == 2) {
  751. // Connect edge that are shared in different polygons.
  752. gd::Edge::Connection &c1 = E.value.write[0];
  753. gd::Edge::Connection &c2 = E.value.write[1];
  754. c1.polygon->edges[c1.edge].connections.push_back(c2);
  755. c2.polygon->edges[c2.edge].connections.push_back(c1);
  756. // Note: The pathway_start/end are full for those connection and do not need to be modified.
  757. _new_pm_edge_merge_count += 1;
  758. } else {
  759. CRASH_COND_MSG(E.value.size() != 1, vformat("Number of connection != 1. Found: %d", E.value.size()));
  760. if (use_edge_connections && E.value[0].polygon->owner->get_use_edge_connections()) {
  761. free_edges.push_back(E.value[0]);
  762. }
  763. }
  764. }
  765. // Find the compatible near edges.
  766. //
  767. // Note:
  768. // Considering that the edges must be compatible (for obvious reasons)
  769. // to be connected, create new polygons to remove that small gap is
  770. // not really useful and would result in wasteful computation during
  771. // connection, integration and path finding.
  772. _new_pm_edge_free_count = free_edges.size();
  773. for (int i = 0; i < free_edges.size(); i++) {
  774. const gd::Edge::Connection &free_edge = free_edges[i];
  775. Vector3 edge_p1 = free_edge.polygon->points[free_edge.edge].pos;
  776. Vector3 edge_p2 = free_edge.polygon->points[(free_edge.edge + 1) % free_edge.polygon->points.size()].pos;
  777. for (int j = 0; j < free_edges.size(); j++) {
  778. const gd::Edge::Connection &other_edge = free_edges[j];
  779. if (i == j || free_edge.polygon->owner == other_edge.polygon->owner) {
  780. continue;
  781. }
  782. Vector3 other_edge_p1 = other_edge.polygon->points[other_edge.edge].pos;
  783. Vector3 other_edge_p2 = other_edge.polygon->points[(other_edge.edge + 1) % other_edge.polygon->points.size()].pos;
  784. // Compute the projection of the opposite edge on the current one
  785. Vector3 edge_vector = edge_p2 - edge_p1;
  786. real_t projected_p1_ratio = edge_vector.dot(other_edge_p1 - edge_p1) / (edge_vector.length_squared());
  787. real_t projected_p2_ratio = edge_vector.dot(other_edge_p2 - edge_p1) / (edge_vector.length_squared());
  788. if ((projected_p1_ratio < 0.0 && projected_p2_ratio < 0.0) || (projected_p1_ratio > 1.0 && projected_p2_ratio > 1.0)) {
  789. continue;
  790. }
  791. // Check if the two edges are close to each other enough and compute a pathway between the two regions.
  792. Vector3 self1 = edge_vector * CLAMP(projected_p1_ratio, 0.0, 1.0) + edge_p1;
  793. Vector3 other1;
  794. if (projected_p1_ratio >= 0.0 && projected_p1_ratio <= 1.0) {
  795. other1 = other_edge_p1;
  796. } else {
  797. other1 = other_edge_p1.lerp(other_edge_p2, (1.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  798. }
  799. if (other1.distance_to(self1) > edge_connection_margin) {
  800. continue;
  801. }
  802. Vector3 self2 = edge_vector * CLAMP(projected_p2_ratio, 0.0, 1.0) + edge_p1;
  803. Vector3 other2;
  804. if (projected_p2_ratio >= 0.0 && projected_p2_ratio <= 1.0) {
  805. other2 = other_edge_p2;
  806. } else {
  807. other2 = other_edge_p1.lerp(other_edge_p2, (0.0 - projected_p1_ratio) / (projected_p2_ratio - projected_p1_ratio));
  808. }
  809. if (other2.distance_to(self2) > edge_connection_margin) {
  810. continue;
  811. }
  812. // The edges can now be connected.
  813. gd::Edge::Connection new_connection = other_edge;
  814. new_connection.pathway_start = (self1 + other1) / 2.0;
  815. new_connection.pathway_end = (self2 + other2) / 2.0;
  816. free_edge.polygon->edges[free_edge.edge].connections.push_back(new_connection);
  817. // Add the connection to the region_connection map.
  818. ((NavRegion *)free_edge.polygon->owner)->get_connections().push_back(new_connection);
  819. _new_pm_edge_connection_count += 1;
  820. }
  821. }
  822. uint32_t link_poly_idx = 0;
  823. link_polygons.resize(links.size());
  824. // Search for polygons within range of a nav link.
  825. for (const NavLink *link : links) {
  826. if (!link->get_enabled()) {
  827. continue;
  828. }
  829. const Vector3 start = link->get_start_position();
  830. const Vector3 end = link->get_end_position();
  831. gd::Polygon *closest_start_polygon = nullptr;
  832. real_t closest_start_distance = link_connection_radius;
  833. Vector3 closest_start_point;
  834. gd::Polygon *closest_end_polygon = nullptr;
  835. real_t closest_end_distance = link_connection_radius;
  836. Vector3 closest_end_point;
  837. // Create link to any polygons within the search radius of the start point.
  838. for (uint32_t start_index = 0; start_index < polygons.size(); start_index++) {
  839. gd::Polygon &start_poly = polygons[start_index];
  840. // For each face check the distance to the start
  841. for (uint32_t start_point_id = 2; start_point_id < start_poly.points.size(); start_point_id += 1) {
  842. const Face3 start_face(start_poly.points[0].pos, start_poly.points[start_point_id - 1].pos, start_poly.points[start_point_id].pos);
  843. const Vector3 start_point = start_face.get_closest_point_to(start);
  844. const real_t start_distance = start_point.distance_to(start);
  845. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  846. if (start_distance <= link_connection_radius && start_distance < closest_start_distance) {
  847. closest_start_distance = start_distance;
  848. closest_start_point = start_point;
  849. closest_start_polygon = &start_poly;
  850. }
  851. }
  852. }
  853. // Find any polygons within the search radius of the end point.
  854. for (gd::Polygon &end_poly : polygons) {
  855. // For each face check the distance to the end
  856. for (uint32_t end_point_id = 2; end_point_id < end_poly.points.size(); end_point_id += 1) {
  857. const Face3 end_face(end_poly.points[0].pos, end_poly.points[end_point_id - 1].pos, end_poly.points[end_point_id].pos);
  858. const Vector3 end_point = end_face.get_closest_point_to(end);
  859. const real_t end_distance = end_point.distance_to(end);
  860. // Pick the polygon that is within our radius and is closer than anything we've seen yet.
  861. if (end_distance <= link_connection_radius && end_distance < closest_end_distance) {
  862. closest_end_distance = end_distance;
  863. closest_end_point = end_point;
  864. closest_end_polygon = &end_poly;
  865. }
  866. }
  867. }
  868. // If we have both a start and end point, then create a synthetic polygon to route through.
  869. if (closest_start_polygon && closest_end_polygon) {
  870. gd::Polygon &new_polygon = link_polygons[link_poly_idx++];
  871. new_polygon.owner = link;
  872. new_polygon.edges.clear();
  873. new_polygon.edges.resize(4);
  874. new_polygon.points.clear();
  875. new_polygon.points.reserve(4);
  876. // Build a set of vertices that create a thin polygon going from the start to the end point.
  877. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  878. new_polygon.points.push_back({ closest_start_point, get_point_key(closest_start_point) });
  879. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  880. new_polygon.points.push_back({ closest_end_point, get_point_key(closest_end_point) });
  881. Vector3 center;
  882. for (int p = 0; p < 4; ++p) {
  883. center += new_polygon.points[p].pos;
  884. }
  885. new_polygon.center = center / real_t(new_polygon.points.size());
  886. new_polygon.clockwise = true;
  887. // Setup connections to go forward in the link.
  888. {
  889. gd::Edge::Connection entry_connection;
  890. entry_connection.polygon = &new_polygon;
  891. entry_connection.edge = -1;
  892. entry_connection.pathway_start = new_polygon.points[0].pos;
  893. entry_connection.pathway_end = new_polygon.points[1].pos;
  894. closest_start_polygon->edges[0].connections.push_back(entry_connection);
  895. gd::Edge::Connection exit_connection;
  896. exit_connection.polygon = closest_end_polygon;
  897. exit_connection.edge = -1;
  898. exit_connection.pathway_start = new_polygon.points[2].pos;
  899. exit_connection.pathway_end = new_polygon.points[3].pos;
  900. new_polygon.edges[2].connections.push_back(exit_connection);
  901. }
  902. // If the link is bi-directional, create connections from the end to the start.
  903. if (link->is_bidirectional()) {
  904. gd::Edge::Connection entry_connection;
  905. entry_connection.polygon = &new_polygon;
  906. entry_connection.edge = -1;
  907. entry_connection.pathway_start = new_polygon.points[2].pos;
  908. entry_connection.pathway_end = new_polygon.points[3].pos;
  909. closest_end_polygon->edges[0].connections.push_back(entry_connection);
  910. gd::Edge::Connection exit_connection;
  911. exit_connection.polygon = closest_start_polygon;
  912. exit_connection.edge = -1;
  913. exit_connection.pathway_start = new_polygon.points[0].pos;
  914. exit_connection.pathway_end = new_polygon.points[1].pos;
  915. new_polygon.edges[0].connections.push_back(exit_connection);
  916. }
  917. }
  918. }
  919. // Update the update ID.
  920. // Some code treats 0 as a failure case, so we avoid returning 0.
  921. map_update_id = map_update_id % 9999999 + 1;
  922. }
  923. // Do we have modified obstacle positions?
  924. for (NavObstacle *obstacle : obstacles) {
  925. if (obstacle->check_dirty()) {
  926. obstacles_dirty = true;
  927. }
  928. }
  929. // Do we have modified agent arrays?
  930. for (NavAgent *agent : agents) {
  931. if (agent->check_dirty()) {
  932. agents_dirty = true;
  933. }
  934. }
  935. // Update avoidance worlds.
  936. if (obstacles_dirty || agents_dirty) {
  937. _update_rvo_simulation();
  938. }
  939. regenerate_polygons = false;
  940. regenerate_links = false;
  941. obstacles_dirty = false;
  942. agents_dirty = false;
  943. // Performance Monitor.
  944. pm_region_count = _new_pm_region_count;
  945. pm_agent_count = _new_pm_agent_count;
  946. pm_link_count = _new_pm_link_count;
  947. pm_polygon_count = _new_pm_polygon_count;
  948. pm_edge_count = _new_pm_edge_count;
  949. pm_edge_merge_count = _new_pm_edge_merge_count;
  950. pm_edge_connection_count = _new_pm_edge_connection_count;
  951. pm_edge_free_count = _new_pm_edge_free_count;
  952. }
  953. void NavMap::_update_rvo_obstacles_tree_2d() {
  954. int obstacle_vertex_count = 0;
  955. for (NavObstacle *obstacle : obstacles) {
  956. obstacle_vertex_count += obstacle->get_vertices().size();
  957. }
  958. // Cleaning old obstacles.
  959. for (size_t i = 0; i < rvo_simulation_2d.obstacles_.size(); ++i) {
  960. delete rvo_simulation_2d.obstacles_[i];
  961. }
  962. rvo_simulation_2d.obstacles_.clear();
  963. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree
  964. std::vector<RVO2D::Obstacle2D *> &raw_obstacles = rvo_simulation_2d.obstacles_;
  965. raw_obstacles.reserve(obstacle_vertex_count);
  966. // The following block is modified copy from RVO2D::AddObstacle()
  967. // Obstacles are linked and depend on all other obstacles.
  968. for (NavObstacle *obstacle : obstacles) {
  969. const Vector3 &_obstacle_position = obstacle->get_position();
  970. const Vector<Vector3> &_obstacle_vertices = obstacle->get_vertices();
  971. if (_obstacle_vertices.size() < 2) {
  972. continue;
  973. }
  974. std::vector<RVO2D::Vector2> rvo_2d_vertices;
  975. rvo_2d_vertices.reserve(_obstacle_vertices.size());
  976. uint32_t _obstacle_avoidance_layers = obstacle->get_avoidance_layers();
  977. real_t _obstacle_height = obstacle->get_height();
  978. for (const Vector3 &_obstacle_vertex : _obstacle_vertices) {
  979. #ifdef TOOLS_ENABLED
  980. if (_obstacle_vertex.y != 0) {
  981. WARN_PRINT_ONCE("Y coordinates of static obstacle vertices are ignored. Please use obstacle position Y to change elevation of obstacle.");
  982. }
  983. #endif
  984. rvo_2d_vertices.push_back(RVO2D::Vector2(_obstacle_vertex.x + _obstacle_position.x, _obstacle_vertex.z + _obstacle_position.z));
  985. }
  986. const size_t obstacleNo = raw_obstacles.size();
  987. for (size_t i = 0; i < rvo_2d_vertices.size(); i++) {
  988. RVO2D::Obstacle2D *rvo_2d_obstacle = new RVO2D::Obstacle2D();
  989. rvo_2d_obstacle->point_ = rvo_2d_vertices[i];
  990. rvo_2d_obstacle->height_ = _obstacle_height;
  991. rvo_2d_obstacle->elevation_ = _obstacle_position.y;
  992. rvo_2d_obstacle->avoidance_layers_ = _obstacle_avoidance_layers;
  993. if (i != 0) {
  994. rvo_2d_obstacle->prevObstacle_ = raw_obstacles.back();
  995. rvo_2d_obstacle->prevObstacle_->nextObstacle_ = rvo_2d_obstacle;
  996. }
  997. if (i == rvo_2d_vertices.size() - 1) {
  998. rvo_2d_obstacle->nextObstacle_ = raw_obstacles[obstacleNo];
  999. rvo_2d_obstacle->nextObstacle_->prevObstacle_ = rvo_2d_obstacle;
  1000. }
  1001. rvo_2d_obstacle->unitDir_ = normalize(rvo_2d_vertices[(i == rvo_2d_vertices.size() - 1 ? 0 : i + 1)] - rvo_2d_vertices[i]);
  1002. if (rvo_2d_vertices.size() == 2) {
  1003. rvo_2d_obstacle->isConvex_ = true;
  1004. } else {
  1005. 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);
  1006. }
  1007. rvo_2d_obstacle->id_ = raw_obstacles.size();
  1008. raw_obstacles.push_back(rvo_2d_obstacle);
  1009. }
  1010. }
  1011. rvo_simulation_2d.kdTree_->buildObstacleTree(raw_obstacles);
  1012. }
  1013. void NavMap::_update_rvo_agents_tree_2d() {
  1014. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1015. std::vector<RVO2D::Agent2D *> raw_agents;
  1016. raw_agents.reserve(active_2d_avoidance_agents.size());
  1017. for (NavAgent *agent : active_2d_avoidance_agents) {
  1018. raw_agents.push_back(agent->get_rvo_agent_2d());
  1019. }
  1020. rvo_simulation_2d.kdTree_->buildAgentTree(raw_agents);
  1021. }
  1022. void NavMap::_update_rvo_agents_tree_3d() {
  1023. // Cannot use LocalVector here as RVO library expects std::vector to build KdTree.
  1024. std::vector<RVO3D::Agent3D *> raw_agents;
  1025. raw_agents.reserve(active_3d_avoidance_agents.size());
  1026. for (NavAgent *agent : active_3d_avoidance_agents) {
  1027. raw_agents.push_back(agent->get_rvo_agent_3d());
  1028. }
  1029. rvo_simulation_3d.kdTree_->buildAgentTree(raw_agents);
  1030. }
  1031. void NavMap::_update_rvo_simulation() {
  1032. if (obstacles_dirty) {
  1033. _update_rvo_obstacles_tree_2d();
  1034. }
  1035. if (agents_dirty) {
  1036. _update_rvo_agents_tree_2d();
  1037. _update_rvo_agents_tree_3d();
  1038. }
  1039. }
  1040. void NavMap::compute_single_avoidance_step_2d(uint32_t index, NavAgent **agent) {
  1041. (*(agent + index))->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1042. (*(agent + index))->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1043. (*(agent + index))->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1044. (*(agent + index))->update();
  1045. }
  1046. void NavMap::compute_single_avoidance_step_3d(uint32_t index, NavAgent **agent) {
  1047. (*(agent + index))->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1048. (*(agent + index))->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1049. (*(agent + index))->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1050. (*(agent + index))->update();
  1051. }
  1052. void NavMap::step(real_t p_deltatime) {
  1053. deltatime = p_deltatime;
  1054. rvo_simulation_2d.setTimeStep(float(deltatime));
  1055. rvo_simulation_3d.setTimeStep(float(deltatime));
  1056. if (active_2d_avoidance_agents.size() > 0) {
  1057. if (use_threads && avoidance_use_multiple_threads) {
  1058. 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"));
  1059. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1060. } else {
  1061. for (NavAgent *agent : active_2d_avoidance_agents) {
  1062. agent->get_rvo_agent_2d()->computeNeighbors(&rvo_simulation_2d);
  1063. agent->get_rvo_agent_2d()->computeNewVelocity(&rvo_simulation_2d);
  1064. agent->get_rvo_agent_2d()->update(&rvo_simulation_2d);
  1065. agent->update();
  1066. }
  1067. }
  1068. }
  1069. if (active_3d_avoidance_agents.size() > 0) {
  1070. if (use_threads && avoidance_use_multiple_threads) {
  1071. 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"));
  1072. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  1073. } else {
  1074. for (NavAgent *agent : active_3d_avoidance_agents) {
  1075. agent->get_rvo_agent_3d()->computeNeighbors(&rvo_simulation_3d);
  1076. agent->get_rvo_agent_3d()->computeNewVelocity(&rvo_simulation_3d);
  1077. agent->get_rvo_agent_3d()->update(&rvo_simulation_3d);
  1078. agent->update();
  1079. }
  1080. }
  1081. }
  1082. }
  1083. void NavMap::dispatch_callbacks() {
  1084. for (NavAgent *agent : active_2d_avoidance_agents) {
  1085. agent->dispatch_avoidance_callback();
  1086. }
  1087. for (NavAgent *agent : active_3d_avoidance_agents) {
  1088. agent->dispatch_avoidance_callback();
  1089. }
  1090. }
  1091. 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 {
  1092. Vector3 from = path[path.size() - 1];
  1093. if (from.is_equal_approx(p_to_point)) {
  1094. return;
  1095. }
  1096. Plane cut_plane;
  1097. cut_plane.normal = (from - p_to_point).cross(up);
  1098. if (cut_plane.normal == Vector3()) {
  1099. return;
  1100. }
  1101. cut_plane.normal.normalize();
  1102. cut_plane.d = cut_plane.normal.dot(from);
  1103. while (from_poly != p_to_poly) {
  1104. Vector3 pathway_start = from_poly->back_navigation_edge_pathway_start;
  1105. Vector3 pathway_end = from_poly->back_navigation_edge_pathway_end;
  1106. ERR_FAIL_COND(from_poly->back_navigation_poly_id == -1);
  1107. from_poly = &p_navigation_polys[from_poly->back_navigation_poly_id];
  1108. if (!pathway_start.is_equal_approx(pathway_end)) {
  1109. Vector3 inters;
  1110. if (cut_plane.intersects_segment(pathway_start, pathway_end, &inters)) {
  1111. if (!inters.is_equal_approx(p_to_point) && !inters.is_equal_approx(path[path.size() - 1])) {
  1112. path.push_back(inters);
  1113. APPEND_METADATA(from_poly->poly);
  1114. }
  1115. }
  1116. }
  1117. }
  1118. }
  1119. NavMap::NavMap() {
  1120. avoidance_use_multiple_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_multiple_threads");
  1121. avoidance_use_high_priority_threads = GLOBAL_GET("navigation/avoidance/thread_model/avoidance_use_high_priority_threads");
  1122. }
  1123. NavMap::~NavMap() {
  1124. }