navigation_using_navigationmeshes.rst 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. .. _doc_navigation_using_navigationmeshes:
  2. Using navigation meshes
  3. =======================
  4. .. image:: img/nav_meshes.webp
  5. 2D and 3D versions of the navigation mesh are available as
  6. :ref:`NavigationPolygon<class_NavigationPolygon>` and
  7. :ref:`NavigationMesh<class_NavigationMesh>` respectively.
  8. .. note::
  9. A navigation mesh only describes a traversable area for an agent's center position. Any radius values an agent may have are ignored.
  10. If you want pathfinding to account for an agent's (collision) size you need to shrink the navigation mesh accordingly.
  11. Navigation works independently from other engine parts like rendering or physics.
  12. Navigation meshes are the only things considered when doing pathfinding, e.g. visuals and collision shapes for example are completely ignored by the navigation system.
  13. If you need to take other data (like visuals for example) into account when doing pathfinding, you need to adapt your navigation meshes accordingly.
  14. The process of factoring in navigation restrictions in navigation meshes is commonly referred to as navigation mesh baking.
  15. .. figure:: img/nav_mesh_vs_physics.webp
  16. :align: center
  17. :alt: Navigation mesh polygon convex vs concave comparison
  18. A navigation mesh describes a surface that an agent can stand on safely with its center compared to physics shapes that describe outer collision bounds.
  19. If you experience clipping or collision problems while following navigation paths, always remember that you need to tell the navigation system what your intentions are through an appropriate navigation mesh.
  20. By itself the navigation system will never know "this is a tree / rock / wall collision shape or visual mesh" because it only knows that "here I was told I can path safely because it is on a navigation mesh".
  21. .. _doc_navigation_navmesh_baking:
  22. Navigation mesh baking can be done either by using a :ref:`NavigationRegion2D<class_NavigationRegion2D>` or :ref:`NavigationRegion3D<class_NavigationRegion3D>`, or by using the
  23. :ref:`NavigationServer2D<class_NavigationServer2D>` and :ref:`NavigationServer3D<class_NavigationServer3D>` API directly.
  24. .. _doc_navigation_using_navigationmeshes_baking_navigation_mesh_with_navigationregion:
  25. Baking a navigation mesh with a NavigationRegion
  26. ------------------------------------------------
  27. .. figure:: img/nav_mesh_baking_steps.gif
  28. :align: center
  29. :alt: Navigation mesh baking steps
  30. Baking a navigation mesh with agent radius offset from geometry.
  31. The navigation mesh baking is made more accessible with the NavigationRegion node. When baking with a NavigationRegion
  32. node, the individual parsing, baking, and region update steps are all combined into one function.
  33. The nodes are available in 2D and 3D as :ref:`NavigationRegion2D<class_NavigationRegion2D>` and :ref:`NavigationRegion3D<class_NavigationRegion3D>` respectively.
  34. .. tabs::
  35. .. tab:: Baking with a NavigationRegion2D
  36. When a NavigationRegion2D node is selected in the Editor, bake options as well as polygon draw tools appear in the top bar of the Editor.
  37. .. image:: img/nav_region_baking_01.webp
  38. In order for the region to work a :ref:`NavigationPolygon<class_NavigationPolygon>` resource needs to be added.
  39. The properties to parse and bake a navigation mesh are then part of the used resource and can be found in the resource Inspector.
  40. .. image:: img/nav_region_baking_02.webp
  41. The result of the source geometry parsing can be influenced with the following properties.
  42. - The ``parsed_geometry_type`` that filters if visual objects or physics objects or both should be parsed from the :ref:`SceneTree<class_SceneTree>`.
  43. For more details on what objects are parsed and how, see the section about parsing source geometry below.
  44. - The ``collision_mask`` filters which physics collision objects are included when the ``parsed_geometry_type`` includes static colliders.
  45. - The ``source_geometry_mode`` that defines on which node(s) to start the parsing, and how to traverse the :ref:`SceneTree<class_SceneTree>`.
  46. - The ``source_geometry_group_name`` is used when only a certain node group should be parsed. Depends on the selected ``source_geometry_mode``.
  47. With the source geometry added, the result of the baking can be controlled with the following properties.
  48. - The ``cell_size`` sets the rasterization grid size and should match the navigation map size.
  49. - The ``agent_radius`` shrinks the baked navigation mesh to have enough margin for the agent (collision) size.
  50. The NavigationRegion2D baking can also be used at runtime with scripts.
  51. .. tabs::
  52. .. code-tab:: gdscript GDScript
  53. var on_thread: bool = true
  54. bake_navigation_polygon(on_thread)
  55. To quickly test the 2D baking with default settings:
  56. - Add a :ref:`NavigationRegion2D<class_NavigationRegion2D>`.
  57. - Add a :ref:`NavigationPolygon<class_NavigationPolygon>` resource to the NavigationRegion2D.
  58. - Add a :ref:`Polygon2D<class_Polygon2D>` below the NavigationRegion2D.
  59. - Draw 1 NavigationPolygon outline with the selected NavigationRegion2D draw tool.
  60. - Draw 1 Polygon2D outline inside the NavigationPolygon outline with the selected Polygon2D draw tool.
  61. - Hit the Editor bake button and a navigation mesh should appear.
  62. .. image:: img/nav_region_baking_01.webp
  63. .. image:: img/nav_mesh_mini_2d.webp
  64. .. tab:: Baking with a NavigationRegion3D
  65. When a NavigationRegion3D node is selected in the Editor, bake options appear in the top bar of the Editor.
  66. .. image:: img/nav_mesh_bake_toolbar.webp
  67. In order for the region to work a :ref:`NavigationMesh<class_NavigationMesh>` resource needs to be added.
  68. The properties to parse and bake a navigation mesh are then part of the used resource and can be found in the resource Inspector.
  69. .. image:: img/nav_region3d_baking_01.webp
  70. The result of the source geometry parsing can be influenced with the following properties.
  71. - The ``parsed_geometry_type`` that filters if visual objects or physics objects or both should be parsed from the :ref:`SceneTree<class_SceneTree>`.
  72. For more details on what objects are parsed and how, see the section about parsing source geometry below.
  73. - The ``collision_mask`` filters which physics collision objects are included when the ``parsed_geometry_type`` includes static colliders.
  74. - The ``source_geometry_mode`` that defines on which node(s) to start the parsing, and how to traverse the :ref:`SceneTree<class_SceneTree>`.
  75. - The ``source_geometry_group_name`` is used when only a certain node group should be parsed. Depends on the selected ``source_geometry_mode``.
  76. With the source geometry added, the result of the baking can be controlled with the following properties.
  77. - The ``cell_size`` and ``cell_height`` sets the rasterization voxel grid size and should match the navigation map size.
  78. - The ``agent_radius`` shrinks the baked navigation mesh to have enough margin for the agent (collision) size.
  79. - The ``agent_height`` excludes areas from the navigation mesh where the agent is too tall to fit in.
  80. - The ``agent_max_climb`` and ``agent_max_slope`` removes areas where the height difference between neighboring voxels is too large, or where their surface is too steep.
  81. .. warning::
  82. A too small ``cell_size`` or ``cell_height`` can create so many voxels that it has the potential to freeze the game or even crash.
  83. The NavigationRegion3D baking can also be used at runtime with scripts.
  84. .. tabs::
  85. .. code-tab:: gdscript GDScript
  86. var on_thread: bool = true
  87. bake_navigation_mesh(on_thread)
  88. To quickly test the 3D baking with default settings:
  89. - Add a :ref:`NavigationRegion3D<class_NavigationRegion3D>`.
  90. - Add a :ref:`NavigationMesh<class_NavigationMesh>` resource to the NavigationRegion3D.
  91. - Add a :ref:`MeshInstance3D<class_MeshInstance3D>` below the NavigationRegion3D.
  92. - Add a :ref:`PlaneMesh<class_PlaneMesh>` to the MeshInstance3D.
  93. - Hit the Editor bake button and a navigation mesh should appear.
  94. .. image:: img/nav_mesh_bake_toolbar.webp
  95. .. image:: img/nav_mesh_mini_3d.webp
  96. .. _doc_navigation_using_navigationmeshes_baking_navigation_mesh_with_navigationserver:
  97. Baking a navigation mesh with the NavigationServer
  98. --------------------------------------------------
  99. The :ref:`NavigationServer2D<class_NavigationServer2D>` and :ref:`NavigationServer3D<class_NavigationServer3D>` have API functions to call each step of the navigation mesh baking process individually.
  100. - ``parse_source_geometry_data()`` can be used to parse source geometry to a reusable and serializable resource.
  101. - ``bake_from_source_geometry_data()`` can be used to bake a navigation mesh from already parsed data e.g. to avoid runtime performance issues with (redundant) parsing.
  102. - ``bake_from_source_geometry_data_async()`` is the same but bakes the navigation mesh deferred with threads, not blocking the main thread.
  103. Compared to a NavigationRegion, the NavigationServer offers finer control over the navigation mesh baking process.
  104. In turn it is more complex to use but also provides more advanced options.
  105. Some other advantages of the NavigationServer over a NavigationRegion are:
  106. - The server can parse source geometry without baking, e.g. to cache it for later use.
  107. - The server allows selecting the root node at which to start the source geometry parsing manually.
  108. - The server can accept and bake from procedurally generated source geometry data.
  109. - The server can bake multiple navigation meshes in sequence while (re)using the same source geometry data.
  110. To bake navigation meshes with the NavigationServer, source geometry is required.
  111. Source geometry is geometry data that should be considered in a navigation mesh baking process.
  112. Both navigation meshes for 2D and 3D are created by baking them from source geometry.
  113. 2D and 3D versions of the source geometry resources are available as
  114. :ref:`NavigationMeshSourceGeometryData2D<class_NavigationMeshSourceGeometryData2D>` and
  115. :ref:`NavigationMeshSourceGeometryData3D<class_NavigationMeshSourceGeometryData3D>` respectively.
  116. Source geometry can be geometry parsed from visual meshes, from physics collision,
  117. or procedural created arrays of data, like outlines (2D) and triangle faces (3D).
  118. For convenience, source geometry is commonly parsed directly from node setups in the SceneTree.
  119. For runtime navigation mesh (re)bakes, be aware that the geometry parsing always happens on the main thread.
  120. .. note::
  121. The SceneTree is not thread-safe. Parsing source geometry from the SceneTree can only be done on the main thread.
  122. .. warning::
  123. The data from visual meshes and polygons needs to be received from the GPU, stalling the RenderingServer in the process.
  124. For runtime (re)baking prefer using physics shapes as parsed source geometry.
  125. Source geometry is stored inside resources so the created geometry can be reused for multiple bakes.
  126. E.g. baking multiple navigation meshes for different agent sizes from the same source geometry.
  127. This also allows to save source geometry to disk so it can be loaded later, e.g. to avoid the overhead of parsing it again at runtime.
  128. The geometry data should be in general kept very simple. As many edges as are required but as few as possible.
  129. Especially in 2D duplicated and nested geometry should be avoided as it forces polygon hole calculation that can result in flipped polygons.
  130. An example for nested geometry would be a smaller StaticBody2D shape placed completely inside the bounds of another StaticBody2D shape.
  131. Navigation mesh baking common problems
  132. --------------------------------------
  133. There are some common user problems and important caveats to consider when creating or baking navigation meshes.
  134. - Navigation mesh baking creates frame rate problems at runtime
  135. The navigation mesh baking is by default done on a background thread, so as long as the platform supports threads, the actual baking is
  136. rarely the source of any performance issues (assuming a reasonably sized and complex geometry for runtime rebakes).
  137. The common source for performance issues at runtime is the parsing step for source geometry that involves nodes and the SceneTree.
  138. The SceneTree is not thread-safe so all the nodes need to be parsed on the main thread.
  139. Some nodes with a lot of data can be very heavy and slow to parse at runtime, e.g. a TileMap has one or more polygons for every single used cell and TileMapLayer to parse.
  140. Nodes that hold meshes need to request the data from the RenderingServer stalling the rendering in the process.
  141. To improve performance, use more optimized shapes, e.g. collision shapes over detailed visual meshes, and merge and simplify as much geometry as possible upfront.
  142. If nothing helps, don't parse the SceneTree and add the source geometry procedural with scripts. If only pure data arrays are used as source geometry, the entire baking process can be done on a background thread.
  143. - Navigation mesh creates unintended holes in 2D.
  144. The navigation mesh baking in 2D is done by doing polygon clipping operations based on outline paths.
  145. Polygons with "holes" are a necessary evil to create more complex 2D polygons but can become unpredictable for users with many complex shapes involved.
  146. To avoid any unexpected problems with polygon hole calculations, avoid nesting any outlines inside other outlines of the same type (traversable / obstruction).
  147. This includes the parsed shapes from nodes. E.g. placing a smaller StaticBody2D shape inside a larger StaticBody2D shape can result in the resulting polygon being flipped.
  148. - Navigation mesh appears inside geometry in 3D.
  149. The navigation mesh baking in 3D has no concept of "inside". The voxel cells used to rasterize the geometry are either occupied or not.
  150. Remove the geometry that is on the ground inside the other geometry. If that is not possible, add smaller "dummy" geometry inside with as few triangles as possible so the cells
  151. are occupied with something.
  152. .. tabs::
  153. .. code-tab:: gdscript 2D GDScript
  154. extends Node2D
  155. func parse_and_bake_navigation_mesh_and_create_region() -> void:
  156. # Note, the navigation mesh is not baked here, it only holds the parse parameters.
  157. var navigation_mesh: NavigationPolygon = NavigationPolygon.new()
  158. # Create the source geometry that will hold the parsed data.
  159. var source_geometry := NavigationMeshSourceGeometryData2D.new()
  160. # The Node where the parsing should start traversing the SceneTree.
  161. var root_node: Node2D = self
  162. NavigationServer2D.parse_source_geometry_data(
  163. navigation_mesh,
  164. source_geometry,
  165. root_node
  166. )
  167. # Bake the navigation mesh with the source geometry data.
  168. NavigationServer2D.bake_from_source_geometry_data_async(
  169. navigation_mesh,
  170. source_geometry
  171. )
  172. # Create a new navigation region and update the region with prepared navigation mesh.
  173. var region_rid: RID = NavigationServer2D.region_create()
  174. NavigationServer2D.region_set_navigation_polygon(region_rid, navigation_mesh)
  175. NavigationServer2D.region_set_enabled(region_rid, true)
  176. NavigationServer2D.region_set_map(region_rid, get_world_2d().get_navigation_map())
  177. .. code-tab:: gdscript 3D GDScript
  178. extends Node3D
  179. func parse_and_bake_navigation_mesh_and_create_region() -> void:
  180. # Note, the navigation mesh is not baked here, it only holds the parse parameters.
  181. var navigation_mesh: NavigationMesh = NavigationMesh.new()
  182. # Create the source geometry that will hold the parsed data.
  183. var source_geometry := NavigationMeshSourceGeometryData3D.new()
  184. # The Node where the parsing should start traversing the SceneTree.
  185. var root_node: Node3D = self
  186. NavigationServer3D.parse_source_geometry_data(
  187. navigation_mesh,
  188. source_geometry,
  189. root_node
  190. )
  191. # Bake the navigation mesh with the source geometry data.
  192. NavigationServer3D.bake_from_source_geometry_data_async(
  193. navigation_mesh,
  194. source_geometry
  195. )
  196. # Create a new navigation region and update the region with prepared navigation mesh.
  197. var region_rid: RID = NavigationServer3D.region_create()
  198. NavigationServer3D.region_set_navigation_mesh(region_rid, navigation_mesh)
  199. NavigationServer3D.region_set_enabled(region_rid, true)
  200. NavigationServer3D.region_set_map(region_rid, get_world_3d().get_navigation_map())
  201. Navigation mesh script templates
  202. --------------------------------
  203. The following script creates a new navigation region and fills it with procedurally generated navigation mesh data.
  204. .. tabs::
  205. .. code-tab:: gdscript 2D GDScript
  206. extends Node2D
  207. func _ready() -> void:
  208. var new_2d_region_rid: RID = NavigationServer2D.region_create()
  209. var default_2d_map_rid: RID = get_world_2d().get_navigation_map()
  210. NavigationServer2D.region_set_map(new_2d_region_rid, default_2d_map_rid)
  211. var new_navigation_mesh: NavigationPolygon = NavigationPolygon.new()
  212. # Add vertices for a convex polygon.
  213. new_navigation_mesh.vertices = PackedVector2Array([
  214. Vector2(0.0, 0.0),
  215. Vector2(100.0, 0.0),
  216. Vector2(100.0, 100.0),
  217. Vector2(0.0, 100.0)
  218. ])
  219. # Add indices for the polygon.
  220. new_navigation_mesh.add_polygon(
  221. PackedInt32Array([0, 1, 2, 3])
  222. )
  223. NavigationServer2D.region_set_navigation_polygon(new_2d_region_rid, new_navigation_mesh)
  224. .. code-tab:: gdscript 3D GDScript
  225. extends Node3D
  226. func _ready() -> void:
  227. var new_3d_region_rid: RID = NavigationServer3D.region_create()
  228. var default_3d_map_rid: RID = get_world_3d().get_navigation_map()
  229. NavigationServer3D.region_set_map(new_3d_region_rid, default_3d_map_rid)
  230. var new_navigation_mesh: NavigationMesh = NavigationMesh.new()
  231. # Add vertices for a convex polygon.
  232. new_navigation_mesh.vertices = PackedVector3Array([
  233. Vector3(-1.0, 0.0, 1.0),
  234. Vector3(1.0, 0.0, 1.0),
  235. Vector3(1.0, 0.0, -1.0),
  236. Vector3(-1.0, 0.0, -1.0),
  237. ])
  238. # Add indices for the polygon.
  239. new_navigation_mesh.add_polygon(
  240. PackedInt32Array([0, 1, 2, 3])
  241. )
  242. NavigationServer3D.region_set_navigation_mesh(new_3d_region_rid, new_navigation_mesh)