navigation_mesh_generator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. Ref<Mesh> mesh = multimesh->get_mesh();
  146. if (mesh.is_valid()) {
  147. int n = multimesh->get_visible_instance_count();
  148. if (n == -1) {
  149. n = multimesh->get_instance_count();
  150. }
  151. for (int i = 0; i < n; i++) {
  152. _add_mesh(mesh, p_navmesh_transform * multimesh_instance->get_global_transform() * multimesh->get_instance_transform(i), p_vertices, p_indices);
  153. }
  154. }
  155. }
  156. #ifdef MODULE_CSG_ENABLED
  157. if (Object::cast_to<CSGShape3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  158. CSGShape3D *csg_shape = Object::cast_to<CSGShape3D>(p_node);
  159. Array meshes = csg_shape->get_meshes();
  160. if (!meshes.is_empty()) {
  161. Ref<Mesh> mesh = meshes[1];
  162. if (mesh.is_valid()) {
  163. _add_mesh(mesh, p_navmesh_transform * csg_shape->get_global_transform(), p_vertices, p_indices);
  164. }
  165. }
  166. }
  167. #endif
  168. if (Object::cast_to<StaticBody3D>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) {
  169. StaticBody3D *static_body = Object::cast_to<StaticBody3D>(p_node);
  170. if (static_body->get_collision_layer() & p_collision_mask) {
  171. List<uint32_t> shape_owners;
  172. static_body->get_shape_owners(&shape_owners);
  173. for (uint32_t shape_owner : shape_owners) {
  174. const int shape_count = static_body->shape_owner_get_shape_count(shape_owner);
  175. for (int i = 0; i < shape_count; i++) {
  176. Ref<Shape3D> s = static_body->shape_owner_get_shape(shape_owner, i);
  177. if (s.is_null()) {
  178. continue;
  179. }
  180. const Transform3D transform = p_navmesh_transform * static_body->get_global_transform() * static_body->shape_owner_get_transform(shape_owner);
  181. BoxShape3D *box = Object::cast_to<BoxShape3D>(*s);
  182. if (box) {
  183. Array arr;
  184. arr.resize(RS::ARRAY_MAX);
  185. BoxMesh::create_mesh_array(arr, box->get_size());
  186. _add_mesh_array(arr, transform, p_vertices, p_indices);
  187. }
  188. CapsuleShape3D *capsule = Object::cast_to<CapsuleShape3D>(*s);
  189. if (capsule) {
  190. Array arr;
  191. arr.resize(RS::ARRAY_MAX);
  192. CapsuleMesh::create_mesh_array(arr, capsule->get_radius(), capsule->get_height());
  193. _add_mesh_array(arr, transform, p_vertices, p_indices);
  194. }
  195. CylinderShape3D *cylinder = Object::cast_to<CylinderShape3D>(*s);
  196. if (cylinder) {
  197. Array arr;
  198. arr.resize(RS::ARRAY_MAX);
  199. CylinderMesh::create_mesh_array(arr, cylinder->get_radius(), cylinder->get_radius(), cylinder->get_height());
  200. _add_mesh_array(arr, transform, p_vertices, p_indices);
  201. }
  202. SphereShape3D *sphere = Object::cast_to<SphereShape3D>(*s);
  203. if (sphere) {
  204. Array arr;
  205. arr.resize(RS::ARRAY_MAX);
  206. SphereMesh::create_mesh_array(arr, sphere->get_radius(), sphere->get_radius() * 2.0);
  207. _add_mesh_array(arr, transform, p_vertices, p_indices);
  208. }
  209. ConcavePolygonShape3D *concave_polygon = Object::cast_to<ConcavePolygonShape3D>(*s);
  210. if (concave_polygon) {
  211. _add_faces(concave_polygon->get_faces(), transform, p_vertices, p_indices);
  212. }
  213. ConvexPolygonShape3D *convex_polygon = Object::cast_to<ConvexPolygonShape3D>(*s);
  214. if (convex_polygon) {
  215. Vector<Vector3> varr = Variant(convex_polygon->get_points());
  216. Geometry3D::MeshData md;
  217. Error err = ConvexHullComputer::convex_hull(varr, md);
  218. if (err == OK) {
  219. PackedVector3Array faces;
  220. for (int j = 0; j < md.faces.size(); ++j) {
  221. Geometry3D::MeshData::Face face = md.faces[j];
  222. for (int k = 2; k < face.indices.size(); ++k) {
  223. faces.push_back(md.vertices[face.indices[0]]);
  224. faces.push_back(md.vertices[face.indices[k - 1]]);
  225. faces.push_back(md.vertices[face.indices[k]]);
  226. }
  227. }
  228. _add_faces(faces, transform, p_vertices, p_indices);
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. #ifdef MODULE_GRIDMAP_ENABLED
  236. GridMap *gridmap = Object::cast_to<GridMap>(p_node);
  237. if (gridmap) {
  238. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  239. Array meshes = gridmap->get_meshes();
  240. Transform3D xform = gridmap->get_global_transform();
  241. for (int i = 0; i < meshes.size(); i += 2) {
  242. Ref<Mesh> mesh = meshes[i + 1];
  243. if (mesh.is_valid()) {
  244. _add_mesh(mesh, p_navmesh_transform * xform * (Transform3D)meshes[i], p_vertices, p_indices);
  245. }
  246. }
  247. }
  248. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES && (gridmap->get_collision_layer() & p_collision_mask)) {
  249. Array shapes = gridmap->get_collision_shapes();
  250. for (int i = 0; i < shapes.size(); i += 2) {
  251. RID shape = shapes[i + 1];
  252. PhysicsServer3D::ShapeType type = PhysicsServer3D::get_singleton()->shape_get_type(shape);
  253. Variant data = PhysicsServer3D::get_singleton()->shape_get_data(shape);
  254. switch (type) {
  255. case PhysicsServer3D::SHAPE_SPHERE: {
  256. real_t radius = data;
  257. Array arr;
  258. arr.resize(RS::ARRAY_MAX);
  259. SphereMesh::create_mesh_array(arr, radius, radius * 2.0);
  260. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  261. } break;
  262. case PhysicsServer3D::SHAPE_BOX: {
  263. Vector3 extents = data;
  264. Array arr;
  265. arr.resize(RS::ARRAY_MAX);
  266. BoxMesh::create_mesh_array(arr, extents * 2.0);
  267. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  268. } break;
  269. case PhysicsServer3D::SHAPE_CAPSULE: {
  270. Dictionary dict = data;
  271. real_t radius = dict["radius"];
  272. real_t height = dict["height"];
  273. Array arr;
  274. arr.resize(RS::ARRAY_MAX);
  275. CapsuleMesh::create_mesh_array(arr, radius, height);
  276. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  277. } break;
  278. case PhysicsServer3D::SHAPE_CYLINDER: {
  279. Dictionary dict = data;
  280. real_t radius = dict["radius"];
  281. real_t height = dict["height"];
  282. Array arr;
  283. arr.resize(RS::ARRAY_MAX);
  284. CylinderMesh::create_mesh_array(arr, radius, radius, height);
  285. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  286. } break;
  287. case PhysicsServer3D::SHAPE_CONVEX_POLYGON: {
  288. PackedVector3Array vertices = data;
  289. Geometry3D::MeshData md;
  290. Error err = ConvexHullComputer::convex_hull(vertices, md);
  291. if (err == OK) {
  292. PackedVector3Array faces;
  293. for (int j = 0; j < md.faces.size(); ++j) {
  294. Geometry3D::MeshData::Face face = md.faces[j];
  295. for (int k = 2; k < face.indices.size(); ++k) {
  296. faces.push_back(md.vertices[face.indices[0]]);
  297. faces.push_back(md.vertices[face.indices[k - 1]]);
  298. faces.push_back(md.vertices[face.indices[k]]);
  299. }
  300. }
  301. _add_faces(faces, shapes[i], p_vertices, p_indices);
  302. }
  303. } break;
  304. case PhysicsServer3D::SHAPE_CONCAVE_POLYGON: {
  305. Dictionary dict = data;
  306. PackedVector3Array faces = Variant(dict["faces"]);
  307. _add_faces(faces, shapes[i], p_vertices, p_indices);
  308. } break;
  309. default: {
  310. WARN_PRINT("Unsupported collision shape type.");
  311. } break;
  312. }
  313. }
  314. }
  315. }
  316. #endif
  317. if (p_recurse_children) {
  318. for (int i = 0; i < p_node->get_child_count(); i++) {
  319. _parse_geometry(p_navmesh_transform, p_node->get_child(i), p_vertices, p_indices, p_generate_from, p_collision_mask, p_recurse_children);
  320. }
  321. }
  322. }
  323. void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
  324. Vector<Vector3> nav_vertices;
  325. for (int i = 0; i < p_detail_mesh->nverts; i++) {
  326. const float *v = &p_detail_mesh->verts[i * 3];
  327. nav_vertices.push_back(Vector3(v[0], v[1], v[2]));
  328. }
  329. p_nav_mesh->set_vertices(nav_vertices);
  330. for (int i = 0; i < p_detail_mesh->nmeshes; i++) {
  331. const unsigned int *m = &p_detail_mesh->meshes[i * 4];
  332. const unsigned int bverts = m[0];
  333. const unsigned int btris = m[2];
  334. const unsigned int ntris = m[3];
  335. const unsigned char *tris = &p_detail_mesh->tris[btris * 4];
  336. for (unsigned int j = 0; j < ntris; j++) {
  337. Vector<int> nav_indices;
  338. nav_indices.resize(3);
  339. // Polygon order in recast is opposite than godot's
  340. nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0]));
  341. nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2]));
  342. nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1]));
  343. p_nav_mesh->add_polygon(nav_indices);
  344. }
  345. }
  346. }
  347. void NavigationMeshGenerator::_build_recast_navigation_mesh(
  348. Ref<NavigationMesh> p_nav_mesh,
  349. #ifdef TOOLS_ENABLED
  350. EditorProgress *ep,
  351. #endif
  352. rcHeightfield *hf,
  353. rcCompactHeightfield *chf,
  354. rcContourSet *cset,
  355. rcPolyMesh *poly_mesh,
  356. rcPolyMeshDetail *detail_mesh,
  357. Vector<float> &vertices,
  358. Vector<int> &indices) {
  359. rcContext ctx;
  360. #ifdef TOOLS_ENABLED
  361. if (ep) {
  362. ep->step(TTR("Setting up Configuration..."), 1);
  363. }
  364. #endif
  365. const float *verts = vertices.ptr();
  366. const int nverts = vertices.size() / 3;
  367. const int *tris = indices.ptr();
  368. const int ntris = indices.size() / 3;
  369. float bmin[3], bmax[3];
  370. rcCalcBounds(verts, nverts, bmin, bmax);
  371. rcConfig cfg;
  372. memset(&cfg, 0, sizeof(cfg));
  373. cfg.cs = p_nav_mesh->get_cell_size();
  374. cfg.ch = p_nav_mesh->get_cell_height();
  375. cfg.walkableSlopeAngle = p_nav_mesh->get_agent_max_slope();
  376. cfg.walkableHeight = (int)Math::ceil(p_nav_mesh->get_agent_height() / cfg.ch);
  377. cfg.walkableClimb = (int)Math::floor(p_nav_mesh->get_agent_max_climb() / cfg.ch);
  378. cfg.walkableRadius = (int)Math::ceil(p_nav_mesh->get_agent_radius() / cfg.cs);
  379. cfg.maxEdgeLen = (int)(p_nav_mesh->get_edge_max_length() / p_nav_mesh->get_cell_size());
  380. cfg.maxSimplificationError = p_nav_mesh->get_edge_max_error();
  381. cfg.minRegionArea = (int)(p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size());
  382. cfg.mergeRegionArea = (int)(p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size());
  383. cfg.maxVertsPerPoly = (int)p_nav_mesh->get_verts_per_poly();
  384. cfg.detailSampleDist = p_nav_mesh->get_detail_sample_distance() < 0.9f ? 0 : p_nav_mesh->get_cell_size() * p_nav_mesh->get_detail_sample_distance();
  385. cfg.detailSampleMaxError = p_nav_mesh->get_cell_height() * p_nav_mesh->get_detail_sample_max_error();
  386. cfg.bmin[0] = bmin[0];
  387. cfg.bmin[1] = bmin[1];
  388. cfg.bmin[2] = bmin[2];
  389. cfg.bmax[0] = bmax[0];
  390. cfg.bmax[1] = bmax[1];
  391. cfg.bmax[2] = bmax[2];
  392. #ifdef TOOLS_ENABLED
  393. if (ep) {
  394. ep->step(TTR("Calculating grid size..."), 2);
  395. }
  396. #endif
  397. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  398. #ifdef TOOLS_ENABLED
  399. if (ep) {
  400. ep->step(TTR("Creating heightfield..."), 3);
  401. }
  402. #endif
  403. hf = rcAllocHeightfield();
  404. ERR_FAIL_COND(!hf);
  405. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  406. #ifdef TOOLS_ENABLED
  407. if (ep) {
  408. ep->step(TTR("Marking walkable triangles..."), 4);
  409. }
  410. #endif
  411. {
  412. Vector<unsigned char> tri_areas;
  413. tri_areas.resize(ntris);
  414. ERR_FAIL_COND(tri_areas.size() == 0);
  415. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  416. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  417. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  418. }
  419. if (p_nav_mesh->get_filter_low_hanging_obstacles()) {
  420. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  421. }
  422. if (p_nav_mesh->get_filter_ledge_spans()) {
  423. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  424. }
  425. if (p_nav_mesh->get_filter_walkable_low_height_spans()) {
  426. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  427. }
  428. #ifdef TOOLS_ENABLED
  429. if (ep) {
  430. ep->step(TTR("Constructing compact heightfield..."), 5);
  431. }
  432. #endif
  433. chf = rcAllocCompactHeightfield();
  434. ERR_FAIL_COND(!chf);
  435. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  436. rcFreeHeightField(hf);
  437. hf = nullptr;
  438. #ifdef TOOLS_ENABLED
  439. if (ep) {
  440. ep->step(TTR("Eroding walkable area..."), 6);
  441. }
  442. #endif
  443. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  444. #ifdef TOOLS_ENABLED
  445. if (ep) {
  446. ep->step(TTR("Partitioning..."), 7);
  447. }
  448. #endif
  449. if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  450. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  451. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  452. } else if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  453. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  454. } else {
  455. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea));
  456. }
  457. #ifdef TOOLS_ENABLED
  458. if (ep) {
  459. ep->step(TTR("Creating contours..."), 8);
  460. }
  461. #endif
  462. cset = rcAllocContourSet();
  463. ERR_FAIL_COND(!cset);
  464. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  465. #ifdef TOOLS_ENABLED
  466. if (ep) {
  467. ep->step(TTR("Creating polymesh..."), 9);
  468. }
  469. #endif
  470. poly_mesh = rcAllocPolyMesh();
  471. ERR_FAIL_COND(!poly_mesh);
  472. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  473. detail_mesh = rcAllocPolyMeshDetail();
  474. ERR_FAIL_COND(!detail_mesh);
  475. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  476. rcFreeCompactHeightfield(chf);
  477. chf = nullptr;
  478. rcFreeContourSet(cset);
  479. cset = nullptr;
  480. #ifdef TOOLS_ENABLED
  481. if (ep) {
  482. ep->step(TTR("Converting to native navigation mesh..."), 10);
  483. }
  484. #endif
  485. _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
  486. rcFreePolyMesh(poly_mesh);
  487. poly_mesh = nullptr;
  488. rcFreePolyMeshDetail(detail_mesh);
  489. detail_mesh = nullptr;
  490. }
  491. NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() {
  492. return singleton;
  493. }
  494. NavigationMeshGenerator::NavigationMeshGenerator() {
  495. singleton = this;
  496. }
  497. NavigationMeshGenerator::~NavigationMeshGenerator() {
  498. }
  499. void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
  500. ERR_FAIL_COND_MSG(!p_nav_mesh.is_valid(), "Invalid navigation mesh.");
  501. #ifdef TOOLS_ENABLED
  502. EditorProgress *ep(nullptr);
  503. if (Engine::get_singleton()->is_editor_hint()) {
  504. ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11));
  505. }
  506. if (ep) {
  507. ep->step(TTR("Parsing Geometry..."), 0);
  508. }
  509. #endif
  510. Vector<float> vertices;
  511. Vector<int> indices;
  512. List<Node *> parse_nodes;
  513. if (p_nav_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
  514. parse_nodes.push_back(p_node);
  515. } else {
  516. p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes);
  517. }
  518. Transform3D navmesh_xform = Object::cast_to<Node3D>(p_node)->get_global_transform().affine_inverse();
  519. for (Node *E : parse_nodes) {
  520. NavigationMesh::ParsedGeometryType geometry_type = p_nav_mesh->get_parsed_geometry_type();
  521. uint32_t collision_mask = p_nav_mesh->get_collision_mask();
  522. bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  523. _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children);
  524. }
  525. if (vertices.size() > 0 && indices.size() > 0) {
  526. rcHeightfield *hf = nullptr;
  527. rcCompactHeightfield *chf = nullptr;
  528. rcContourSet *cset = nullptr;
  529. rcPolyMesh *poly_mesh = nullptr;
  530. rcPolyMeshDetail *detail_mesh = nullptr;
  531. _build_recast_navigation_mesh(
  532. p_nav_mesh,
  533. #ifdef TOOLS_ENABLED
  534. ep,
  535. #endif
  536. hf,
  537. chf,
  538. cset,
  539. poly_mesh,
  540. detail_mesh,
  541. vertices,
  542. indices);
  543. rcFreeHeightField(hf);
  544. hf = nullptr;
  545. rcFreeCompactHeightfield(chf);
  546. chf = nullptr;
  547. rcFreeContourSet(cset);
  548. cset = nullptr;
  549. rcFreePolyMesh(poly_mesh);
  550. poly_mesh = nullptr;
  551. rcFreePolyMeshDetail(detail_mesh);
  552. detail_mesh = nullptr;
  553. }
  554. #ifdef TOOLS_ENABLED
  555. if (ep) {
  556. ep->step(TTR("Done!"), 11);
  557. }
  558. if (ep) {
  559. memdelete(ep);
  560. }
  561. #endif
  562. }
  563. void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) {
  564. if (p_nav_mesh.is_valid()) {
  565. p_nav_mesh->clear_polygons();
  566. p_nav_mesh->set_vertices(Vector<Vector3>());
  567. }
  568. }
  569. void NavigationMeshGenerator::_bind_methods() {
  570. ClassDB::bind_method(D_METHOD("bake", "nav_mesh", "root_node"), &NavigationMeshGenerator::bake);
  571. ClassDB::bind_method(D_METHOD("clear", "nav_mesh"), &NavigationMeshGenerator::clear);
  572. }
  573. #endif