navigation_mesh_generator.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /**************************************************************************/
  2. /* navigation_mesh_generator.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 "core/math/convex_hull.h"
  31. #ifndef _3D_DISABLED
  32. #include "navigation_mesh_generator.h"
  33. //#include "core/math/quick_hull.h"
  34. //#include "core/math/convex_hull.h"
  35. #include "core/os/thread.h"
  36. #include "scene/3d/mesh_instance.h"
  37. #include "scene/3d/multimesh_instance.h"
  38. #include "scene/3d/physics_body.h"
  39. #include "scene/resources/box_shape.h"
  40. #include "scene/resources/capsule_shape.h"
  41. #include "scene/resources/concave_polygon_shape.h"
  42. #include "scene/resources/convex_polygon_shape.h"
  43. #include "scene/resources/cylinder_shape.h"
  44. #include "scene/resources/plane_shape.h"
  45. #include "scene/resources/primitive_meshes.h"
  46. #include "scene/resources/shape.h"
  47. #include "scene/resources/sphere_shape.h"
  48. #include "modules/modules_enabled.gen.h" // For csg, gridmap.
  49. #ifdef TOOLS_ENABLED
  50. #include "editor/editor_node.h"
  51. #include "editor/editor_settings.h"
  52. #endif
  53. #ifdef MODULE_CSG_ENABLED
  54. #include "modules/csg/csg_shape.h"
  55. #endif
  56. #ifdef MODULE_GRIDMAP_ENABLED
  57. #include "modules/gridmap/grid_map.h"
  58. #endif
  59. NavigationMeshGenerator *NavigationMeshGenerator::singleton = NULL;
  60. void NavigationMeshGenerator::_add_vertex(const Vector3 &p_vec3, Vector<float> &p_vertices) {
  61. p_vertices.push_back(p_vec3.x);
  62. p_vertices.push_back(p_vec3.y);
  63. p_vertices.push_back(p_vec3.z);
  64. }
  65. void NavigationMeshGenerator::_add_mesh(const Ref<Mesh> &p_mesh, const Transform &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  66. int current_vertex_count;
  67. for (int i = 0; i < p_mesh->get_surface_count(); i++) {
  68. current_vertex_count = p_vertices.size() / 3;
  69. if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) {
  70. continue;
  71. }
  72. int index_count = 0;
  73. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  74. index_count = p_mesh->surface_get_array_index_len(i);
  75. } else {
  76. index_count = p_mesh->surface_get_array_len(i);
  77. }
  78. ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0));
  79. int face_count = index_count / 3;
  80. Array a = p_mesh->surface_get_arrays(i);
  81. PoolVector<Vector3> mesh_vertices = a[Mesh::ARRAY_VERTEX];
  82. PoolVector<Vector3>::Read vr = mesh_vertices.read();
  83. if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
  84. PoolVector<int> mesh_indices = a[Mesh::ARRAY_INDEX];
  85. PoolVector<int>::Read ir = mesh_indices.read();
  86. for (int j = 0; j < mesh_vertices.size(); j++) {
  87. _add_vertex(p_xform.xform(vr[j]), p_vertices);
  88. }
  89. for (int j = 0; j < face_count; j++) {
  90. // CCW
  91. p_indices.push_back(current_vertex_count + (ir[j * 3 + 0]));
  92. p_indices.push_back(current_vertex_count + (ir[j * 3 + 2]));
  93. p_indices.push_back(current_vertex_count + (ir[j * 3 + 1]));
  94. }
  95. } else {
  96. face_count = mesh_vertices.size() / 3;
  97. for (int j = 0; j < face_count; j++) {
  98. _add_vertex(p_xform.xform(vr[j * 3 + 0]), p_vertices);
  99. _add_vertex(p_xform.xform(vr[j * 3 + 2]), p_vertices);
  100. _add_vertex(p_xform.xform(vr[j * 3 + 1]), p_vertices);
  101. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  102. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  103. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  104. }
  105. }
  106. }
  107. }
  108. void NavigationMeshGenerator::_add_mesh_array(const Array &p_array, const Transform &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  109. PoolVector<Vector3> mesh_vertices = p_array[Mesh::ARRAY_VERTEX];
  110. PoolVector<Vector3>::Read vr = mesh_vertices.read();
  111. PoolVector<int> mesh_indices = p_array[Mesh::ARRAY_INDEX];
  112. PoolVector<int>::Read ir = mesh_indices.read();
  113. const int face_count = mesh_indices.size() / 3;
  114. const int current_vertex_count = p_vertices.size() / 3;
  115. for (int j = 0; j < mesh_vertices.size(); j++) {
  116. _add_vertex(p_xform.xform(vr[j]), p_vertices);
  117. }
  118. for (int j = 0; j < face_count; j++) {
  119. // CCW
  120. p_indices.push_back(current_vertex_count + (ir[j * 3 + 0]));
  121. p_indices.push_back(current_vertex_count + (ir[j * 3 + 2]));
  122. p_indices.push_back(current_vertex_count + (ir[j * 3 + 1]));
  123. }
  124. }
  125. void NavigationMeshGenerator::_add_faces(const PoolVector3Array &p_faces, const Transform &p_xform, Vector<float> &p_vertices, Vector<int> &p_indices) {
  126. int face_count = p_faces.size() / 3;
  127. int current_vertex_count = p_vertices.size() / 3;
  128. for (int j = 0; j < face_count; j++) {
  129. _add_vertex(p_xform.xform(p_faces[j * 3 + 0]), p_vertices);
  130. _add_vertex(p_xform.xform(p_faces[j * 3 + 1]), p_vertices);
  131. _add_vertex(p_xform.xform(p_faces[j * 3 + 2]), p_vertices);
  132. p_indices.push_back(current_vertex_count + (j * 3 + 0));
  133. p_indices.push_back(current_vertex_count + (j * 3 + 2));
  134. p_indices.push_back(current_vertex_count + (j * 3 + 1));
  135. }
  136. }
  137. void NavigationMeshGenerator::_parse_geometry(const Transform &p_navmesh_xform, Node *p_node, Vector<float> &p_vertices, Vector<int> &p_indices, int p_generate_from, uint32_t p_collision_mask, bool p_recurse_children) {
  138. if (Object::cast_to<MeshInstance>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  139. MeshInstance *mesh_instance = Object::cast_to<MeshInstance>(p_node);
  140. Ref<Mesh> mesh = mesh_instance->get_mesh();
  141. if (mesh.is_valid()) {
  142. _add_mesh(mesh, p_navmesh_xform * mesh_instance->get_global_transform(), p_vertices, p_indices);
  143. }
  144. }
  145. if (Object::cast_to<MultiMeshInstance>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  146. MultiMeshInstance *multimesh_instance = Object::cast_to<MultiMeshInstance>(p_node);
  147. Ref<MultiMesh> multimesh = multimesh_instance->get_multimesh();
  148. if (multimesh.is_valid()) {
  149. Ref<Mesh> mesh = multimesh->get_mesh();
  150. if (mesh.is_valid()) {
  151. int n = multimesh->get_visible_instance_count();
  152. if (n == -1) {
  153. n = multimesh->get_instance_count();
  154. }
  155. for (int i = 0; i < n; i++) {
  156. _add_mesh(mesh, p_navmesh_xform * multimesh_instance->get_global_transform() * multimesh->get_instance_transform(i), p_vertices, p_indices);
  157. }
  158. }
  159. }
  160. }
  161. #ifdef MODULE_CSG_ENABLED
  162. if (Object::cast_to<CSGShape>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  163. CSGShape *csg_shape = Object::cast_to<CSGShape>(p_node);
  164. Array meshes = csg_shape->get_meshes();
  165. if (!meshes.empty()) {
  166. Ref<Mesh> mesh = meshes[1];
  167. if (mesh.is_valid()) {
  168. _add_mesh(mesh, p_navmesh_xform * csg_shape->get_global_transform(), p_vertices, p_indices);
  169. }
  170. }
  171. }
  172. #endif
  173. if (Object::cast_to<StaticBody>(p_node) && p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES) {
  174. StaticBody *static_body = Object::cast_to<StaticBody>(p_node);
  175. if (static_body->get_collision_layer() & p_collision_mask) {
  176. List<uint32_t> shape_owners;
  177. static_body->get_shape_owners(&shape_owners);
  178. for (List<uint32_t>::Element *E = shape_owners.front(); E; E = E->next()) {
  179. uint32_t shape_owner = E->get();
  180. const int shape_count = static_body->shape_owner_get_shape_count(shape_owner);
  181. for (int i = 0; i < shape_count; i++) {
  182. if (static_body->is_shape_owner_disabled(i)) {
  183. continue;
  184. }
  185. Ref<Shape> s = static_body->shape_owner_get_shape(shape_owner, i);
  186. if (s.is_null()) {
  187. continue;
  188. }
  189. const Transform transform = p_navmesh_xform * static_body->get_global_transform() * static_body->shape_owner_get_transform(shape_owner);
  190. BoxShape *box = Object::cast_to<BoxShape>(*s);
  191. if (box) {
  192. Array arr;
  193. arr.resize(VS::ARRAY_MAX);
  194. CubeMesh::create_mesh_array(arr, box->get_extents() * 2.0);
  195. _add_mesh_array(arr, transform, p_vertices, p_indices);
  196. }
  197. CapsuleShape *capsule = Object::cast_to<CapsuleShape>(*s);
  198. if (capsule) {
  199. Array arr;
  200. arr.resize(VS::ARRAY_MAX);
  201. CapsuleMesh::create_mesh_array(arr, capsule->get_radius(), capsule->get_height() / 2.0);
  202. _add_mesh_array(arr, transform, p_vertices, p_indices);
  203. }
  204. CylinderShape *cylinder = Object::cast_to<CylinderShape>(*s);
  205. if (cylinder) {
  206. Array arr;
  207. arr.resize(VS::ARRAY_MAX);
  208. CylinderMesh::create_mesh_array(arr, cylinder->get_radius(), cylinder->get_radius(), cylinder->get_height());
  209. _add_mesh_array(arr, transform, p_vertices, p_indices);
  210. }
  211. SphereShape *sphere = Object::cast_to<SphereShape>(*s);
  212. if (sphere) {
  213. Array arr;
  214. arr.resize(VS::ARRAY_MAX);
  215. SphereMesh::create_mesh_array(arr, sphere->get_radius(), sphere->get_radius() * 2.0);
  216. _add_mesh_array(arr, transform, p_vertices, p_indices);
  217. }
  218. ConcavePolygonShape *concave_polygon = Object::cast_to<ConcavePolygonShape>(*s);
  219. if (concave_polygon) {
  220. _add_faces(concave_polygon->get_faces(), transform, p_vertices, p_indices);
  221. }
  222. ConvexPolygonShape *convex_polygon = Object::cast_to<ConvexPolygonShape>(*s);
  223. if (convex_polygon) {
  224. Vector<Vector3> varr = Variant(convex_polygon->get_points());
  225. Geometry::MeshData md;
  226. Error err = ConvexHullComputer::convex_hull(varr, md);
  227. if (err == OK) {
  228. PoolVector3Array faces;
  229. for (int j = 0; j < md.faces.size(); ++j) {
  230. Geometry::MeshData::Face face = md.faces[j];
  231. for (int k = 2; k < face.indices.size(); ++k) {
  232. faces.push_back(md.vertices[face.indices[0]]);
  233. faces.push_back(md.vertices[face.indices[k - 1]]);
  234. faces.push_back(md.vertices[face.indices[k]]);
  235. }
  236. }
  237. _add_faces(faces, transform, p_vertices, p_indices);
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. #ifdef MODULE_GRIDMAP_ENABLED
  245. GridMap *gridmap = Object::cast_to<GridMap>(p_node);
  246. if (gridmap) {
  247. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_STATIC_COLLIDERS) {
  248. Array meshes = gridmap->get_meshes();
  249. Transform xform = gridmap->get_global_transform();
  250. for (int i = 0; i < meshes.size(); i += 2) {
  251. Ref<Mesh> mesh = meshes[i + 1];
  252. if (mesh.is_valid()) {
  253. Transform mesh_xform = meshes[i];
  254. _add_mesh(mesh, p_navmesh_xform * xform * mesh_xform, p_vertices, p_indices);
  255. }
  256. }
  257. }
  258. if (p_generate_from != NavigationMesh::PARSED_GEOMETRY_MESH_INSTANCES && (gridmap->get_collision_layer() & p_collision_mask)) {
  259. Array shapes = gridmap->get_collision_shapes();
  260. for (int i = 0; i < shapes.size(); i += 2) {
  261. RID shape = shapes[i + 1];
  262. PhysicsServer::ShapeType type = PhysicsServer::get_singleton()->shape_get_type(shape);
  263. Variant data = PhysicsServer::get_singleton()->shape_get_data(shape);
  264. switch (type) {
  265. case PhysicsServer::SHAPE_SPHERE: {
  266. real_t radius = data;
  267. Array arr;
  268. arr.resize(VS::ARRAY_MAX);
  269. SphereMesh::create_mesh_array(arr, radius, radius * 2.0);
  270. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  271. } break;
  272. case PhysicsServer::SHAPE_BOX: {
  273. Vector3 extents = data;
  274. Array arr;
  275. arr.resize(VS::ARRAY_MAX);
  276. CubeMesh::create_mesh_array(arr, extents * 2.0);
  277. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  278. } break;
  279. case PhysicsServer::SHAPE_CAPSULE: {
  280. Dictionary dict = data;
  281. real_t radius = dict["radius"];
  282. real_t height = dict["height"];
  283. Array arr;
  284. arr.resize(VS::ARRAY_MAX);
  285. CapsuleMesh::create_mesh_array(arr, radius, height * 0.5);
  286. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  287. } break;
  288. case PhysicsServer::SHAPE_CYLINDER: {
  289. Dictionary dict = data;
  290. real_t radius = dict["radius"];
  291. real_t height = dict["height"];
  292. Array arr;
  293. arr.resize(VS::ARRAY_MAX);
  294. CylinderMesh::create_mesh_array(arr, radius, radius, height);
  295. _add_mesh_array(arr, shapes[i], p_vertices, p_indices);
  296. } break;
  297. case PhysicsServer::SHAPE_CONVEX_POLYGON: {
  298. PoolVector3Array vertices = data;
  299. Geometry::MeshData md;
  300. Error err = ConvexHullComputer::convex_hull(vertices, md);
  301. if (err == OK) {
  302. PoolVector3Array faces;
  303. for (int j = 0; j < md.faces.size(); ++j) {
  304. Geometry::MeshData::Face face = md.faces[j];
  305. for (int k = 2; k < face.indices.size(); ++k) {
  306. faces.push_back(md.vertices[face.indices[0]]);
  307. faces.push_back(md.vertices[face.indices[k - 1]]);
  308. faces.push_back(md.vertices[face.indices[k]]);
  309. }
  310. }
  311. _add_faces(faces, shapes[i], p_vertices, p_indices);
  312. }
  313. } break;
  314. case PhysicsServer::SHAPE_CONCAVE_POLYGON: {
  315. PoolVector3Array faces = data;
  316. _add_faces(faces, shapes[i], p_vertices, p_indices);
  317. } break;
  318. default: {
  319. WARN_PRINT("Unsupported collision shape type.");
  320. } break;
  321. }
  322. }
  323. }
  324. }
  325. #endif
  326. if (p_recurse_children) {
  327. for (int i = 0; i < p_node->get_child_count(); i++) {
  328. _parse_geometry(p_navmesh_xform, p_node->get_child(i), p_vertices, p_indices, p_generate_from, p_collision_mask, p_recurse_children);
  329. }
  330. }
  331. }
  332. void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref<NavigationMesh> p_nav_mesh) {
  333. PoolVector<Vector3> nav_vertices;
  334. for (int i = 0; i < p_detail_mesh->nverts; i++) {
  335. const float *v = &p_detail_mesh->verts[i * 3];
  336. nav_vertices.append(Vector3(v[0], v[1], v[2]));
  337. }
  338. p_nav_mesh->set_vertices(nav_vertices);
  339. for (int i = 0; i < p_detail_mesh->nmeshes; i++) {
  340. const unsigned int *m = &p_detail_mesh->meshes[i * 4];
  341. const unsigned int bverts = m[0];
  342. const unsigned int btris = m[2];
  343. const unsigned int ntris = m[3];
  344. const unsigned char *tris = &p_detail_mesh->tris[btris * 4];
  345. for (unsigned int j = 0; j < ntris; j++) {
  346. Vector<int> nav_indices;
  347. nav_indices.resize(3);
  348. // Polygon order in recast is opposite than godot's
  349. nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0]));
  350. nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2]));
  351. nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1]));
  352. p_nav_mesh->add_polygon(nav_indices);
  353. }
  354. }
  355. }
  356. void NavigationMeshGenerator::_build_recast_navigation_mesh(
  357. Ref<NavigationMesh> p_nav_mesh,
  358. #ifdef TOOLS_ENABLED
  359. EditorProgress *ep,
  360. #endif
  361. rcHeightfield *hf,
  362. rcCompactHeightfield *chf,
  363. rcContourSet *cset,
  364. rcPolyMesh *poly_mesh,
  365. rcPolyMeshDetail *detail_mesh,
  366. Vector<float> &vertices,
  367. Vector<int> &indices) {
  368. rcContext ctx;
  369. #ifdef TOOLS_ENABLED
  370. if (ep)
  371. ep->step(TTR("Setting up Configuration..."), 1);
  372. #endif
  373. const float *verts = vertices.ptr();
  374. const int nverts = vertices.size() / 3;
  375. const int *tris = indices.ptr();
  376. const int ntris = indices.size() / 3;
  377. float bmin[3], bmax[3];
  378. rcCalcBounds(verts, nverts, bmin, bmax);
  379. rcConfig cfg;
  380. memset(&cfg, 0, sizeof(cfg));
  381. cfg.cs = p_nav_mesh->get_cell_size();
  382. cfg.ch = p_nav_mesh->get_cell_height();
  383. cfg.walkableSlopeAngle = p_nav_mesh->get_agent_max_slope();
  384. cfg.walkableHeight = (int)Math::ceil(p_nav_mesh->get_agent_height() / cfg.ch);
  385. cfg.walkableClimb = (int)Math::floor(p_nav_mesh->get_agent_max_climb() / cfg.ch);
  386. cfg.walkableRadius = (int)Math::ceil(p_nav_mesh->get_agent_radius() / cfg.cs);
  387. cfg.maxEdgeLen = (int)(p_nav_mesh->get_edge_max_length() / p_nav_mesh->get_cell_size());
  388. cfg.maxSimplificationError = p_nav_mesh->get_edge_max_error();
  389. cfg.minRegionArea = (int)(p_nav_mesh->get_region_min_size() * p_nav_mesh->get_region_min_size());
  390. cfg.mergeRegionArea = (int)(p_nav_mesh->get_region_merge_size() * p_nav_mesh->get_region_merge_size());
  391. cfg.maxVertsPerPoly = (int)p_nav_mesh->get_verts_per_poly();
  392. cfg.detailSampleDist = MAX(p_nav_mesh->get_cell_size() * p_nav_mesh->get_detail_sample_distance(), 0.1f);
  393. cfg.detailSampleMaxError = p_nav_mesh->get_cell_height() * p_nav_mesh->get_detail_sample_max_error();
  394. cfg.bmin[0] = bmin[0];
  395. cfg.bmin[1] = bmin[1];
  396. cfg.bmin[2] = bmin[2];
  397. cfg.bmax[0] = bmax[0];
  398. cfg.bmax[1] = bmax[1];
  399. cfg.bmax[2] = bmax[2];
  400. AABB baking_aabb = p_nav_mesh->get_filter_baking_aabb();
  401. bool aabb_has_no_volume = baking_aabb.has_no_area();
  402. if (!aabb_has_no_volume) {
  403. Vector3 baking_aabb_offset = p_nav_mesh->get_filter_baking_aabb_offset();
  404. cfg.bmin[0] = baking_aabb.position[0] + baking_aabb_offset.x;
  405. cfg.bmin[1] = baking_aabb.position[1] + baking_aabb_offset.y;
  406. cfg.bmin[2] = baking_aabb.position[2] + baking_aabb_offset.z;
  407. cfg.bmax[0] = cfg.bmin[0] + baking_aabb.size[0];
  408. cfg.bmax[1] = cfg.bmin[1] + baking_aabb.size[1];
  409. cfg.bmax[2] = cfg.bmin[2] + baking_aabb.size[2];
  410. }
  411. #ifdef TOOLS_ENABLED
  412. if (ep)
  413. ep->step(TTR("Calculating grid size..."), 2);
  414. #endif
  415. rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
  416. // ~30000000 seems to be around sweetspot where Editor baking breaks
  417. if ((cfg.width * cfg.height) > 30000000) {
  418. WARN_PRINT("NavigationMesh baking process will likely fail."
  419. "\nSource geometry is suspiciously big for the current Cell Size and Cell Height in the NavMesh Resource bake settings."
  420. "\nIf baking does not fail, the resulting NavigationMesh will create serious pathfinding performance issues."
  421. "\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.");
  422. }
  423. #ifdef TOOLS_ENABLED
  424. if (ep)
  425. ep->step(TTR("Creating heightfield..."), 3);
  426. #endif
  427. hf = rcAllocHeightfield();
  428. ERR_FAIL_COND(!hf);
  429. ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch));
  430. #ifdef TOOLS_ENABLED
  431. if (ep)
  432. ep->step(TTR("Marking walkable triangles..."), 4);
  433. #endif
  434. {
  435. Vector<unsigned char> tri_areas;
  436. tri_areas.resize(ntris);
  437. ERR_FAIL_COND(tri_areas.size() == 0);
  438. memset(tri_areas.ptrw(), 0, ntris * sizeof(unsigned char));
  439. rcMarkWalkableTriangles(&ctx, cfg.walkableSlopeAngle, verts, nverts, tris, ntris, tri_areas.ptrw());
  440. ERR_FAIL_COND(!rcRasterizeTriangles(&ctx, verts, nverts, tris, tri_areas.ptr(), ntris, *hf, cfg.walkableClimb));
  441. }
  442. if (p_nav_mesh->get_filter_low_hanging_obstacles()) {
  443. rcFilterLowHangingWalkableObstacles(&ctx, cfg.walkableClimb, *hf);
  444. }
  445. if (p_nav_mesh->get_filter_ledge_spans()) {
  446. rcFilterLedgeSpans(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf);
  447. }
  448. if (p_nav_mesh->get_filter_walkable_low_height_spans()) {
  449. rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf);
  450. }
  451. #ifdef TOOLS_ENABLED
  452. if (ep)
  453. ep->step(TTR("Constructing compact heightfield..."), 5);
  454. #endif
  455. chf = rcAllocCompactHeightfield();
  456. ERR_FAIL_COND(!chf);
  457. ERR_FAIL_COND(!rcBuildCompactHeightfield(&ctx, cfg.walkableHeight, cfg.walkableClimb, *hf, *chf));
  458. rcFreeHeightField(hf);
  459. hf = 0;
  460. #ifdef TOOLS_ENABLED
  461. if (ep)
  462. ep->step(TTR("Eroding walkable area..."), 6);
  463. #endif
  464. ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf));
  465. #ifdef TOOLS_ENABLED
  466. if (ep)
  467. ep->step(TTR("Partitioning..."), 7);
  468. #endif
  469. if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) {
  470. ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf));
  471. ERR_FAIL_COND(!rcBuildRegions(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  472. } else if (p_nav_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_MONOTONE) {
  473. ERR_FAIL_COND(!rcBuildRegionsMonotone(&ctx, *chf, 0, cfg.minRegionArea, cfg.mergeRegionArea));
  474. } else {
  475. ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea));
  476. }
  477. #ifdef TOOLS_ENABLED
  478. if (ep)
  479. ep->step(TTR("Creating contours..."), 8);
  480. #endif
  481. cset = rcAllocContourSet();
  482. ERR_FAIL_COND(!cset);
  483. ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset));
  484. #ifdef TOOLS_ENABLED
  485. if (ep)
  486. ep->step(TTR("Creating polymesh..."), 9);
  487. #endif
  488. poly_mesh = rcAllocPolyMesh();
  489. ERR_FAIL_COND(!poly_mesh);
  490. ERR_FAIL_COND(!rcBuildPolyMesh(&ctx, *cset, cfg.maxVertsPerPoly, *poly_mesh));
  491. detail_mesh = rcAllocPolyMeshDetail();
  492. ERR_FAIL_COND(!detail_mesh);
  493. ERR_FAIL_COND(!rcBuildPolyMeshDetail(&ctx, *poly_mesh, *chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *detail_mesh));
  494. rcFreeCompactHeightfield(chf);
  495. chf = 0;
  496. rcFreeContourSet(cset);
  497. cset = 0;
  498. #ifdef TOOLS_ENABLED
  499. if (ep)
  500. ep->step(TTR("Converting to native navigation mesh..."), 10);
  501. #endif
  502. _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_nav_mesh);
  503. rcFreePolyMesh(poly_mesh);
  504. poly_mesh = 0;
  505. rcFreePolyMeshDetail(detail_mesh);
  506. detail_mesh = 0;
  507. }
  508. NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() {
  509. return singleton;
  510. }
  511. NavigationMeshGenerator::NavigationMeshGenerator() {
  512. singleton = this;
  513. }
  514. NavigationMeshGenerator::~NavigationMeshGenerator() {
  515. }
  516. void NavigationMeshGenerator::bake(Ref<NavigationMesh> p_nav_mesh, Node *p_node) {
  517. ERR_FAIL_COND_MSG(!p_nav_mesh.is_valid(), "Invalid Navigation Mesh");
  518. #ifdef TOOLS_ENABLED
  519. EditorProgress *ep(nullptr);
  520. // FIXME
  521. #endif
  522. #if 0
  523. // After discussion on devchat disabled EditorProgress for now as it is not thread-safe and uses hacks and Main::iteration() for steps.
  524. // 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
  525. // This was not a problem in older versions as previously Godot was unable to (re)bake NavigationMesh at runtime.
  526. // If EditorProgress is fixed and made thread-safe this should be enabled again.
  527. if (Engine::get_singleton()->is_editor_hint()) {
  528. ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11));
  529. }
  530. if (ep)
  531. ep->step(TTR("Parsing Geometry..."), 0);
  532. #endif
  533. Vector<float> vertices;
  534. Vector<int> indices;
  535. List<Node *> parse_nodes;
  536. if (p_nav_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_NAVMESH_CHILDREN) {
  537. parse_nodes.push_back(p_node);
  538. } else {
  539. p_node->get_tree()->get_nodes_in_group(p_nav_mesh->get_source_group_name(), &parse_nodes);
  540. }
  541. Transform navmesh_xform = Object::cast_to<Spatial>(p_node)->get_global_transform().affine_inverse();
  542. for (const List<Node *>::Element *E = parse_nodes.front(); E; E = E->next()) {
  543. NavigationMesh::ParsedGeometryType geometry_type = p_nav_mesh->get_parsed_geometry_type();
  544. uint32_t collision_mask = p_nav_mesh->get_collision_mask();
  545. bool recurse_children = p_nav_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT;
  546. _parse_geometry(navmesh_xform, E->get(), vertices, indices, geometry_type, collision_mask, recurse_children);
  547. }
  548. if (vertices.size() > 0 && indices.size() > 0) {
  549. rcHeightfield *hf = nullptr;
  550. rcCompactHeightfield *chf = nullptr;
  551. rcContourSet *cset = nullptr;
  552. rcPolyMesh *poly_mesh = nullptr;
  553. rcPolyMeshDetail *detail_mesh = nullptr;
  554. _build_recast_navigation_mesh(
  555. p_nav_mesh,
  556. #ifdef TOOLS_ENABLED
  557. ep,
  558. #endif
  559. hf,
  560. chf,
  561. cset,
  562. poly_mesh,
  563. detail_mesh,
  564. vertices,
  565. indices);
  566. rcFreeHeightField(hf);
  567. hf = 0;
  568. rcFreeCompactHeightfield(chf);
  569. chf = 0;
  570. rcFreeContourSet(cset);
  571. cset = 0;
  572. rcFreePolyMesh(poly_mesh);
  573. poly_mesh = 0;
  574. rcFreePolyMeshDetail(detail_mesh);
  575. detail_mesh = 0;
  576. }
  577. #ifdef TOOLS_ENABLED
  578. if (ep)
  579. ep->step(TTR("Done!"), 11);
  580. if (ep)
  581. memdelete(ep);
  582. #endif
  583. p_nav_mesh->property_list_changed_notify();
  584. }
  585. void NavigationMeshGenerator::clear(Ref<NavigationMesh> p_nav_mesh) {
  586. if (p_nav_mesh.is_valid()) {
  587. p_nav_mesh->clear_polygons();
  588. p_nav_mesh->set_vertices(PoolVector<Vector3>());
  589. }
  590. }
  591. void NavigationMeshGenerator::_bind_methods() {
  592. ClassDB::bind_method(D_METHOD("bake", "nav_mesh", "root_node"), &NavigationMeshGenerator::bake);
  593. ClassDB::bind_method(D_METHOD("clear", "nav_mesh"), &NavigationMeshGenerator::clear);
  594. }
  595. #endif