navigation_mesh_generator.cpp 29 KB

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