navMesh.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2014 Daniel Buckmaster
  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
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell 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
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _NAVMESH_H_
  23. #define _NAVMESH_H_
  24. #include <queue>
  25. #include "scene/sceneObject.h"
  26. #include "collision/concretePolyList.h"
  27. #include "recastPolyList.h"
  28. #include "util/messaging/eventManager.h"
  29. #include "torqueRecast.h"
  30. #include "duDebugDrawTorque.h"
  31. #include "coverPoint.h"
  32. #include <Recast.h>
  33. #include <DetourNavMesh.h>
  34. #include <DetourNavMeshBuilder.h>
  35. #include <DebugDraw.h>
  36. #include <DetourNavMeshQuery.h>
  37. /// @class NavMesh
  38. /// Represents a set of bounds within which a Recast navigation mesh is generated.
  39. /// @see NavMeshPolyList
  40. /// @see Trigger
  41. class NavMesh : public SceneObject {
  42. typedef SceneObject Parent;
  43. friend class NavPath;
  44. public:
  45. /// @name NavMesh build
  46. /// @{
  47. /// Initiates the navmesh build process, which includes notifying the
  48. /// clients and posting an event.
  49. bool build(bool background = true, bool saveIntermediates = false);
  50. /// Stop a build in progress.
  51. void cancelBuild();
  52. /// Generate cover points from a nav mesh.
  53. bool createCoverPoints();
  54. /// Remove all cover points
  55. void deleteCoverPoints();
  56. /// Save the navmesh to a file.
  57. bool save();
  58. /// Load a saved navmesh from a file.
  59. bool load();
  60. /// Instantly rebuild the tiles in the navmesh that overlap the box.
  61. void buildTiles(const Box3F &box);
  62. /// Instantly rebuild a specific tile.
  63. void buildTile(const U32 &tile);
  64. /// Rebuild parts of the navmesh where links have changed.
  65. void buildLinks();
  66. /// Data file to store this nav mesh in. (From engine executable dir.)
  67. StringTableEntry mFileName;
  68. /// Name of the SimSet to store cover points in. (Usually a SimGroup.)
  69. StringTableEntry mCoverSet;
  70. /// Cell width and height.
  71. F32 mCellSize, mCellHeight;
  72. /// @name Actor data
  73. /// @{
  74. F32 mWalkableHeight,
  75. mWalkableClimb,
  76. mWalkableRadius,
  77. mWalkableSlope;
  78. /// @}
  79. /// @name Generation data
  80. /// @{
  81. U32 mBorderSize;
  82. F32 mDetailSampleDist, mDetailSampleMaxError;
  83. U32 mMaxEdgeLen;
  84. F32 mMaxSimplificationError;
  85. static const U32 mMaxVertsPerPoly;
  86. U32 mMinRegionArea;
  87. U32 mMergeRegionArea;
  88. F32 mTileSize;
  89. U32 mMaxPolysPerTile;
  90. duDebugDrawTorque mDbgDraw;
  91. /// @}
  92. /// @name Water
  93. /// @{
  94. enum WaterMethod {
  95. Ignore,
  96. Solid,
  97. Impassable
  98. };
  99. enum DrawMode
  100. {
  101. DRAWMODE_NAVMESH,
  102. DRAWMODE_NAVMESH_TRANS,
  103. DRAWMODE_NAVMESH_BVTREE,
  104. DRAWMODE_NAVMESH_NODES,
  105. DRAWMODE_NAVMESH_PORTALS,
  106. DRAWMODE_NAVMESH_INVIS,
  107. DRAWMODE_MESH,
  108. DRAWMODE_VOXELS,
  109. DRAWMODE_VOXELS_WALKABLE,
  110. DRAWMODE_COMPACT,
  111. DRAWMODE_COMPACT_DISTANCE,
  112. DRAWMODE_COMPACT_REGIONS,
  113. DRAWMODE_REGION_CONNECTIONS,
  114. DRAWMODE_RAW_CONTOURS,
  115. DRAWMODE_BOTH_CONTOURS,
  116. DRAWMODE_CONTOURS,
  117. DRAWMODE_POLYMESH,
  118. DRAWMODE_POLYMESH_DETAIL,
  119. MAX_DRAWMODE
  120. };
  121. WaterMethod mWaterMethod;
  122. /// @}
  123. /// @}
  124. /// Return the index of the tile included by this point.
  125. S32 getTile(const Point3F& pos);
  126. /// Return the box of a given tile.
  127. Box3F getTileBox(U32 id);
  128. /// @name Links
  129. /// @{
  130. /// Add an off-mesh link.
  131. S32 addLink(const Point3F &from, const Point3F &to, bool biDir, F32 rad, U32 flags = 0);
  132. /// Get the ID of the off-mesh link near the point.
  133. S32 getLink(const Point3F &pos);
  134. /// Get the number of links this mesh has.
  135. S32 getLinkCount();
  136. /// Get the starting point of a link.
  137. Point3F getLinkStart(U32 idx);
  138. /// Get the ending point of a link.
  139. Point3F getLinkEnd(U32 idx);
  140. /// Get the flags used by a link.
  141. LinkData getLinkFlags(U32 idx);
  142. bool getLinkDir(U32 idx);
  143. F32 getLinkRadius(U32 idx);
  144. void setLinkDir(U32 idx, bool biDir);
  145. void setLinkRadius(U32 idx, F32 rad);
  146. /// Set flags used by a link.
  147. void setLinkFlags(U32 idx, const LinkData &d);
  148. void setDrawMode(DrawMode mode) { m_drawMode = mode; setMaskBits(LoadFlag); }
  149. /// Set the selected state of a link.
  150. void selectLink(U32 idx, bool select, bool hover = true);
  151. /// Delete the selected link.
  152. void deleteLink(U32 idx);
  153. dtNavMeshQuery* getNavMeshQuery() { return mQuery; }
  154. /// @}
  155. /// Should small characters use this mesh?
  156. bool mSmallCharacters;
  157. /// Should regular-sized characters use this mesh?
  158. bool mRegularCharacters;
  159. /// Should large characters use this mesh?
  160. bool mLargeCharacters;
  161. /// Should vehicles use this mesh?
  162. bool mVehicles;
  163. /// @name Annotations
  164. /// @{
  165. /* not implemented
  166. /// Should we automatically generate jump-down links?
  167. bool mJumpDownLinks;
  168. /// Height of a 'small' jump link.
  169. F32 mJumpLinkSmall;
  170. /// Height of a 'large' jump link.
  171. F32 mJumpLinkLarge;
  172. */
  173. /// Distance to search for cover.
  174. F32 mCoverDist;
  175. /// Distance to search horizontally when peeking around cover.
  176. F32 mPeekDist;
  177. /// Add cover to walls that don't have corners?
  178. bool mInnerCover;
  179. /// @}
  180. /// @name SimObject
  181. /// @{
  182. void onEditorEnable() override;
  183. void onEditorDisable() override;
  184. void write(Stream &stream, U32 tabStop, U32 flags) override;
  185. /// @}
  186. /// @name SceneObject
  187. /// @{
  188. static void initPersistFields();
  189. bool onAdd() override;
  190. void onRemove() override;
  191. enum flags {
  192. BuildFlag = Parent::NextFreeMask << 0,
  193. LoadFlag = Parent::NextFreeMask << 1,
  194. NextFreeMask = Parent::NextFreeMask << 2,
  195. };
  196. U32 packUpdate(NetConnection *conn, U32 mask, BitStream *stream) override;
  197. void unpackUpdate(NetConnection *conn, BitStream *stream) override;
  198. void setTransform(const MatrixF &mat) override;
  199. void setScale(const VectorF &scale) override;
  200. /// @}
  201. /// @name ProcessObject
  202. /// @{
  203. void processTick(const Move *move) override;
  204. /// @}
  205. /// @name Rendering
  206. /// @{
  207. void prepRenderImage(SceneRenderState *state) override;
  208. void render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat);
  209. void renderLinks(duDebugDraw &dd);
  210. void renderSearch(duDebugDraw& dd);
  211. void renderTileData(duDebugDrawTorque &dd, U32 tile);
  212. bool mAlwaysRender;
  213. /// @}
  214. NavMesh();
  215. ~NavMesh();
  216. DECLARE_CONOBJECT(NavMesh);
  217. DECLARE_CATEGORY("Navigation");
  218. /// Return the server-side NavMesh SimSet.
  219. static SimSet *getServerSet();
  220. /// Return the EventManager for all NavMeshes.
  221. static EventManager *getEventManager();
  222. void inspectPostApply() override;
  223. void createNewFile();
  224. protected:
  225. dtNavMesh const* getNavMesh() { return nm; }
  226. private:
  227. /// Builds the next tile in the dirty list.
  228. void buildNextTile();
  229. /// Save imtermediate navmesh creation data?
  230. bool mSaveIntermediates;
  231. /// @name Tiles
  232. /// @{
  233. struct Tile {
  234. /// Torque-space world box of this tile.
  235. Box3F box;
  236. /// Local coordinates of this box.
  237. U32 x, y;
  238. /// Recast min and max points.
  239. F32 bmin[3], bmax[3];
  240. /// Default constructor.
  241. Tile() : box(Box3F::Invalid), x(0), y(0), chf(0), solid(0), cset(0), pmesh(0), dmesh(0), triareas(nullptr)
  242. {
  243. bmin[0] = bmin[1] = bmin[2] = bmax[0] = bmax[1] = bmax[2] = 0.0f;
  244. }
  245. /// Value constructor.
  246. Tile(const Box3F &b, U32 _x, U32 _y, const F32 *min, const F32 *max)
  247. : box(b), x(_x), y(_y), chf(0), solid(0), cset(0), pmesh(0), dmesh(0), triareas(nullptr)
  248. {
  249. rcVcopy(bmin, min);
  250. rcVcopy(bmax, max);
  251. }
  252. ~Tile()
  253. {
  254. if (chf)
  255. delete chf;
  256. if (cset)
  257. delete cset;
  258. if (solid)
  259. delete solid;
  260. if (pmesh)
  261. delete pmesh;
  262. if (dmesh)
  263. delete dmesh;
  264. if (triareas)
  265. delete[] triareas;
  266. }
  267. unsigned char* triareas;
  268. rcCompactHeightfield* chf;
  269. rcHeightfield* solid;
  270. rcContourSet* cset;
  271. rcPolyMesh* pmesh;
  272. rcPolyMeshDetail* dmesh;
  273. };
  274. /// List of tiles.
  275. Vector<Tile> mTiles;
  276. /// List of indices to the tile array which are dirty.
  277. Vector<U32> mDirtyTiles;
  278. /// Update tile dimensions.
  279. void updateTiles(bool dirty = false);
  280. /// Generates navmesh data for a single tile.
  281. unsigned char *buildTileData(const Tile &tile, U32 &dataSize);
  282. /// @}
  283. /// @name Off-mesh links
  284. /// @{
  285. enum SelectState {
  286. Unselected,
  287. Hovered,
  288. Selected
  289. };
  290. Vector<F32> mLinkVerts; ///< Coordinates of each link vertex
  291. Vector<bool> mLinksUnsynced; ///< Are the editor links unsynced from the mesh?
  292. Vector<F32> mLinkRads; ///< Radius of each link
  293. Vector<U8> mLinkDirs; ///< Direction (one-way or bidirectional)
  294. Vector<U8> mLinkAreas; ///< Area ID
  295. Vector<U16> mLinkFlags; ///< Flags
  296. Vector<U32> mLinkIDs; ///< ID number of each link
  297. Vector<U8> mLinkSelectStates; ///< Selection state of links
  298. Vector<bool> mDeleteLinks; ///< Link will be deleted next build.
  299. U32 mCurLinkID;
  300. void eraseLink(U32 idx);
  301. void eraseLinks();
  302. void setLinkCount(U32 c);
  303. /// @}
  304. dtNavMesh *nm;
  305. rcContext *ctx;
  306. dtNavMeshQuery* mQuery;
  307. /// @name Cover
  308. /// @{
  309. struct CoverPointData {
  310. MatrixF trans;
  311. CoverPoint::Size size;
  312. bool peek[3];
  313. };
  314. /// Attempt to place cover points along a given edge.
  315. bool testEdgeCover(const Point3F &pos, const VectorF &dir, CoverPointData &data);
  316. /// @}
  317. /// Used to perform non-standard validation. detailSampleDist can be 0, or >= 0.9.
  318. static bool setProtectedDetailSampleDist(void *obj, const char *index, const char *data);
  319. /// Updates the client when we check the alwaysRender option.
  320. static bool setProtectedAlwaysRender(void *obj, const char *index, const char *data);
  321. /// @name Threaded updates
  322. /// @{
  323. /// A simple flag to say we are building.
  324. bool mBuilding;
  325. /// @}
  326. /// @name Rendering
  327. /// @{
  328. void renderToDrawer();
  329. /// @}
  330. /// Server-side set for all NavMesh objects.
  331. static SimObjectPtr<SimSet> smServerSet;
  332. /// Use this object to manage update events.
  333. static SimObjectPtr<EventManager> smEventManager;
  334. protected:
  335. RecastPolyList* m_geo;
  336. unsigned char* m_triareas;
  337. rcHeightfield* m_solid;
  338. rcCompactHeightfield* m_chf;
  339. rcContourSet* m_cset;
  340. rcPolyMesh* m_pmesh;
  341. rcPolyMeshDetail* m_dmesh;
  342. rcConfig m_cfg;
  343. DrawMode m_drawMode;
  344. U32 mWaterVertStart;
  345. U32 mWaterTriStart;
  346. void cleanup();
  347. };
  348. typedef NavMesh::WaterMethod NavMeshWaterMethod;
  349. DefineEnumType(NavMeshWaterMethod);
  350. #endif