NavigationMesh.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. //
  2. // Copyright (c) 2008-2017 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. #pragma once
  23. #include "../Container/ArrayPtr.h"
  24. #include "../Container/HashSet.h"
  25. #include "../Math/BoundingBox.h"
  26. #include "../Math/Matrix3x4.h"
  27. #include "../Scene/Component.h"
  28. #ifdef DT_POLYREF64
  29. typedef uint64_t dtPolyRef;
  30. #else
  31. typedef unsigned int dtPolyRef;
  32. #endif
  33. class dtNavMesh;
  34. class dtNavMeshQuery;
  35. class dtQueryFilter;
  36. namespace Atomic
  37. {
  38. enum NavmeshPartitionType
  39. {
  40. NAVMESH_PARTITION_WATERSHED = 0,
  41. NAVMESH_PARTITION_MONOTONE
  42. };
  43. class Geometry;
  44. class NavArea;
  45. struct FindPathData;
  46. struct NavBuildData;
  47. /// Description of a navigation mesh geometry component, with transform and bounds information.
  48. struct NavigationGeometryInfo
  49. {
  50. /// Component.
  51. Component* component_;
  52. /// Geometry LOD level if applicable.
  53. unsigned lodLevel_;
  54. /// Transform relative to the navigation mesh root node.
  55. Matrix3x4 transform_;
  56. /// Bounding box relative to the navigation mesh root node.
  57. BoundingBox boundingBox_;
  58. };
  59. /// A flag representing the type of path point- none, the start of a path segment, the end of one, or an off-mesh connection.
  60. enum NavigationPathPointFlag
  61. {
  62. NAVPATHFLAG_NONE = 0,
  63. NAVPATHFLAG_START = 0x01,
  64. NAVPATHFLAG_END = 0x02,
  65. NAVPATHFLAG_OFF_MESH = 0x04
  66. };
  67. struct ATOMIC_API NavigationPathPoint
  68. {
  69. /// World-space position of the path point.
  70. Vector3 position_;
  71. /// Detour flag.
  72. NavigationPathPointFlag flag_;
  73. /// Detour area ID.
  74. unsigned char areaID_;
  75. };
  76. /// Navigation mesh component. Collects the navigation geometry from child nodes with the Navigable component and responds to path queries.
  77. class ATOMIC_API NavigationMesh : public Component
  78. {
  79. ATOMIC_OBJECT(NavigationMesh, Component);
  80. friend class CrowdManager;
  81. public:
  82. /// Construct.
  83. NavigationMesh(Context* context);
  84. /// Destruct.
  85. virtual ~NavigationMesh();
  86. /// Register object factory.
  87. static void RegisterObject(Context* context);
  88. /// Visualize the component as debug geometry.
  89. virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);
  90. /// Set tile size.
  91. void SetTileSize(int size);
  92. /// Set cell size.
  93. void SetCellSize(float size);
  94. /// Set cell height.
  95. void SetCellHeight(float height);
  96. /// Set navigation agent height.
  97. void SetAgentHeight(float height);
  98. /// Set navigation agent radius.
  99. void SetAgentRadius(float radius);
  100. /// Set navigation agent max vertical climb.
  101. void SetAgentMaxClimb(float maxClimb);
  102. /// Set navigation agent max slope.
  103. void SetAgentMaxSlope(float maxSlope);
  104. /// Set region minimum size.
  105. void SetRegionMinSize(float size);
  106. /// Set region merge size.
  107. void SetRegionMergeSize(float size);
  108. /// Set edge max length.
  109. void SetEdgeMaxLength(float length);
  110. /// Set edge max error.
  111. void SetEdgeMaxError(float error);
  112. /// Set detail sampling distance.
  113. void SetDetailSampleDistance(float distance);
  114. /// Set detail sampling maximum error.
  115. void SetDetailSampleMaxError(float error);
  116. /// 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.
  117. void SetPadding(const Vector3& padding);
  118. /// Set the cost of an area.
  119. void SetAreaCost(unsigned areaID, float cost);
  120. /// Allocate the navigation mesh without building any tiles. Bounding box is not padded. Return true if successful.
  121. virtual bool Allocate(const BoundingBox& boundingBox, unsigned maxTiles);
  122. /// Rebuild the navigation mesh. Return true if successful.
  123. virtual bool Build();
  124. /// Rebuild part of the navigation mesh contained by the world-space bounding box. Return true if successful.
  125. virtual bool Build(const BoundingBox& boundingBox);
  126. /// Rebuild part of the navigation mesh in the rectangular area. Return true if successful.
  127. virtual bool Build(const IntVector2& from, const IntVector2& to);
  128. /// Return tile data.
  129. virtual PODVector<unsigned char> GetTileData(const IntVector2& tile) const;
  130. /// Add tile to navigation mesh.
  131. virtual bool AddTile(const PODVector<unsigned char>& tileData);
  132. /// Remove tile from navigation mesh.
  133. virtual void RemoveTile(const IntVector2& tile);
  134. /// Remove all tiles from navigation mesh.
  135. virtual void RemoveAllTiles();
  136. /// Return whether the navigation mesh has tile.
  137. bool HasTile(const IntVector2& tile) const;
  138. /// Return bounding box of the tile in the node space.
  139. BoundingBox GetTileBoudningBox(const IntVector2& tile) const;
  140. /// Return index of the tile at the position.
  141. IntVector2 GetTileIndex(const Vector3& position) const;
  142. /// 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.
  143. Vector3 FindNearestPoint
  144. (const Vector3& point, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = 0, dtPolyRef* nearestRef = 0);
  145. /// Try to move along the surface from one point to another.
  146. Vector3 MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE, int maxVisited = 3,
  147. const dtQueryFilter* filter = 0);
  148. /// 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.
  149. void FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE,
  150. const dtQueryFilter* filter = 0);
  151. /// 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.
  152. void FindPath
  153. (PODVector<NavigationPathPoint>& dest, const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE,
  154. const dtQueryFilter* filter = 0);
  155. /// Return a random point on the navigation mesh.
  156. Vector3 GetRandomPoint(const dtQueryFilter* filter = 0, dtPolyRef* randomRef = 0);
  157. /// 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.
  158. Vector3 GetRandomPointInCircle
  159. (const Vector3& center, float radius, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = 0,
  160. dtPolyRef* randomRef = 0);
  161. /// Return distance to wall from a point. Maximum search radius must be specified.
  162. float GetDistanceToWall
  163. (const Vector3& point, float radius, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = 0,
  164. Vector3* hitPos = 0, Vector3* hitNormal = 0);
  165. /// 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.
  166. Vector3 Raycast
  167. (const Vector3& start, const Vector3& end, const Vector3& extents = Vector3::ONE, const dtQueryFilter* filter = 0,
  168. Vector3* hitNormal = 0);
  169. /// Add debug geometry to the debug renderer.
  170. void DrawDebugGeometry(bool depthTest);
  171. /// Return the given name of this navigation mesh.
  172. String GetMeshName() const { return meshName_; }
  173. /// Set the name of this navigation mesh.
  174. void SetMeshName(const String& newName);
  175. /// Return tile size.
  176. int GetTileSize() const { return tileSize_; }
  177. /// Return cell size.
  178. float GetCellSize() const { return cellSize_; }
  179. /// Return cell height.
  180. float GetCellHeight() const { return cellHeight_; }
  181. /// Return navigation agent height.
  182. float GetAgentHeight() const { return agentHeight_; }
  183. /// Return navigation agent radius.
  184. float GetAgentRadius() const { return agentRadius_; }
  185. /// Return navigation agent max vertical climb.
  186. float GetAgentMaxClimb() const { return agentMaxClimb_; }
  187. /// Return navigation agent max slope.
  188. float GetAgentMaxSlope() const { return agentMaxSlope_; }
  189. /// Return region minimum size.
  190. float GetRegionMinSize() const { return regionMinSize_; }
  191. /// Return region merge size.
  192. float GetRegionMergeSize() const { return regionMergeSize_; }
  193. /// Return edge max length.
  194. float GetEdgeMaxLength() const { return edgeMaxLength_; }
  195. /// Return edge max error.
  196. float GetEdgeMaxError() const { return edgeMaxError_; }
  197. /// Return detail sampling distance.
  198. float GetDetailSampleDistance() const { return detailSampleDistance_; }
  199. /// Return detail sampling maximum error.
  200. float GetDetailSampleMaxError() const { return detailSampleMaxError_; }
  201. /// Return navigation mesh bounding box padding.
  202. const Vector3& GetPadding() const { return padding_; }
  203. /// Get the current cost of an area
  204. float GetAreaCost(unsigned areaID) const;
  205. /// Return whether has been initialized with valid navigation data.
  206. bool IsInitialized() const { return navMesh_ != 0; }
  207. /// Return local space bounding box of the navigation mesh.
  208. const BoundingBox& GetBoundingBox() const { return boundingBox_; }
  209. /// Return world space bounding box of the navigation mesh.
  210. BoundingBox GetWorldBoundingBox() const;
  211. /// Return number of tiles.
  212. IntVector2 GetNumTiles() const { return IntVector2(numTilesX_, numTilesZ_); }
  213. /// Set the partition type used for polygon generation.
  214. void SetPartitionType(NavmeshPartitionType aType);
  215. /// Return Partition Type.
  216. NavmeshPartitionType GetPartitionType() const { return partitionType_; }
  217. /// Set navigation data attribute.
  218. virtual void SetNavigationDataAttr(const PODVector<unsigned char>& value);
  219. /// Return navigation data attribute.
  220. virtual PODVector<unsigned char> GetNavigationDataAttr() const;
  221. /// Draw debug geometry for OffMeshConnection components.
  222. void SetDrawOffMeshConnections(bool enable) { drawOffMeshConnections_ = enable; }
  223. /// Return whether to draw OffMeshConnection components.
  224. bool GetDrawOffMeshConnections() const { return drawOffMeshConnections_; }
  225. /// Draw debug geometry for NavArea components.
  226. void SetDrawNavAreas(bool enable) { drawNavAreas_ = enable; }
  227. /// Return whether to draw NavArea components.
  228. bool GetDrawNavAreas() const { return drawNavAreas_; }
  229. private:
  230. /// Write tile data.
  231. void WriteTile(Serializer& dest, int x, int z) const;
  232. /// Read tile data to the navigation mesh.
  233. bool ReadTile(Deserializer& source, bool silent);
  234. protected:
  235. /// Collect geometry from under Navigable components.
  236. void CollectGeometries(Vector<NavigationGeometryInfo>& geometryList);
  237. /// Visit nodes and collect navigable geometry.
  238. void CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive);
  239. /// Get geometry data within a bounding box.
  240. void GetTileGeometry(NavBuildData* build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box);
  241. /// Add a triangle mesh to the geometry data.
  242. void AddTriMeshGeometry(NavBuildData* build, Geometry* geometry, const Matrix3x4& transform);
  243. /// Build one tile of the navigation mesh. Return true if successful.
  244. virtual bool BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z);
  245. /// Build tiles in the rectangular area. Return number of built tiles.
  246. unsigned BuildTiles(Vector<NavigationGeometryInfo>& geometryList, const IntVector2& from, const IntVector2& to);
  247. /// Ensure that the navigation mesh query is initialized. Return true if successful.
  248. bool InitializeQuery();
  249. /// Release the navigation mesh and the query.
  250. virtual void ReleaseNavigationMesh();
  251. /// Identifying name for this navigation mesh.
  252. String meshName_;
  253. /// Detour navigation mesh.
  254. dtNavMesh* navMesh_;
  255. /// Detour navigation mesh query.
  256. dtNavMeshQuery* navMeshQuery_;
  257. /// Detour navigation mesh query filter.
  258. UniquePtr<dtQueryFilter> queryFilter_;
  259. /// Temporary data for finding a path.
  260. UniquePtr<FindPathData> pathData_;
  261. /// Tile size.
  262. int tileSize_;
  263. /// Cell size.
  264. float cellSize_;
  265. /// Cell height.
  266. float cellHeight_;
  267. /// Navigation agent height.
  268. float agentHeight_;
  269. /// Navigation agent radius.
  270. float agentRadius_;
  271. /// Navigation agent max vertical climb.
  272. float agentMaxClimb_;
  273. /// Navigation agent max slope.
  274. float agentMaxSlope_;
  275. /// Region minimum size.
  276. float regionMinSize_;
  277. /// Region merge size.
  278. float regionMergeSize_;
  279. /// Edge max length.
  280. float edgeMaxLength_;
  281. /// Edge max error.
  282. float edgeMaxError_;
  283. /// Detail sampling distance.
  284. float detailSampleDistance_;
  285. /// Detail sampling maximum error.
  286. float detailSampleMaxError_;
  287. /// Bounding box padding.
  288. Vector3 padding_;
  289. /// Number of tiles in X direction.
  290. int numTilesX_;
  291. /// Number of tiles in Z direction.
  292. int numTilesZ_;
  293. /// Whole navigation mesh bounding box.
  294. BoundingBox boundingBox_;
  295. /// Type of the heightfield partitioning.
  296. NavmeshPartitionType partitionType_;
  297. /// Keep internal build resources for debug draw modes.
  298. bool keepInterResults_;
  299. /// Debug draw OffMeshConnection components.
  300. bool drawOffMeshConnections_;
  301. /// Debug draw NavArea components.
  302. bool drawNavAreas_;
  303. /// NavAreas for this NavMesh
  304. Vector<WeakPtr<NavArea> > areas_;
  305. };
  306. /// Register Navigation library objects.
  307. void ATOMIC_API RegisterNavigationLibrary(Context* context);
  308. }