navigation_mesh_generator.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. /*************************************************************************/
  2. /* navigation_mesh_generator.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifndef _3D_DISABLED
  31. #include "navigation_mesh_generator.h"
  32. #include "core/math/convex_hull.h"
  33. #include "core/os/thread.h"
  34. #include "scene/3d/mesh_instance_3d.h"
  35. #include "scene/3d/multimesh_instance_3d.h"
  36. #include "scene/3d/physics_body_3d.h"
  37. #include "scene/resources/box_shape_3d.h"
  38. #include "scene/resources/capsule_shape_3d.h"
  39. #include "scene/resources/concave_polygon_shape_3d.h"
  40. #include "scene/resources/convex_polygon_shape_3d.h"
  41. #include "scene/resources/cylinder_shape_3d.h"
  42. #include "scene/resources/primitive_meshes.h"
  43. #include "scene/resources/shape_3d.h"
  44. #include "scene/resources/sphere_shape_3d.h"
  45. #include "scene/resources/world_boundary_shape_3d.h"
  46. #ifdef TOOLS_ENABLED
  47. #include "editor/editor_node.h"
  48. #endif
  49. #include "modules/modules_enabled.gen.h" // For csg, gridmap.
  50. #ifdef MODULE_CSG_ENABLED
  51. #include "modules/csg/csg_shape.h"
  52. #endif
  53. #ifdef MODULE_GRIDMAP_ENABLED
  54. #include "modules/gridmap/grid_map.h"
  55. #endif
  56. NavigationMeshGenerator *NavigationMeshGenerator::singleton = nullptr;
  57. void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_vertices) {
  58. p_vertices.push_back(p_vec3.x);
  59. p_vertices.push_back(p_vec3.y);
  60. p_vertices.push_back(p_vec3.z);
  61. }
  62. void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  63. int current_vertex_count;
  64. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  65. current_vertex_count = p_vertices.size() / 3;
  66. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  67. continue;
  68. }
  69. int index_count = 0;
  70. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  71. index_count = p_mesh->surface_get_array_index_len(i);
  72. } else {
  73. index_count = p_mesh->surface_get_array_len(i);
  74. }
  75. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  76. int face_count = index_count / 3;
  77. Array a = p_mesh->surface_get_arrays(i);
  78. Vector<Vector3> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  79. const Vector3 *vr = mesh_vertices.ptr();
  80. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  81. Vector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  82. const int *ir = mesh_indices.ptr();
  83. for (int j = 0; j < mesh_vertices.size(); j++) {
  84. _add_vertex(p_xform.xform(vr[j]), p_vertices);
  85. }
  86. for (int j = 0; j < face_count; j++) {
  87. // CCW
  88. p_indices.push_back(current_vertex_count + (ir[j * 3 + 0]));
  89. p_indices.push_back(current_vertex_count + (ir[j * 3 + 2]));
  90. p_indices.push_back(current_vertex_count + (ir[j * 3 + 1]));
  91. }
  92. } else {
  93. face_count = mesh_vertices.size() / 3;
  94. for (int j = 0; j < face_count; j++) {
  95. _add_vertex(p_xform.xform(vr[j * 3 + 0]), p_vertices);
  96. _add_vertex(p_xform.xform(vr[j * 3 + 2]), p_vertices);
  97. _add_vertex(p_xform.xform(vr[j * 3 + 1]), p_vertices);
  98. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  99. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  100. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  101. }
  102. }
  103. }
  104. }
  105. void NavigationMeshGenerator::_add_mesh_array(const Array &p_array, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  106. Vector<Vector3> mesh_vertices = p_array[Mesh::ARRAY_VERTEX];
  107. const Vector3 *vr = mesh_vertices.ptr();
  108. Vector<int> mesh_indices = p_array[Mesh::ARRAY_INDEX];
  109. const int *ir = mesh_indices.ptr();
  110. const int face_count = mesh_indices.size() / 3;
  111. const int current_vertex_count = p_vertices.size() / 3;
  112. for (int j = 0; j < mesh_vertices.size(); j++) {
  113. _add_vertex(p_xform.xform(vr[j]), p_vertices);
  114. }
  115. for (int j = 0; j < face_count; j++) {
  116. // CCW
  117. p_indices.push_back(current_vertex_count + (ir[j * 3 + 0]));
  118. p_indices.push_back(current_vertex_count + (ir[j * 3 + 2]));
  119. p_indices.push_back(current_vertex_count + (ir[j * 3 + 1]));
  120. }
  121. }
  122. void NavigationMeshGenerator::_add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  123. int face_count = p_faces.size() / 3;
  124. int current_vertex_count = p_vertices.size() / 3;
  125. for (int j = 0; j < face_count; j++) {
  126. _add_vertex(p_xform.xform(p_faces[j * 3 + 0]), p_vertices);
  127. _add_vertex(p_xform.xform(p_faces[j * 3 + 1]), p_vertices);
  128. _add_vertex(p_xform.xform(p_faces[j * 3 + 2]), p_vertices);
  129. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  130. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  131. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  132. }
  133. }
  134. void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_transform, Node *p_node, Vector<float> &p_vertices, Vector<int> &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) {
  135. if (Object::cast_to<MeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  136. MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(p_node);
  137. Ref<Mesh> mesh = mesh_instance->get_mesh();
  138. if (mesh.is_valid()) {
  139. _add_mesh(mesh, p_navmesh_transform * mesh_instance->get_global_transform(), p_vertices, p_indices);
  140. }
  141. }
  142. if (Object::cast_to<MultiMeshInstance3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  143. MultiMeshInstance3D *multimesh_instance = Object::cast_to<MultiMeshInstance3D>(p_node);
  144. Ref<MultiMesh> multimesh = multimesh_instance->get_multimesh();
  145. if (multimesh.is_valid()) {
  146. Ref<Mesh> mesh = multimesh->get_mesh();
  147. if (mesh.is_valid()) {
  148. int n = multimesh->get_visible_instance_count();
  149. if (n == -1) {
  150. n = multimesh->get_instance_count();
  151. }
  152. for (int i = 0; i < n; i++) {
  153. _add_mesh(mesh, p_navmesh_transform * multimesh_instance->get_global_transform() * multimesh->get_instance_transform(i), p_vertices, p_indices);
  154. }
  155. }
  156. }
  157. }
  158. #ifdef MODULE_CSG_ENABLED
  159. if (Object::cast_to<CSGShape3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  160. CSGShape3D *csg_shape = Object::cast_to<CSGShape3D>(p_node);
  161. Array meshes = csg_shape->get_meshes();
  162. if (!meshes.is_empty()) {
  163. Ref<Mesh> mesh = meshes[1];
  164. if (mesh.is_valid()) {
  165. _add_mesh(mesh, p_navmesh_transform * csg_shape->get_global_transform(), p_vertices, p_indices);
  166. }
  167. }
  168. }
  169. #endif
  170. if (Object::cast_to<StaticBody3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) {
  171. StaticBody3D *static_body = Object::cast_to<StaticBody3D>(p_node);
  172. if (static_body->get_collision_layer() & p_collision_mask) {
  173. List<uint32_t> shape_owners;
  174. static_body->get_shape_owners(&shape_owners);
  175. for (uint32_t shape_owner : shape_owners) {
  176. const int shape_count = static_body->shape_owner_get_shape_count(shape_owner);
  177. for (int i = 0; i < shape_count; i++) {
  178. Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, i);
  179. if (s.is_null()) {
  180. continue;
  181. }
  182. const Transform3D transform = p_navmesh_transform * static_body->get_global_transform() * static_body->shape_owner_get_transform(shape_owner);
  183. BoxShape3D *box = Object::cast_to<BoxShape3D>(*s);
  184. if (box) {
  185. Array arr;
  186. arr.resize(RS::ARRAY_MAX);
  187. BoxMesh::create_mesh_array(arr, box->get_size());
  188. _add_mesh_array(arr, transform, p_vertices, p_indices);
  189. }
  190. CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s);
  191. if (capsule) {
  192. Array arr;
  193. arr.resize(RS::ARRAY_MAX);
  194. CapsuleMesh::create_mesh_array(arr, capsule->get_radius(), capsule->get_height());
  195. _add_mesh_array(arr, transform, p_vertices, p_indices);
  196. }
  197. CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s);
  198. if (cylinder) {
  199. Array arr;
  200. arr.resize(RS::ARRAY_MAX);
  201. CylinderMesh::create_mesh_array(arr, cylinder->get_radius(), cylinder->get_radius(), cylinder->get_height());
  202. _add_mesh_array(arr, transform, p_vertices, p_indices);
  203. }
  204. SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s);
  205. if (sphere) {
  206. Array arr;
  207. arr.resize(RS::ARRAY_MAX);
  208. SphereMesh::create_mesh_array(arr, sphere->get_radius(), sphere->get_radius() * 2.0);
  209. _add_mesh_array(arr, transform, p_vertices, p_indices);
  210. }
  211. ConcavePolygonShape3D *concave_polygon = Object::cast_to<ConcavePolygonShape3D>(*s);
  212. if (concave_polygon) {
  213. _add_faces(concave_polygon->get_faces(), transform, p_vertices, p_indices);
  214. }
  215. ConvexPolygonShape3D *convex_polygon = Object::cast_to<ConvexPolygonShape3D>(*s);
  216. if (convex_polygon) {
  217. Vector<Vector3> varr = Variant(convex_polygon->get_points());
  218. Geometry3D::MeshData md;
  219. Error err = ConvexHullComputer::convex_hull(varr, md);
  220. if (err == OK) {
  221. PackedVector3Array faces;
  222. for (int j = 0; j < md.faces.size(); ++j) {
  223. Geometry3D::MeshData::Face face = md.faces[j];
  224. for (int k = 2; k < face.indices.size(); ++k) {
  225. faces.push_back(md.vertices[face.indices[0]]);
  226. faces.push_back(md.vertices[face.indices[k - 1]]);
  227. faces.push_back(md.vertices[face.indices[k]]);
  228. }
  229. }
  230. _add_faces(faces, transform, p_vertices, p_indices);
  231. }
  232. }
  233. }
  234. }
  235. }
  236. }
  237. #ifdef MODULE_GRIDMAP_ENABLED
  238. GridMap *gridmap = Object::cast_to<GridMap>(p_node);
  239. if (gridmap) {
  240. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  241. Array meshes = gridmap->get_meshes();
  242. Transform3D xform = gridmap->get_global_transform();
  243. for (int i = 0; i < meshes.size(); i += 2) {
  244. Ref<Mesh> mesh = meshes[i + 1];
  245. if (mesh.is_valid()) {
  246. _add_mesh(mesh, p_navmesh_transform * xform * (Transform3D)meshes[i], p_vertices, p_indices);
  247. }
  248. }
  249. }
  250. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES && (gridmap->get_collision_layer() & p_collision_mask)) {
  251. Array shapes = gridmap->get_collision_shapes();
  252. for (int i = 0; i < shapes.size(); i += 2) {
  253. RID shape = shapes[i + 1];
  254. PhysicsServer3D::ShapeType type = PhysicsServer3D::get_singleton()->shape_get_type(shape);
  255. Variant data = PhysicsServer3D::get_singleton()->shape_get_data(shape);
  256. switch (type) {
  257. case PhysicsServer3D::SHAPE_SPHERE: {
  258. real_t radius = data;
  259. Array arr;
  260. arr.resize(RS::ARRAY_MAX);
  261. SphereMesh::create_mesh_array(arr, radius, radius * 2.0);
  262. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  263. } break;
  264. case PhysicsServer3D::SHAPE_BOX: {
  265. Vector3 extents = data;
  266. Array arr;
  267. arr.resize(RS::ARRAY_MAX);
  268. BoxMesh::create_mesh_array(arr, extents * 2.0);
  269. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  270. } break;
  271. case PhysicsServer3D::SHAPE_CAPSULE: {
  272. Dictionary dict = data;
  273. real_t radius = dict["radius"];
  274. real_t height = dict["height"];
  275. Array arr;
  276. arr.resize(RS::ARRAY_MAX);
  277. CapsuleMesh::create_mesh_array(arr, radius, height);
  278. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  279. } break;
  280. case PhysicsServer3D::SHAPE_CYLINDER: {
  281. Dictionary dict = data;
  282. real_t radius = dict["radius"];
  283. real_t height = dict["height"];
  284. Array arr;
  285. arr.resize(RS::ARRAY_MAX);
  286. CylinderMesh::create_mesh_array(arr, radius, radius, height);
  287. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  288. } break;
  289. case PhysicsServer3D::SHAPE_CONVEX_POLYGON: {
  290. PackedVector3Array vertices = data;
  291. Geometry3D::MeshData md;
  292. Error err = ConvexHullComputer::convex_hull(vertices, md);
  293. if (err == OK) {
  294. PackedVector3Array faces;
  295. for (int j = 0; j < md.faces.size(); ++j) {
  296. Geometry3D::MeshData::Face face = md.faces[j];
  297. for (int k = 2; k < face.indices.size(); ++k) {
  298. faces.push_back(md.vertices[face.indices[0]]);
  299. faces.push_back(md.vertices[face.indices[k - 1]]);
  300. faces.push_back(md.vertices[face.indices[k]]);
  301. }
  302. }
  303. _add_faces(faces, shapes[i], p_vertices, p_indices);
  304. }
  305. } break;
  306. case PhysicsServer3D::SHAPE_CONCAVE_POLYGON: {
  307. Dictionary dict = data;
  308. PackedVector3Array faces = Variant(dict["faces"]);
  309. _add_faces(faces, shapes[i], p_vertices, p_indices);
  310. } break;
  311. default: {
  312. WARN_PRINT("Unsupported collision shape type.");
  313. } break;
  314. }
  315. }
  316. }
  317. }
  318. #endif
  319. if (p_recurse_children) {
  320. for (int i = 0; i < p_node->get_child_count(); i++) {
  321. _parse_geometry(p_navmesh_transform, p_node->get_child(i), p_vertices, p_indices, p_generate_from, p_collision_mask, p_recurse_children);
  322. }
  323. }
  324. }
  325. void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
  326. Vector<Vector3> nav_vertices;
  327. for (int i = 0; i < p_detail_mesh->nverts; i++) {
  328. const float *v = &p_detail_mesh->verts[i * 3];
  329. nav_vertices.push_back(Vector3(v[0], v[1], v[2]));
  330. }
  331. p_nav_mesh->set_vertices(nav_vertices);
  332. for (int i = 0; i < p_detail_mesh->nmeshes; i++) {
  333. const unsigned int *m = &p_detail_mesh->meshes[i * 4];
  334. const unsigned int bverts = m[0];
  335. const unsigned int btris = m[2];
  336. const unsigned int ntris = m[3];
  337. const unsigned char *tris = &p_detail_mesh->tris[btris * 4];
  338. for (unsigned int j = 0; j < ntris; j++) {
  339. Vector<int> nav_indices;
  340. nav_indices.resize(3);
  341. // Polygon order in recast is opposite than godot's
  342. nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0]));
  343. nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2]));
  344. nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1]));
  345. p_nav_mesh->add_polygon(nav_indices);
  346. }
  347. }
  348. }
  349. void NavigationMeshGenerator::_build_recast_navigation_mesh(
  350. Ref<NavigationMesh> p_nav_mesh,
  351. #ifdef TOOLS_ENABLED
  352. EditorProgress *ep,
  353. #endif
  354. rcHeightfield *hf,
  355. rcCompactHeightfield *chf,
  356. rcContourSet *cset,
  357. rcPolyMesh *poly_mesh,
  358. rcPolyMeshDetail *detail_mesh,
  359. Vector<float> &vertices,
  360. Vector<int> &indices) {
  361. rcContext ctx;
  362. #ifdef TOOLS_ENABLED
  363. if (ep) {
  364. ep->step(TTR("Setting up Configuration..."), 1);
  365. }
  366. #endif
  367. const float *verts = vertices.ptr();
  368. const int nverts = vertices.size() / 3;
  369. const int *tris = indices.ptr();
  370. const int ntris = indices.size() / 3;
  371. float bmin[3], bmax[3];
  372. rcCalcBounds(verts, nverts, bmin, bmax);
  373. rcConfig cfg;
  374. memset(&cfg, 0, sizeof(cfg));
  375. cfg.cs = p_nav_mesh->get_cell_size();
  376. cfg.ch = p_nav_mesh->get_cell_height();
  377. cfg.walkableSlopeAngle = p_nav_mesh->get_agent_max_slope();
  378. cfg.walkableHeight = (int)Math::ceil(p_nav_mesh->get_agent_height() / cfg.ch);
  379. cfg.walkableClimb = (int)Math::floor(p_nav_mesh->get_agent_max_climb() / cfg.ch);
  380. cfg.walkableRadius = (int)Math::ceil(p_nav_mesh->get_agent_radius() / cfg.cs);
  381. cfg.maxEdgeLen = (int)(p_nav_mesh->get_edge_max_length() / p_nav_mesh->get_cell_size());
  382. cfg.maxSimplificationError = p_nav_mesh->get_edge_max_error();
  383. cfg.minRegionArea = (int)(p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size());
  384. cfg.mergeRegionArea = (int)(p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size());
  385. cfg.maxVertsPerPoly = (int)p_nav_mesh->get_verts_per_poly();
  386. cfg.detailSampleDist = MAX(p_nav_mesh->get_cell_size() * p_nav_mesh->get_detail_sample_distance(), 0.1f);
  387. cfg.detailSampleMaxError = p_nav_mesh->get_cell_height() * p_nav_mesh->get_detail_sample_max_error();
  388. if (!Math::is_equal_approx((float)cfg.walkableHeight * cfg.ch, p_nav_mesh->get_agent_height())) {
  389. WARN_PRINT("Property agent_height is ceiled to cell_height voxel units and loses precision.");
  390. }
  391. if (!Math::is_equal_approx((float)cfg.walkableClimb * cfg.ch, p_nav_mesh->get_agent_max_climb())) {
  392. WARN_PRINT("Property agent_max_climb is floored to cell_height voxel units and loses precision.");
  393. }
  394. if (!Math::is_equal_approx((float)cfg.walkableRadius * cfg.cs, p_nav_mesh->get_agent_radius())) {
  395. WARN_PRINT("Property agent_radius is ceiled to cell_size voxel units and loses precision.");
  396. }
  397. if (!Math::is_equal_approx((float)cfg.maxEdgeLen * cfg.cs, p_nav_mesh->get_edge_max_length())) {
  398. WARN_PRINT("Property edge_max_length is rounded to cell_size voxel units and loses precision.");
  399. }
  400. if (!Math::is_equal_approx((float)cfg.minRegionArea, p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size())) {
  401. WARN_PRINT("Property region_min_size is converted to int and loses precision.");
  402. }
  403. if (!Math::is_equal_approx((float)cfg.mergeRegionArea, p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size())) {
  404. WARN_PRINT("Property region_merge_size is converted to int and loses precision.");
  405. }
  406. if (!Math::is_equal_approx((float)cfg.maxVertsPerPoly, p_nav_mesh->get_verts_per_poly())) {
  407. WARN_PRINT("Property verts_per_poly is converted to int and loses precision.");
  408. }
  409. if (p_nav_mesh->get_cell_size() * p_nav_mesh->get_detail_sample_distance() < 0.1f) {
  410. WARN_PRINT("Property detail_sample_distance is clamped to 0.1 world units as the resulting value from multiplying with cell_size is too low.");
  411. }
  412. cfg.bmin[0] = bmin[0];
  413. cfg.bmin[1] = bmin[1];
  414. cfg.bmin[2] = bmin[2];
  415. cfg.bmax[0] = bmax[0];
  416. cfg.bmax[1] = bmax[1];
  417. cfg.bmax[2] = bmax[2];
  418. #ifdef TOOLS_ENABLED
  419. if (ep) {
  420. ep->step(TTR("Calculating grid size..."), 2);
  421. }
  422. #endif
  423. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  424. // ~30000000 seems to be around sweetspot where Editor baking breaks
  425. if ((cfg.width * cfg.height) > 30000000) {
  426. WARN_PRINT("NavigationMesh baking process will likely fail."
  427. "\nSource geometry is suspiciously big for the current Cell Size and Cell Height in the NavMesh Resource bake settings."
  428. "\nIf baking does not fail, the resulting NavigationMesh will create serious pathfinding performance issues."
  429. "\nIt is advised to increase Cell Size and/or Cell Height in the NavMesh Resource bake settings or reduce the size / scale of the source geometry.");
  430. }
  431. #ifdef TOOLS_ENABLED
  432. if (ep) {
  433. ep->step(TTR("Creating heightfield..."), 3);
  434. }
  435. #endif
  436. hf = rcAllocHeightfield();
  437. ERR_FAIL_COND(!hf);
  438. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  439. #ifdef TOOLS_ENABLED
  440. if (ep) {
  441. ep->step(TTR("Marking walkable triangles..."), 4);
  442. }
  443. #endif
  444. {
  445. Vector<unsigned char> tri_areas;
  446. tri_areas.resize(ntris);
  447. ERR_FAIL_COND(tri_areas.size() == 0);
  448. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  449. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  450. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  451. }
  452. if (p_nav_mesh->get_filter_low_hanging_obstacles()) {
  453. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  454. }
  455. if (p_nav_mesh->get_filter_ledge_spans()) {
  456. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  457. }
  458. if (p_nav_mesh->get_filter_walkable_low_height_spans()) {
  459. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  460. }
  461. #ifdef TOOLS_ENABLED
  462. if (ep) {
  463. ep->step(TTR("Constructing compact heightfield..."), 5);
  464. }
  465. #endif
  466. chf = rcAllocCompactHeightfield();
  467. ERR_FAIL_COND(!chf);
  468. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  469. rcFreeHeightField(hf);
  470. hf = nullptr;
  471. #ifdef TOOLS_ENABLED
  472. if (ep) {
  473. ep->step(TTR("Eroding walkable area..."), 6);
  474. }
  475. #endif
  476. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  477. #ifdef TOOLS_ENABLED
  478. if (ep) {
  479. ep->step(TTR("Partitioning..."), 7);
  480. }
  481. #endif
  482. if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  483. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  484. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  485. } else if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  486. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  487. } else {
  488. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea));
  489. }
  490. #ifdef TOOLS_ENABLED
  491. if (ep) {
  492. ep->step(TTR("Creating contours..."), 8);
  493. }
  494. #endif
  495. cset = rcAllocContourSet();
  496. ERR_FAIL_COND(!cset);
  497. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  498. #ifdef TOOLS_ENABLED
  499. if (ep) {
  500. ep->step(TTR("Creating polymesh..."), 9);
  501. }
  502. #endif
  503. poly_mesh = rcAllocPolyMesh();
  504. ERR_FAIL_COND(!poly_mesh);
  505. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  506. detail_mesh = rcAllocPolyMeshDetail();
  507. ERR_FAIL_COND(!detail_mesh);
  508. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  509. rcFreeCompactHeightfield(chf);
  510. chf = nullptr;
  511. rcFreeContourSet(cset);
  512. cset = nullptr;
  513. #ifdef TOOLS_ENABLED
  514. if (ep) {
  515. ep->step(TTR("Converting to native navigation mesh..."), 10);
  516. }
  517. #endif
  518. _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
  519. rcFreePolyMesh(poly_mesh);
  520. poly_mesh = nullptr;
  521. rcFreePolyMeshDetail(detail_mesh);
  522. detail_mesh = nullptr;
  523. }
  524. NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() {
  525. return singleton;
  526. }
  527. NavigationMeshGenerator::NavigationMeshGenerator() {
  528. singleton = this;
  529. }
  530. NavigationMeshGenerator::~NavigationMeshGenerator() {
  531. }
  532. void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
  533. ERR_FAIL_COND_MSG(!p_nav_mesh.is_valid(), "Invalid navigation mesh.");
  534. #ifdef TOOLS_ENABLED
  535. EditorProgress *ep(nullptr);
  536. // FIXME
  537. #endif
  538. #if 0
  539. // After discussion on devchat disabled EditorProgress for now as it is not thread-safe and uses hacks and Main::iteration() for steps.
  540. // EditorProgress randomly crashes the Engine when the bake function is used with a thread e.g. inside Editor with a tool script and procedural navigation
  541. // This was not a problem in older versions as previously Godot was unable to (re)bake NavigationMesh at runtime.
  542. // If EditorProgress is fixed and made thread-safe this should be enabled again.
  543. if (Engine::get_singleton()->is_editor_hint()) {
  544. ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11));
  545. }
  546. if (ep) {
  547. ep->step(TTR("Parsing Geometry..."), 0);
  548. }
  549. #endif
  550. Vector<float> vertices;
  551. Vector<int> indices;
  552. List<Node *> parse_nodes;
  553. if (p_nav_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
  554. parse_nodes.push_back(p_node);
  555. } else {
  556. p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes);
  557. }
  558. Transform3D navmesh_xform = Object::cast_to<Node3D>(p_node)->get_global_transform().affine_inverse();
  559. for (Node *E : parse_nodes) {
  560. NavigationMesh::ParsedGeometryType geometry_type = p_nav_mesh->get_parsed_geometry_type();
  561. uint32_t collision_mask = p_nav_mesh->get_collision_mask();
  562. bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  563. _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children);
  564. }
  565. if (vertices.size() > 0 && indices.size() > 0) {
  566. rcHeightfield *hf = nullptr;
  567. rcCompactHeightfield *chf = nullptr;
  568. rcContourSet *cset = nullptr;
  569. rcPolyMesh *poly_mesh = nullptr;
  570. rcPolyMeshDetail *detail_mesh = nullptr;
  571. _build_recast_navigation_mesh(
  572. p_nav_mesh,
  573. #ifdef TOOLS_ENABLED
  574. ep,
  575. #endif
  576. hf,
  577. chf,
  578. cset,
  579. poly_mesh,
  580. detail_mesh,
  581. vertices,
  582. indices);
  583. rcFreeHeightField(hf);
  584. hf = nullptr;
  585. rcFreeCompactHeightfield(chf);
  586. chf = nullptr;
  587. rcFreeContourSet(cset);
  588. cset = nullptr;
  589. rcFreePolyMesh(poly_mesh);
  590. poly_mesh = nullptr;
  591. rcFreePolyMeshDetail(detail_mesh);
  592. detail_mesh = nullptr;
  593. }
  594. #ifdef TOOLS_ENABLED
  595. if (ep) {
  596. ep->step(TTR("Done!"), 11);
  597. }
  598. if (ep) {
  599. memdelete(ep);
  600. }
  601. #endif
  602. }
  603. void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) {
  604. if (p_nav_mesh.is_valid()) {
  605. p_nav_mesh->clear_polygons();
  606. p_nav_mesh->set_vertices(Vector<Vector3>());
  607. }
  608. }
  609. void NavigationMeshGenerator::_bind_methods() {
  610. ClassDB::bind_method(D_METHOD("bake", "nav_mesh", "root_node"), &NavigationMeshGenerator::bake);
  611. ClassDB::bind_method(D_METHOD("clear", "nav_mesh"), &NavigationMeshGenerator::clear);
  612. }
  613. #endif