diff --git a/doc/classes/NavigationMeshGenerator.xml b/doc/classes/NavigationMeshGenerator.xml index e10e23a5cf0..f13d6b570ab 100644 --- a/doc/classes/NavigationMeshGenerator.xml +++ b/doc/classes/NavigationMeshGenerator.xml @@ -14,12 +14,21 @@ $DOCS_URL/tutorials/navigation/navigation_using_navigationmeshes.html - + - Bakes navigation data to the provided [param navigation_mesh] by parsing child nodes under the provided [param root_node] or a specific group of nodes for potential source geometry. The parse behavior can be controlled with the [member NavigationMesh.geometry_parsed_geometry_type] and [member NavigationMesh.geometry_source_geometry_mode] properties on the [NavigationMesh] resource. + The bake function is deprecated due to core threading changes. To upgrade existing code, first create a [NavigationMeshSourceGeometryData3D] resource. Use this resource with [method parse_source_geometry_data] to parse the SceneTree for nodes that should contribute to the navigation mesh baking. The SceneTree parsing needs to happen on the main thread. After the parsing is finished use the resource with [method bake_from_source_geometry_data] to bake a navigation mesh. + + + + + + + + + Bakes the provided [param navigation_mesh] with the data from the provided [param source_geometry_data]. After the process is finished the optional [param callback] will be called. @@ -29,5 +38,16 @@ Removes all polygons and vertices from the provided [param navigation_mesh] resource. + + + + + + + + Parses the [SceneTree] for source geometry according to the properties of [param navigation_mesh]. Updates the provided [param source_geometry_data] resource with the resulting data. The resource can then be used to bake a navigation mesh with [method bake_from_source_geometry_data]. After the process is finished the optional [param callback] will be called. + [b]Note:[/b] This function needs to run on the main thread or with a deferred call as the SceneTree is not thread-safe. + + diff --git a/doc/classes/NavigationMeshSourceGeometryData3D.xml b/doc/classes/NavigationMeshSourceGeometryData3D.xml new file mode 100644 index 00000000000..b929e824369 --- /dev/null +++ b/doc/classes/NavigationMeshSourceGeometryData3D.xml @@ -0,0 +1,77 @@ + + + + Container for parsed source geometry data used in navigation mesh baking. + + + Container for parsed source geometry data used in navigation mesh baking. + + + + + + + + + + Adds an array of vertex positions to the geometry data for navigation mesh baking to form triangulated faces. For each face the array must have three vertex positions in clockwise winding order. Since [NavigationMesh] resource have no transform all vertex positions need to be offset by the node's transform using the [code]xform[/code] parameter. + + + + + + + + Adds the geometry data of a [Mesh] resource to the navigation mesh baking data. The mesh must have valid triangulated mesh data to be considered. Since [NavigationMesh] resource have no transform all vertex positions need to be offset by the node's transform using the [code]xform[/code] parameter. + + + + + + + + Adds an [Array] the size of [constant Mesh.ARRAY_MAX] and with vertices at index [constant Mesh.ARRAY_VERTEX] and indices at index [constant Mesh.ARRAY_INDEX] to the navigation mesh baking data. The array must have valid triangulated mesh data to be considered. Since [NavigationMesh] resource have no transform all vertex positions need to be offset by the node's transform using the [code]xform[/code] parameter. + + + + + + Clears the internal data. + + + + + + Returns the parsed source geometry data indices array. + + + + + + Returns the parsed source geometry data vertices array. + + + + + + Returns [b]true[/b] when parsed source geometry data exists. + + + + + + + Sets the parsed source geometry data indices. The indices need to be matched with appropriated vertices. + [b]Warning:[/b] Inappropriate data can crash the baking process of the involved third-party libraries. + + + + + + + Sets the parsed source geometry data vertices. The vertices need to be matched with appropriated indices. + [b]Warning:[/b] Inappropriate data can crash the baking process of the involved third-party libraries. + + + + diff --git a/doc/classes/NavigationServer3D.xml b/doc/classes/NavigationServer3D.xml index 6f406aa629e..79b8e30652e 100644 --- a/doc/classes/NavigationServer3D.xml +++ b/doc/classes/NavigationServer3D.xml @@ -192,6 +192,15 @@ Replaces the internal velocity in the collision avoidance simulation with [param velocity] for the specified [param agent]. When an agent is teleported to a new position this function should be used in the same frame. If called frequently this function can get agents stuck. + + + + + + + Bakes the provided [param navigation_mesh] with the data from the provided [param source_geometry_data]. After the process is finished the optional [param callback] will be called. + + @@ -622,6 +631,17 @@ Sets the outline vertices for the obstacle. If the vertices are winded in clockwise order agents will be pushed in by the obstacle, else they will be pushed out. + + + + + + + + Parses the [SceneTree] for source geometry according to the properties of [param navigation_mesh]. Updates the provided [param source_geometry_data] resource with the resulting data. The resource can then be used to bake a navigation mesh with [method bake_from_source_geometry_data]. After the process is finished the optional [param callback] will be called. + [b]Note:[/b] This function needs to run on the main thread or with a deferred call as the SceneTree is not thread-safe. + + diff --git a/modules/navigation/editor/navigation_mesh_editor_plugin.cpp b/modules/navigation/editor/navigation_mesh_editor_plugin.cpp index dd2c539c953..bf6a75cce8d 100644 --- a/modules/navigation/editor/navigation_mesh_editor_plugin.cpp +++ b/modules/navigation/editor/navigation_mesh_editor_plugin.cpp @@ -41,6 +41,7 @@ #include "scene/gui/button.h" #include "scene/gui/dialogs.h" #include "scene/gui/label.h" +#include "scene/resources/navigation_mesh_source_geometry_data_3d.h" void NavigationMeshEditor::_node_removed(Node *p_node) { if (p_node == node) { @@ -98,7 +99,10 @@ void NavigationMeshEditor::_bake_pressed() { } NavigationMeshGenerator::get_singleton()->clear(node->get_navigation_mesh()); - NavigationMeshGenerator::get_singleton()->bake(node->get_navigation_mesh(), node); + Ref source_geometry_data; + source_geometry_data.instantiate(); + NavigationMeshGenerator::get_singleton()->parse_source_geometry_data(node->get_navigation_mesh(), source_geometry_data, node); + NavigationMeshGenerator::get_singleton()->bake_from_source_geometry_data(node->get_navigation_mesh(), source_geometry_data); node->update_gizmos(); } diff --git a/modules/navigation/godot_navigation_server.cpp b/modules/navigation/godot_navigation_server.cpp index c72b61014b7..98ac1348966 100644 --- a/modules/navigation/godot_navigation_server.cpp +++ b/modules/navigation/godot_navigation_server.cpp @@ -451,7 +451,10 @@ void GodotNavigationServer::region_bake_navigation_mesh(Ref p_na #ifndef _3D_DISABLED NavigationMeshGenerator::get_singleton()->clear(p_navigation_mesh); - NavigationMeshGenerator::get_singleton()->bake(p_navigation_mesh, p_root_node); + Ref source_geometry_data; + source_geometry_data.instantiate(); + NavigationMeshGenerator::get_singleton()->parse_source_geometry_data(p_navigation_mesh, source_geometry_data, p_root_node); + NavigationMeshGenerator::get_singleton()->bake_from_source_geometry_data(p_navigation_mesh, source_geometry_data); #endif } @@ -911,6 +914,18 @@ COMMAND_2(obstacle_set_avoidance_layers, RID, p_obstacle, uint32_t, p_layers) { obstacle->set_avoidance_layers(p_layers); } +void GodotNavigationServer::parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback) { +#ifndef _3D_DISABLED + NavigationMeshGenerator::get_singleton()->parse_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_root_node, p_callback); +#endif +} + +void GodotNavigationServer::bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback) { +#ifndef _3D_DISABLED + NavigationMeshGenerator::get_singleton()->bake_from_source_geometry_data(p_navigation_mesh, p_source_geometry_data, p_callback); +#endif +} + COMMAND_1(free, RID, p_object) { if (map_owner.owns(p_object)) { NavMap *map = map_owner.get_or_null(p_object); diff --git a/modules/navigation/godot_navigation_server.h b/modules/navigation/godot_navigation_server.h index 8c9b1eb1b19..0ad639ef0d7 100644 --- a/modules/navigation/godot_navigation_server.h +++ b/modules/navigation/godot_navigation_server.h @@ -211,6 +211,9 @@ public: virtual void obstacle_set_vertices(RID p_obstacle, const Vector &p_vertices) override; COMMAND_2(obstacle_set_avoidance_layers, RID, p_obstacle, uint32_t, p_layers); + virtual void parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback = Callable()) override; + virtual void bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback = Callable()) override; + COMMAND_1(free, RID, p_object); virtual void set_active(bool p_active) override; diff --git a/modules/navigation/navigation_mesh_generator.cpp b/modules/navigation/navigation_mesh_generator.cpp index fe63d67aba9..88965cd4395 100644 --- a/modules/navigation/navigation_mesh_generator.cpp +++ b/modules/navigation/navigation_mesh_generator.cpp @@ -43,6 +43,7 @@ #include "scene/resources/convex_polygon_shape_3d.h" #include "scene/resources/cylinder_shape_3d.h" #include "scene/resources/height_map_shape_3d.h" +#include "scene/resources/navigation_mesh_source_geometry_data_3d.h" #include "scene/resources/primitive_meshes.h" #include "scene/resources/shape_3d.h" #include "scene/resources/sphere_shape_3d.h" @@ -466,52 +467,102 @@ void NavigationMeshGenerator::_parse_geometry(const Transform3D &p_navmesh_trans } } -void NavigationMeshGenerator::_convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref p_navigation_mesh) { - Vector nav_vertices; +NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() { + return singleton; +} - for (int i = 0; i < p_detail_mesh->nverts; i++) { - const float *v = &p_detail_mesh->verts[i * 3]; - nav_vertices.push_back(Vector3(v[0], v[1], v[2])); +NavigationMeshGenerator::NavigationMeshGenerator() { + singleton = this; +} + +NavigationMeshGenerator::~NavigationMeshGenerator() { +} + +void NavigationMeshGenerator::bake(const Ref &p_navigation_mesh, Node *p_root_node) { + WARN_PRINT_ONCE("NavigationMeshGenerator::bake() is deprecated due to core threading changes. To upgrade existing code, first create a NavigationMeshSourceGeometryData3D resource. Use this resource with method parse_source_geometry_data() to parse the SceneTree for nodes that should contribute to the navigation mesh baking. The SceneTree parsing needs to happen on the main thread. After the parsing is finished use the resource with method bake_from_source_geometry_data() to bake a navigation mesh.."); +} + +void NavigationMeshGenerator::clear(Ref p_navigation_mesh) { + if (p_navigation_mesh.is_valid()) { + p_navigation_mesh->clear_polygons(); + p_navigation_mesh->set_vertices(Vector()); } - p_navigation_mesh->set_vertices(nav_vertices); +} - for (int i = 0; i < p_detail_mesh->nmeshes; i++) { - const unsigned int *m = &p_detail_mesh->meshes[i * 4]; - const unsigned int bverts = m[0]; - const unsigned int btris = m[2]; - const unsigned int ntris = m[3]; - const unsigned char *tris = &p_detail_mesh->tris[btris * 4]; - for (unsigned int j = 0; j < ntris; j++) { - Vector nav_indices; - nav_indices.resize(3); - // Polygon order in recast is opposite than godot's - nav_indices.write[0] = ((int)(bverts + tris[j * 4 + 0])); - nav_indices.write[1] = ((int)(bverts + tris[j * 4 + 2])); - nav_indices.write[2] = ((int)(bverts + tris[j * 4 + 1])); - p_navigation_mesh->add_polygon(nav_indices); +void NavigationMeshGenerator::parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback) { + ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "The SceneTree can only be parsed on the main thread. Call this function from the main thread or use call_deferred()."); + ERR_FAIL_COND_MSG(!p_navigation_mesh.is_valid(), "Invalid navigation mesh."); + ERR_FAIL_COND_MSG(p_root_node == nullptr, "No parsing root node specified."); + ERR_FAIL_COND_MSG(!p_root_node->is_inside_tree(), "The root node needs to be inside the SceneTree."); + + Vector vertices; + Vector indices; + + List parse_nodes; + + if (p_navigation_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_ROOT_NODE_CHILDREN) { + parse_nodes.push_back(p_root_node); + } else { + p_root_node->get_tree()->get_nodes_in_group(p_navigation_mesh->get_source_group_name(), &parse_nodes); + } + + Transform3D navmesh_xform = Transform3D(); + if (Object::cast_to(p_root_node)) { + navmesh_xform = Object::cast_to(p_root_node)->get_global_transform().affine_inverse(); + } + for (Node *E : parse_nodes) { + NavigationMesh::ParsedGeometryType geometry_type = p_navigation_mesh->get_parsed_geometry_type(); + uint32_t collision_mask = p_navigation_mesh->get_collision_mask(); + bool recurse_children = p_navigation_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT; + _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children); + } + + p_source_geometry_data->set_vertices(vertices); + p_source_geometry_data->set_indices(indices); + + if (p_callback.is_valid()) { + Callable::CallError ce; + Variant result; + p_callback.callp(nullptr, 0, result, ce); + if (ce.error == Callable::CallError::CALL_OK) { + // } } } -void NavigationMeshGenerator::_build_recast_navigation_mesh( - Ref p_navigation_mesh, -#ifdef TOOLS_ENABLED - EditorProgress *ep, -#endif - rcHeightfield *hf, - rcCompactHeightfield *chf, - rcContourSet *cset, - rcPolyMesh *poly_mesh, - rcPolyMeshDetail *detail_mesh, - Vector &vertices, - Vector &indices) { +void NavigationMeshGenerator::bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback) { + ERR_FAIL_COND_MSG(!p_navigation_mesh.is_valid(), "Invalid navigation mesh."); + ERR_FAIL_COND_MSG(!p_source_geometry_data.is_valid(), "Invalid NavigationMeshSourceGeometryData3D."); + ERR_FAIL_COND_MSG(!p_source_geometry_data->has_data(), "NavigationMeshSourceGeometryData3D is empty. Parse source geometry first."); + + generator_mutex.lock(); + if (baking_navmeshes.has(p_navigation_mesh)) { + generator_mutex.unlock(); + ERR_FAIL_MSG("NavigationMesh is already baking. Wait for current bake to finish."); + } else { + baking_navmeshes.insert(p_navigation_mesh); + generator_mutex.unlock(); + } + +#ifndef _3D_DISABLED + const Vector vertices = p_source_geometry_data->get_vertices(); + const Vector indices = p_source_geometry_data->get_indices(); + + if (vertices.size() < 3 || indices.size() < 3) { + return; + } + + rcHeightfield *hf = nullptr; + rcCompactHeightfield *chf = nullptr; + rcContourSet *cset = nullptr; + rcPolyMesh *poly_mesh = nullptr; + rcPolyMeshDetail *detail_mesh = nullptr; rcContext ctx; -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Setting up Configuration..."), 1); - } -#endif + // added to keep track of steps, no functionality right now + String bake_state = ""; + + bake_state = "Setting up Configuration..."; // step #1 const float *verts = vertices.ptr(); const int nverts = vertices.size() / 3; @@ -581,11 +632,7 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( cfg.bmax[2] = cfg.bmin[2] + baking_aabb.size[2]; } -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Calculating grid size..."), 2); - } -#endif + bake_state = "Calculating grid size..."; // step #2 rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height); // ~30000000 seems to be around sweetspot where Editor baking breaks @@ -596,21 +643,13 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( "\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."); } -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Creating heightfield..."), 3); - } -#endif + bake_state = "Creating heightfield..."; // step #3 hf = rcAllocHeightfield(); ERR_FAIL_COND(!hf); ERR_FAIL_COND(!rcCreateHeightfield(&ctx, *hf, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs, cfg.ch)); -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Marking walkable triangles..."), 4); - } -#endif + bake_state = "Marking walkable triangles..."; // step #4 { Vector tri_areas; tri_areas.resize(ntris); @@ -633,11 +672,7 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( rcFilterWalkableLowHeightSpans(&ctx, cfg.walkableHeight, *hf); } -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Constructing compact heightfield..."), 5); - } -#endif + bake_state = "Constructing compact heightfield..."; // step #5 chf = rcAllocCompactHeightfield(); @@ -647,19 +682,11 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( rcFreeHeightField(hf); hf = nullptr; -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Eroding walkable area..."), 6); - } -#endif + bake_state = "Eroding walkable area..."; // step #6 ERR_FAIL_COND(!rcErodeWalkableArea(&ctx, cfg.walkableRadius, *chf)); -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Partitioning..."), 7); - } -#endif + bake_state = "Partitioning..."; // step #7 if (p_navigation_mesh->get_sample_partition_type() == NavigationMesh::SAMPLE_PARTITION_WATERSHED) { ERR_FAIL_COND(!rcBuildDistanceField(&ctx, *chf)); @@ -670,22 +697,14 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( ERR_FAIL_COND(!rcBuildLayerRegions(&ctx, *chf, 0, cfg.minRegionArea)); } -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Creating contours..."), 8); - } -#endif + bake_state = "Creating contours..."; // step #8 cset = rcAllocContourSet(); ERR_FAIL_COND(!cset); ERR_FAIL_COND(!rcBuildContours(&ctx, *chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *cset)); -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Creating polymesh..."), 9); - } -#endif + bake_state = "Creating polymesh..."; // step #9 poly_mesh = rcAllocPolyMesh(); ERR_FAIL_COND(!poly_mesh); @@ -700,128 +719,63 @@ void NavigationMeshGenerator::_build_recast_navigation_mesh( rcFreeContourSet(cset); cset = nullptr; -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Converting to native navigation mesh..."), 10); - } -#endif + bake_state = "Converting to native navigation mesh..."; // step #10 - _convert_detail_mesh_to_native_navigation_mesh(detail_mesh, p_navigation_mesh); + Vector nav_vertices; + + for (int i = 0; i < detail_mesh->nverts; i++) { + const float *v = &detail_mesh->verts[i * 3]; + nav_vertices.push_back(Vector3(v[0], v[1], v[2])); + } + p_navigation_mesh->set_vertices(nav_vertices); + + for (int i = 0; i < detail_mesh->nmeshes; i++) { + const unsigned int *detail_mesh_m = &detail_mesh->meshes[i * 4]; + const unsigned int detail_mesh_bverts = detail_mesh_m[0]; + const unsigned int detail_mesh_m_btris = detail_mesh_m[2]; + const unsigned int detail_mesh_ntris = detail_mesh_m[3]; + const unsigned char *detail_mesh_tris = &detail_mesh->tris[detail_mesh_m_btris * 4]; + for (unsigned int j = 0; j < detail_mesh_ntris; j++) { + Vector nav_indices; + nav_indices.resize(3); + // Polygon order in recast is opposite than godot's + nav_indices.write[0] = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 0])); + nav_indices.write[1] = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 2])); + nav_indices.write[2] = ((int)(detail_mesh_bverts + detail_mesh_tris[j * 4 + 1])); + p_navigation_mesh->add_polygon(nav_indices); + } + } + + bake_state = "Cleanup..."; // step #11 rcFreePolyMesh(poly_mesh); poly_mesh = nullptr; rcFreePolyMeshDetail(detail_mesh); detail_mesh = nullptr; -} -NavigationMeshGenerator *NavigationMeshGenerator::get_singleton() { - return singleton; -} + bake_state = "Baking finished."; // step #12 +#endif // _3D_DISABLED -NavigationMeshGenerator::NavigationMeshGenerator() { - singleton = this; -} + generator_mutex.lock(); + baking_navmeshes.erase(p_navigation_mesh); + generator_mutex.unlock(); -NavigationMeshGenerator::~NavigationMeshGenerator() { -} - -void NavigationMeshGenerator::bake(Ref p_navigation_mesh, Node *p_root_node) { - ERR_FAIL_COND_MSG(!p_navigation_mesh.is_valid(), "Invalid navigation mesh."); - -#ifdef TOOLS_ENABLED - EditorProgress *ep(nullptr); - // FIXME -#endif -#if 0 - // After discussion on devchat disabled EditorProgress for now as it is not thread-safe and uses hacks and Main::iteration() for steps. - // 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 - // This was not a problem in older versions as previously Godot was unable to (re)bake NavigationMesh at runtime. - // If EditorProgress is fixed and made thread-safe this should be enabled again. - if (Engine::get_singleton()->is_editor_hint()) { - ep = memnew(EditorProgress("bake", TTR("Navigation Mesh Generator Setup:"), 11)); - } - - if (ep) { - ep->step(TTR("Parsing Geometry..."), 0); - } -#endif - - Vector vertices; - Vector indices; - - List parse_nodes; - - if (p_navigation_mesh->get_source_geometry_mode() == NavigationMesh::SOURCE_GEOMETRY_ROOT_NODE_CHILDREN) { - parse_nodes.push_back(p_root_node); - } else { - p_root_node->get_tree()->get_nodes_in_group(p_navigation_mesh->get_source_group_name(), &parse_nodes); - } - - Transform3D navmesh_xform = Object::cast_to(p_root_node)->get_global_transform().affine_inverse(); - for (Node *E : parse_nodes) { - NavigationMesh::ParsedGeometryType geometry_type = p_navigation_mesh->get_parsed_geometry_type(); - uint32_t collision_mask = p_navigation_mesh->get_collision_mask(); - bool recurse_children = p_navigation_mesh->get_source_geometry_mode() != NavigationMesh::SOURCE_GEOMETRY_GROUPS_EXPLICIT; - _parse_geometry(navmesh_xform, E, vertices, indices, geometry_type, collision_mask, recurse_children); - } - - if (vertices.size() > 0 && indices.size() > 0) { - rcHeightfield *hf = nullptr; - rcCompactHeightfield *chf = nullptr; - rcContourSet *cset = nullptr; - rcPolyMesh *poly_mesh = nullptr; - rcPolyMeshDetail *detail_mesh = nullptr; - - _build_recast_navigation_mesh( - p_navigation_mesh, -#ifdef TOOLS_ENABLED - ep, -#endif - hf, - chf, - cset, - poly_mesh, - detail_mesh, - vertices, - indices); - - rcFreeHeightField(hf); - hf = nullptr; - - rcFreeCompactHeightfield(chf); - chf = nullptr; - - rcFreeContourSet(cset); - cset = nullptr; - - rcFreePolyMesh(poly_mesh); - poly_mesh = nullptr; - - rcFreePolyMeshDetail(detail_mesh); - detail_mesh = nullptr; - } - -#ifdef TOOLS_ENABLED - if (ep) { - ep->step(TTR("Done!"), 11); - } - - if (ep) { - memdelete(ep); - } -#endif -} - -void NavigationMeshGenerator::clear(Ref p_navigation_mesh) { - if (p_navigation_mesh.is_valid()) { - p_navigation_mesh->clear_polygons(); - p_navigation_mesh->set_vertices(Vector()); + if (p_callback.is_valid()) { + Callable::CallError ce; + Variant result; + p_callback.callp(nullptr, 0, result, ce); + if (ce.error == Callable::CallError::CALL_OK) { + // + } } } void NavigationMeshGenerator::_bind_methods() { ClassDB::bind_method(D_METHOD("bake", "navigation_mesh", "root_node"), &NavigationMeshGenerator::bake); ClassDB::bind_method(D_METHOD("clear", "navigation_mesh"), &NavigationMeshGenerator::clear); + + ClassDB::bind_method(D_METHOD("parse_source_geometry_data", "navigation_mesh", "source_geometry_data", "root_node", "callback"), &NavigationMeshGenerator::parse_source_geometry_data, DEFVAL(Callable())); + ClassDB::bind_method(D_METHOD("bake_from_source_geometry_data", "navigation_mesh", "source_geometry_data", "callback"), &NavigationMeshGenerator::bake_from_source_geometry_data, DEFVAL(Callable())); } #endif diff --git a/modules/navigation/navigation_mesh_generator.h b/modules/navigation/navigation_mesh_generator.h index 4399c422e2e..4bf2b64f441 100644 --- a/modules/navigation/navigation_mesh_generator.h +++ b/modules/navigation/navigation_mesh_generator.h @@ -34,18 +34,20 @@ #ifndef _3D_DISABLED #include "scene/3d/navigation_region_3d.h" +#include "scene/resources/navigation_mesh.h" #include -#ifdef TOOLS_ENABLED -struct EditorProgress; -#endif +class NavigationMeshSourceGeometryData3D; class NavigationMeshGenerator : public Object { GDCLASS(NavigationMeshGenerator, Object); + Mutex generator_mutex; static NavigationMeshGenerator *singleton; + HashSet> baking_navmeshes; + protected: static void _bind_methods(); @@ -55,28 +57,17 @@ protected: static void _add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform, Vector &p_vertices, Vector &p_indices); static void _parse_geometry(const Transform3D &p_navmesh_transform, Node *p_node, Vector &p_vertices, Vector &p_indices, NavigationMesh::ParsedGeometryType p_generate_from, uint32_t p_collision_mask, bool p_recurse_children); - static void _convert_detail_mesh_to_native_navigation_mesh(const rcPolyMeshDetail *p_detail_mesh, Ref p_navigation_mesh); - static void _build_recast_navigation_mesh( - Ref p_navigation_mesh, -#ifdef TOOLS_ENABLED - EditorProgress *ep, -#endif - rcHeightfield *hf, - rcCompactHeightfield *chf, - rcContourSet *cset, - rcPolyMesh *poly_mesh, - rcPolyMeshDetail *detail_mesh, - Vector &vertices, - Vector &indices); - public: static NavigationMeshGenerator *get_singleton(); NavigationMeshGenerator(); ~NavigationMeshGenerator(); - void bake(Ref p_navigation_mesh, Node *p_root_node); + void bake(const Ref &p_navigation_mesh, Node *p_root_node); void clear(Ref p_navigation_mesh); + + void parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback = Callable()); + void bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback = Callable()); }; #endif diff --git a/scene/3d/navigation_region_3d.cpp b/scene/3d/navigation_region_3d.cpp index 165d44436cb..dfa38ea70f8 100644 --- a/scene/3d/navigation_region_3d.cpp +++ b/scene/3d/navigation_region_3d.cpp @@ -31,6 +31,7 @@ #include "navigation_region_3d.h" #include "mesh_instance_3d.h" +#include "scene/resources/navigation_mesh_source_geometry_data_3d.h" #include "servers/navigation_server_3d.h" void NavigationRegion3D::set_enabled(bool p_enabled) { @@ -263,6 +264,7 @@ Ref NavigationRegion3D::get_navigation_mesh() const { struct BakeThreadsArgs { NavigationRegion3D *nav_region = nullptr; + Ref source_geometry_data; }; void _bake_navigation_mesh(void *p_user_data) { @@ -270,8 +272,9 @@ void _bake_navigation_mesh(void *p_user_data) { if (args->nav_region->get_navigation_mesh().is_valid()) { Ref nav_mesh = args->nav_region->get_navigation_mesh()->duplicate(); + Ref source_geometry_data = args->source_geometry_data; - NavigationServer3D::get_singleton()->region_bake_navigation_mesh(nav_mesh, args->nav_region); + NavigationServer3D::get_singleton()->bake_from_source_geometry_data(nav_mesh, source_geometry_data); args->nav_region->call_deferred(SNAME("_bake_finished"), nav_mesh); memdelete(args); } else { @@ -282,10 +285,18 @@ void _bake_navigation_mesh(void *p_user_data) { } void NavigationRegion3D::bake_navigation_mesh(bool p_on_thread) { + ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "The SceneTree can only be parsed on the main thread. Call this function from the main thread or use call_deferred()."); + ERR_FAIL_COND_MSG(!navigation_mesh.is_valid(), "Baking the navigation mesh requires a valid `NavigationMesh` resource."); ERR_FAIL_COND_MSG(bake_thread.is_started(), "Unable to start another bake request. The navigation mesh bake thread is already baking a navigation mesh."); + Ref source_geometry_data; + source_geometry_data.instantiate(); + + NavigationServer3D::get_singleton()->parse_source_geometry_data(navigation_mesh, source_geometry_data, this); + BakeThreadsArgs *args = memnew(BakeThreadsArgs); args->nav_region = this; + args->source_geometry_data = source_geometry_data; if (p_on_thread) { bake_thread.start(_bake_navigation_mesh, args); diff --git a/scene/register_scene_types.cpp b/scene/register_scene_types.cpp index a4fe24dfd95..9706fb1a5d6 100644 --- a/scene/register_scene_types.cpp +++ b/scene/register_scene_types.cpp @@ -165,6 +165,7 @@ #include "scene/resources/mesh_data_tool.h" #include "scene/resources/multimesh.h" #include "scene/resources/navigation_mesh.h" +#include "scene/resources/navigation_mesh_source_geometry_data_3d.h" #include "scene/resources/navigation_polygon.h" #include "scene/resources/packed_scene.h" #include "scene/resources/particle_process_material.h" @@ -930,6 +931,7 @@ void register_scene_types() { GDREGISTER_CLASS(PathFollow2D); GDREGISTER_CLASS(NavigationMesh); + GDREGISTER_CLASS(NavigationMeshSourceGeometryData3D); GDREGISTER_CLASS(NavigationPolygon); GDREGISTER_CLASS(NavigationRegion2D); GDREGISTER_CLASS(NavigationAgent2D); diff --git a/scene/resources/navigation_mesh_source_geometry_data_3d.cpp b/scene/resources/navigation_mesh_source_geometry_data_3d.cpp new file mode 100644 index 00000000000..0201fb70b21 --- /dev/null +++ b/scene/resources/navigation_mesh_source_geometry_data_3d.cpp @@ -0,0 +1,181 @@ +/**************************************************************************/ +/* navigation_mesh_source_geometry_data_3d.cpp */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#include "navigation_mesh_source_geometry_data_3d.h" + +void NavigationMeshSourceGeometryData3D::set_vertices(const Vector &p_vertices) { + vertices = p_vertices; +} + +void NavigationMeshSourceGeometryData3D::set_indices(const Vector &p_indices) { + indices = p_indices; +} + +void NavigationMeshSourceGeometryData3D::clear() { + vertices.clear(); + indices.clear(); +} + +void NavigationMeshSourceGeometryData3D::_add_vertex(const Vector3 &p_vec3) { + vertices.push_back(p_vec3.x); + vertices.push_back(p_vec3.y); + vertices.push_back(p_vec3.z); +} + +void NavigationMeshSourceGeometryData3D::_add_mesh(const Ref &p_mesh, const Transform3D &p_xform) { + int current_vertex_count; + for (int i = 0; i < p_mesh->get_surface_count(); i++) { + current_vertex_count = vertices.size() / 3; + + if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES) { + continue; + } + + int index_count = 0; + if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) { + index_count = p_mesh->surface_get_array_index_len(i); + } else { + index_count = p_mesh->surface_get_array_len(i); + } + + ERR_CONTINUE((index_count == 0 || (index_count % 3) != 0)); + + int face_count = index_count / 3; + + Array a = p_mesh->surface_get_arrays(i); + + Vector mesh_vertices = a[Mesh::ARRAY_VERTEX]; + const Vector3 *vr = mesh_vertices.ptr(); + + if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) { + Vector mesh_indices = a[Mesh::ARRAY_INDEX]; + const int *ir = mesh_indices.ptr(); + + for (int j = 0; j < mesh_vertices.size(); j++) { + _add_vertex(p_xform.xform(vr[j])); + } + + for (int j = 0; j < face_count; j++) { + // CCW + indices.push_back(current_vertex_count + (ir[j * 3 + 0])); + indices.push_back(current_vertex_count + (ir[j * 3 + 2])); + indices.push_back(current_vertex_count + (ir[j * 3 + 1])); + } + } else { + face_count = mesh_vertices.size() / 3; + for (int j = 0; j < face_count; j++) { + _add_vertex(p_xform.xform(vr[j * 3 + 0])); + _add_vertex(p_xform.xform(vr[j * 3 + 2])); + _add_vertex(p_xform.xform(vr[j * 3 + 1])); + + indices.push_back(current_vertex_count + (j * 3 + 0)); + indices.push_back(current_vertex_count + (j * 3 + 1)); + indices.push_back(current_vertex_count + (j * 3 + 2)); + } + } + } +} + +void NavigationMeshSourceGeometryData3D::_add_mesh_array(const Array &p_mesh_array, const Transform3D &p_xform) { + Vector mesh_vertices = p_mesh_array[Mesh::ARRAY_VERTEX]; + const Vector3 *vr = mesh_vertices.ptr(); + + Vector mesh_indices = p_mesh_array[Mesh::ARRAY_INDEX]; + const int *ir = mesh_indices.ptr(); + + const int face_count = mesh_indices.size() / 3; + const int current_vertex_count = vertices.size() / 3; + + for (int j = 0; j < mesh_vertices.size(); j++) { + _add_vertex(p_xform.xform(vr[j])); + } + + for (int j = 0; j < face_count; j++) { + // CCW + indices.push_back(current_vertex_count + (ir[j * 3 + 0])); + indices.push_back(current_vertex_count + (ir[j * 3 + 2])); + indices.push_back(current_vertex_count + (ir[j * 3 + 1])); + } +} + +void NavigationMeshSourceGeometryData3D::_add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform) { + int face_count = p_faces.size() / 3; + int current_vertex_count = vertices.size() / 3; + + for (int j = 0; j < face_count; j++) { + _add_vertex(p_xform.xform(p_faces[j * 3 + 0])); + _add_vertex(p_xform.xform(p_faces[j * 3 + 1])); + _add_vertex(p_xform.xform(p_faces[j * 3 + 2])); + + indices.push_back(current_vertex_count + (j * 3 + 0)); + indices.push_back(current_vertex_count + (j * 3 + 2)); + indices.push_back(current_vertex_count + (j * 3 + 1)); + } +} + +void NavigationMeshSourceGeometryData3D::add_mesh(const Ref &p_mesh, const Transform3D &p_xform) { + ERR_FAIL_COND(!p_mesh.is_valid()); + _add_mesh(p_mesh, root_node_transform * p_xform); +} + +void NavigationMeshSourceGeometryData3D::add_mesh_array(const Array &p_mesh_array, const Transform3D &p_xform) { + ERR_FAIL_COND(p_mesh_array.size() != Mesh::ARRAY_MAX); + _add_mesh_array(p_mesh_array, root_node_transform * p_xform); +} + +void NavigationMeshSourceGeometryData3D::add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform) { + ERR_FAIL_COND(p_faces.size() % 3 != 0); + _add_faces(p_faces, root_node_transform * p_xform); +} + +void NavigationMeshSourceGeometryData3D::_bind_methods() { + ClassDB::bind_method(D_METHOD("set_vertices", "vertices"), &NavigationMeshSourceGeometryData3D::set_vertices); + ClassDB::bind_method(D_METHOD("get_vertices"), &NavigationMeshSourceGeometryData3D::get_vertices); + + ClassDB::bind_method(D_METHOD("set_indices", "indices"), &NavigationMeshSourceGeometryData3D::set_indices); + ClassDB::bind_method(D_METHOD("get_indices"), &NavigationMeshSourceGeometryData3D::get_indices); + + ClassDB::bind_method(D_METHOD("clear"), &NavigationMeshSourceGeometryData3D::clear); + ClassDB::bind_method(D_METHOD("has_data"), &NavigationMeshSourceGeometryData3D::has_data); + + ClassDB::bind_method(D_METHOD("add_mesh", "mesh", "xform"), &NavigationMeshSourceGeometryData3D::add_mesh); + ClassDB::bind_method(D_METHOD("add_mesh_array", "mesh_array", "xform"), &NavigationMeshSourceGeometryData3D::add_mesh_array); + ClassDB::bind_method(D_METHOD("add_faces", "faces", "xform"), &NavigationMeshSourceGeometryData3D::add_faces); + + ADD_PROPERTY(PropertyInfo(Variant::PACKED_VECTOR3_ARRAY, "vertices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_vertices", "get_vertices"); + ADD_PROPERTY(PropertyInfo(Variant::PACKED_INT32_ARRAY, "indices", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "set_indices", "get_indices"); +} + +NavigationMeshSourceGeometryData3D::NavigationMeshSourceGeometryData3D() { +} + +NavigationMeshSourceGeometryData3D::~NavigationMeshSourceGeometryData3D() { + clear(); +} diff --git a/scene/resources/navigation_mesh_source_geometry_data_3d.h b/scene/resources/navigation_mesh_source_geometry_data_3d.h new file mode 100644 index 00000000000..ec8bddd4ddb --- /dev/null +++ b/scene/resources/navigation_mesh_source_geometry_data_3d.h @@ -0,0 +1,75 @@ +/**************************************************************************/ +/* navigation_mesh_source_geometry_data_3d.h */ +/**************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/**************************************************************************/ +/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ +/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining */ +/* a copy of this software and associated documentation files (the */ +/* "Software"), to deal in the Software without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of the Software, and to */ +/* permit persons to whom the Software is furnished to do so, subject to */ +/* the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be */ +/* included in all copies or substantial portions of the Software. */ +/* */ +/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ +/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ +/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ +/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ +/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ +/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ +/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/**************************************************************************/ + +#ifndef NAVIGATION_MESH_SOURCE_GEOMETRY_DATA_3D_H +#define NAVIGATION_MESH_SOURCE_GEOMETRY_DATA_3D_H + +#include "scene/3d/visual_instance_3d.h" + +class NavigationMeshSourceGeometryData3D : public Resource { + GDCLASS(NavigationMeshSourceGeometryData3D, Resource); + + Vector vertices; + Vector indices; + +protected: + static void _bind_methods(); + +private: + void _add_vertex(const Vector3 &p_vec3); + void _add_mesh(const Ref &p_mesh, const Transform3D &p_xform); + void _add_mesh_array(const Array &p_array, const Transform3D &p_xform); + void _add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform); + +public: + // kept root node transform here on the geometry data + // if we add this transform to all exposed functions we need to break comp on all functions later + // when navmesh changes from global transform to relative to navregion + // but if it stays here we can just remove it and change the internal functions only + Transform3D root_node_transform; + + void set_vertices(const Vector &p_vertices); + const Vector &get_vertices() const { return vertices; } + + void set_indices(const Vector &p_indices); + const Vector &get_indices() const { return indices; } + + bool has_data() { return vertices.size() && indices.size(); }; + void clear(); + + void add_mesh(const Ref &p_mesh, const Transform3D &p_xform); + void add_mesh_array(const Array &p_mesh_array, const Transform3D &p_xform); + void add_faces(const PackedVector3Array &p_faces, const Transform3D &p_xform); + + NavigationMeshSourceGeometryData3D(); + ~NavigationMeshSourceGeometryData3D(); +}; + +#endif // NAVIGATION_MESH_SOURCE_GEOMETRY_DATA_3D_H diff --git a/servers/navigation_server_3d.cpp b/servers/navigation_server_3d.cpp index f9f8797b76f..4840ddc638a 100644 --- a/servers/navigation_server_3d.cpp +++ b/servers/navigation_server_3d.cpp @@ -141,6 +141,9 @@ void NavigationServer3D::_bind_methods() { ClassDB::bind_method(D_METHOD("obstacle_set_vertices", "obstacle", "vertices"), &NavigationServer3D::obstacle_set_vertices); ClassDB::bind_method(D_METHOD("obstacle_set_avoidance_layers", "obstacle", "layers"), &NavigationServer3D::obstacle_set_avoidance_layers); + ClassDB::bind_method(D_METHOD("parse_source_geometry_data", "navigation_mesh", "source_geometry_data", "root_node", "callback"), &NavigationServer3D::parse_source_geometry_data); + ClassDB::bind_method(D_METHOD("bake_from_source_geometry_data", "navigation_mesh", "source_geometry_data", "callback"), &NavigationServer3D::bake_from_source_geometry_data); + ClassDB::bind_method(D_METHOD("free_rid", "rid"), &NavigationServer3D::free); ClassDB::bind_method(D_METHOD("set_active", "active"), &NavigationServer3D::set_active); diff --git a/servers/navigation_server_3d.h b/servers/navigation_server_3d.h index 23c38532e8c..80a779c0f4b 100644 --- a/servers/navigation_server_3d.h +++ b/servers/navigation_server_3d.h @@ -35,6 +35,7 @@ #include "core/templates/rid.h" #include "scene/3d/navigation_region_3d.h" +#include "scene/resources/navigation_mesh_source_geometry_data_3d.h" #include "servers/navigation/navigation_path_query_parameters_3d.h" #include "servers/navigation/navigation_path_query_result_3d.h" @@ -288,6 +289,9 @@ public: virtual NavigationUtilities::PathQueryResult _query_path(const NavigationUtilities::PathQueryParameters &p_parameters) const = 0; + virtual void parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback = Callable()) = 0; + virtual void bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback = Callable()) = 0; + NavigationServer3D(); ~NavigationServer3D() override; diff --git a/servers/navigation_server_3d_dummy.h b/servers/navigation_server_3d_dummy.h index 23fd8291db4..f05c108be06 100644 --- a/servers/navigation_server_3d_dummy.h +++ b/servers/navigation_server_3d_dummy.h @@ -133,6 +133,8 @@ public: void obstacle_set_position(RID p_obstacle, Vector3 p_position) override {} void obstacle_set_vertices(RID p_obstacle, const Vector &p_vertices) override {} void obstacle_set_avoidance_layers(RID p_obstacle, uint32_t p_layers) override {} + void parse_source_geometry_data(const Ref &p_navigation_mesh, Ref p_source_geometry_data, Node *p_root_node, const Callable &p_callback = Callable()) override {} + void bake_from_source_geometry_data(Ref p_navigation_mesh, const Ref &p_source_geometry_data, const Callable &p_callback = Callable()) override {} void free(RID p_object) override {} void set_active(bool p_active) override {} void process(real_t delta_time) override {}