NavigationMesh.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. /// \file
  23. #pragma once
  24. #include "../Container/ArrayPtr.h"
  25. #include "../Container/HashSet.h"
  26. #include "../Math/BoundingBox.h"
  27. #include "../Math/Matrix3x4.h"
  28. #include "../Scene/Component.h"
  29. #ifdef DT_POLYREF64
  30. using dtPolyRef = uint64_t;
  31. #else
  32. using dtPolyRef = unsigned int;
  33. #endif
  34. class dtNavMesh;
  35. class dtNavMeshQuery;
  36. class dtQueryFilter;
  37. namespace Urho3D
  38. {
  39. enum NavmeshPartitionType
  40. {
  41. NAVMESH_PARTITION_WATERSHED = 0,
  42. NAVMESH_PARTITION_MONOTONE
  43. };
  44. class Geometry;
  45. class NavArea;
  46. struct FindPathData;
  47. struct NavBuildData;
  48. /// Description of a navigation mesh geometry component, with transform and bounds information.
  49. struct NavigationGeometryInfo
  50. {
  51. /// Component.
  52. Component* component_;
  53. /// Geometry LOD level if applicable.
  54. unsigned lodLevel_;
  55. /// Transform relative to the navigation mesh root node.
  56. Matrix3x4 transform_;
  57. /// Bounding box relative to the navigation mesh root node.
  58. BoundingBox boundingBox_;
  59. };
  60. /// A flag representing the type of path point- none, the start of a path segment, the end of one, or an off-mesh connection.
  61. enum NavigationPathPointFlag
  62. {
  63. NAVPATHFLAG_NONE = 0,
  64. NAVPATHFLAG_START = 0x01,
  65. NAVPATHFLAG_END = 0x02,
  66. NAVPATHFLAG_OFF_MESH = 0x04
  67. };
  68. struct URHO3D_API NavigationPathPoint
  69. {
  70. /// World-space position of the path point.
  71. Vector3 position_;
  72. /// Detour flag.
  73. NavigationPathPointFlag flag_;
  74. /// Detour area ID.
  75. unsigned char areaID_;
  76. };
  77. /// Navigation mesh component. Collects the navigation geometry from child nodes with the Navigable component and responds to path queries.
  78. class URHO3D_API NavigationMesh : public Component
  79. {
  80. URHO3D_OBJECT(NavigationMesh, Component);
  81. friend class CrowdManager;
  82. public:
  83. /// Construct.
  84. explicit NavigationMesh(Context* context);
  85. /// Destruct.
  86. ~NavigationMesh() override;
  87. /// Register object factory.
  88. static void RegisterObject(Context* context);
  89. /// Visualize the component as debug geometry.
  90. void DrawDebugGeometry(DebugRenderer* debug, bool depthTest) override;
  91. /// Set tile size.
  92. void SetTileSize(int size);
  93. /// Set cell size.
  94. void SetCellSize(float size);
  95. /// Set cell height.
  96. void SetCellHeight(float height);
  97. /// Set navigation agent height.
  98. void SetAgentHeight(float height);
  99. /// Set navigation agent radius.
  100. void SetAgentRadius(float radius);
  101. /// Set navigation agent max vertical climb.
  102. void SetAgentMaxClimb(float maxClimb);
  103. /// Set navigation agent max slope.
  104. void SetAgentMaxSlope(float maxSlope);
  105. /// Set region minimum size.
  106. void SetRegionMinSize(float size);
  107. /// Set region merge size.
  108. void SetRegionMergeSize(float size);
  109. /// Set edge max length.
  110. void SetEdgeMaxLength(float length);
  111. /// Set edge max error.
  112. void SetEdgeMaxError(float error);
  113. /// Set detail sampling distance.
  114. void SetDetailSampleDistance(float distance);
  115. /// Set detail sampling maximum error.
  116. void SetDetailSampleMaxError(float error);
  117. /// Set padding of the navigation mesh bounding box. Having enough padding allows to add geometry on the extremities of the navigation mesh when doing partial rebuilds.
  118. void SetPadding(const Vector3& padding);
  119. /// Set the cost of an area.
  120. void SetAreaCost(unsigned areaID, float cost);
  121. /// Allocate the navigation mesh without building any tiles. Bounding box is not padded. Return true if successful.
  122. virtual bool Allocate(const BoundingBox& boundingBox, unsigned maxTiles);
  123. /// Rebuild the navigation mesh. Return true if successful.
  124. virtual bool Build();
  125. /// Rebuild part of the navigation mesh contained by the world-space bounding box. Return true if successful.
  126. virtual bool Build(const BoundingBox& boundingBox);
  127. /// Rebuild part of the navigation mesh in the rectangular area. Return true if successful.
  128. virtual bool Build(const IntVector2& from, const IntVector2& to);
  129. /// Return tile data.
  130. virtual PODVector<unsigned char> GetTileData(const IntVector2& tile) const;
  131. /// Add tile to navigation mesh.
  132. virtual bool AddTile(const PODVector<unsigned char>& tileData);
  133. /// Remove tile from navigation mesh.
  134. virtual void RemoveTile(const IntVector2& tile);
  135. /// Remove all tiles from navigation mesh.
  136. virtual void RemoveAllTiles();
  137. /// Return whether the navigation mesh has tile.
  138. bool HasTile(const IntVector2& tile) const;
  139. /// Return bounding box of the tile in the node space.
  140. BoundingBox GetTileBoundingBox(const IntVector2& tile) const;
  141. /// Return index of the tile at the position.
  142. IntVector2 GetTileIndex(const Vector3& position) const;
  143. /// Find the nearest point on the navigation mesh to a given point. Extents specifies how far out from the specified point to check along each axis.
  144. Vector3 FindNearestPoint
  145. (const Vector3& point, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = nullptr, dtPolyRef* nearestRef = nullptr);
  146. /// Try to move along the surface from one point to another.
  147. Vector3 MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE, int maxVisited = 3,
  148. const dtQueryFilter* filter = nullptr);
  149. /// Find a path between world space points. Return non-empty list of points if successful. Extents specifies how far off the navigation mesh the points can be.
  150. void FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE,
  151. const dtQueryFilter* filter = nullptr);
  152. /// Find a path between world space points. Return non-empty list of navigation path points if successful. Extents specifies how far off the navigation mesh the points can be.
  153. void FindPath
  154. (PODVector<NavigationPathPoint>& dest, const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE,
  155. const dtQueryFilter* filter = nullptr);
  156. /// Return a random point on the navigation mesh.
  157. Vector3 GetRandomPoint(const dtQueryFilter* filter = nullptr, dtPolyRef* randomRef = nullptr);
  158. /// Return a random point on the navigation mesh within a circle. The circle radius is only a guideline and in practice the returned point may be further away.
  159. Vector3 GetRandomPointInCircle
  160. (const Vector3& center, float radius, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = nullptr,
  161. dtPolyRef* randomRef = nullptr);
  162. /// Return distance to wall from a point. Maximum search radius must be specified.
  163. float GetDistanceToWall
  164. (const Vector3& point, float radius, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = nullptr,
  165. Vector3* hitPos = nullptr, Vector3* hitNormal = nullptr);
  166. /// Perform a walkability raycast on the navigation mesh between start and end and return the point where a wall was hit, or the end point if no walls.
  167. Vector3 Raycast
  168. (const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = nullptr,
  169. Vector3* hitNormal = nullptr);
  170. /// Add debug geometry to the debug renderer.
  171. void DrawDebugGeometry(bool depthTest);
  172. /// Return the given name of this navigation mesh.
  173. String GetMeshName() const { return meshName_; }
  174. /// Set the name of this navigation mesh.
  175. void SetMeshName(const String& newName);
  176. /// Return tile size.
  177. int GetTileSize() const { return tileSize_; }
  178. /// Return cell size.
  179. float GetCellSize() const { return cellSize_; }
  180. /// Return cell height.
  181. float GetCellHeight() const { return cellHeight_; }
  182. /// Return navigation agent height.
  183. float GetAgentHeight() const { return agentHeight_; }
  184. /// Return navigation agent radius.
  185. float GetAgentRadius() const { return agentRadius_; }
  186. /// Return navigation agent max vertical climb.
  187. float GetAgentMaxClimb() const { return agentMaxClimb_; }
  188. /// Return navigation agent max slope.
  189. float GetAgentMaxSlope() const { return agentMaxSlope_; }
  190. /// Return region minimum size.
  191. float GetRegionMinSize() const { return regionMinSize_; }
  192. /// Return region merge size.
  193. float GetRegionMergeSize() const { return regionMergeSize_; }
  194. /// Return edge max length.
  195. float GetEdgeMaxLength() const { return edgeMaxLength_; }
  196. /// Return edge max error.
  197. float GetEdgeMaxError() const { return edgeMaxError_; }
  198. /// Return detail sampling distance.
  199. float GetDetailSampleDistance() const { return detailSampleDistance_; }
  200. /// Return detail sampling maximum error.
  201. float GetDetailSampleMaxError() const { return detailSampleMaxError_; }
  202. /// Return navigation mesh bounding box padding.
  203. const Vector3& GetPadding() const { return padding_; }
  204. /// Get the current cost of an area.
  205. float GetAreaCost(unsigned areaID) const;
  206. /// Return whether has been initialized with valid navigation data.
  207. bool IsInitialized() const { return navMesh_ != nullptr; }
  208. /// Return local space bounding box of the navigation mesh.
  209. const BoundingBox& GetBoundingBox() const { return boundingBox_; }
  210. /// Return world space bounding box of the navigation mesh.
  211. BoundingBox GetWorldBoundingBox() const;
  212. /// Return number of tiles.
  213. IntVector2 GetNumTiles() const { return IntVector2(numTilesX_, numTilesZ_); }
  214. /// Set the partition type used for polygon generation.
  215. void SetPartitionType(NavmeshPartitionType partitionType);
  216. /// Return Partition Type.
  217. NavmeshPartitionType GetPartitionType() const { return partitionType_; }
  218. /// Set navigation data attribute.
  219. virtual void SetNavigationDataAttr(const PODVector<unsigned char>& value);
  220. /// Return navigation data attribute.
  221. virtual PODVector<unsigned char> GetNavigationDataAttr() const;
  222. /// Draw debug geometry for OffMeshConnection components.
  223. void SetDrawOffMeshConnections(bool enable) { drawOffMeshConnections_ = enable; }
  224. /// Return whether to draw OffMeshConnection components.
  225. bool GetDrawOffMeshConnections() const { return drawOffMeshConnections_; }
  226. /// Draw debug geometry for NavArea components.
  227. void SetDrawNavAreas(bool enable) { drawNavAreas_ = enable; }
  228. /// Return whether to draw NavArea components.
  229. bool GetDrawNavAreas() const { return drawNavAreas_; }
  230. private:
  231. /// Write tile data.
  232. void WriteTile(Serializer& dest, int x, int z) const;
  233. /// Read tile data to the navigation mesh.
  234. bool ReadTile(Deserializer& source, bool silent);
  235. protected:
  236. /// Collect geometry from under Navigable components.
  237. void CollectGeometries(Vector<NavigationGeometryInfo>& geometryList);
  238. /// Visit nodes and collect navigable geometry.
  239. void CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive);
  240. /// Get geometry data within a bounding box.
  241. void GetTileGeometry(NavBuildData* build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box);
  242. /// Add a triangle mesh to the geometry data.
  243. void AddTriMeshGeometry(NavBuildData* build, Geometry* geometry, const Matrix3x4& transform);
  244. /// Build one tile of the navigation mesh. Return true if successful.
  245. virtual bool BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z);
  246. /// Build tiles in the rectangular area. Return number of built tiles.
  247. unsigned BuildTiles(Vector<NavigationGeometryInfo>& geometryList, const IntVector2& from, const IntVector2& to);
  248. /// Ensure that the navigation mesh query is initialized. Return true if successful.
  249. bool InitializeQuery();
  250. /// Release the navigation mesh and the query.
  251. virtual void ReleaseNavigationMesh();
  252. /// Identifying name for this navigation mesh.
  253. String meshName_;
  254. /// Detour navigation mesh.
  255. dtNavMesh* navMesh_;
  256. /// Detour navigation mesh query.
  257. dtNavMeshQuery* navMeshQuery_;
  258. /// Detour navigation mesh query filter.
  259. UniquePtr<dtQueryFilter> queryFilter_;
  260. /// Temporary data for finding a path.
  261. UniquePtr<FindPathData> pathData_;
  262. /// Tile size.
  263. int tileSize_;
  264. /// Cell size.
  265. float cellSize_;
  266. /// Cell height.
  267. float cellHeight_;
  268. /// Navigation agent height.
  269. float agentHeight_;
  270. /// Navigation agent radius.
  271. float agentRadius_;
  272. /// Navigation agent max vertical climb.
  273. float agentMaxClimb_;
  274. /// Navigation agent max slope.
  275. float agentMaxSlope_;
  276. /// Region minimum size.
  277. float regionMinSize_;
  278. /// Region merge size.
  279. float regionMergeSize_;
  280. /// Edge max length.
  281. float edgeMaxLength_;
  282. /// Edge max error.
  283. float edgeMaxError_;
  284. /// Detail sampling distance.
  285. float detailSampleDistance_;
  286. /// Detail sampling maximum error.
  287. float detailSampleMaxError_;
  288. /// Bounding box padding.
  289. Vector3 padding_;
  290. /// Number of tiles in X direction.
  291. int numTilesX_;
  292. /// Number of tiles in Z direction.
  293. int numTilesZ_;
  294. /// Whole navigation mesh bounding box.
  295. BoundingBox boundingBox_;
  296. /// Type of the heightfield partitioning.
  297. NavmeshPartitionType partitionType_;
  298. /// Keep internal build resources for debug draw modes.
  299. bool keepInterResults_;
  300. /// Debug draw OffMeshConnection components.
  301. bool drawOffMeshConnections_;
  302. /// Debug draw NavArea components.
  303. bool drawNavAreas_;
  304. /// NavAreas for this NavMesh.
  305. Vector<WeakPtr<NavArea> > areas_;
  306. };
  307. /// Register Navigation library objects.
  308. void URHO3D_API RegisterNavigationLibrary(Context* context);
  309. }