NavigationMesh.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. //
  2. // Copyright (c) 2008-2013 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. #include "Precompiled.h"
  23. #include "CollisionShape.h"
  24. #include "Context.h"
  25. #include "DebugRenderer.h"
  26. #include "Drawable.h"
  27. #include "Geometry.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "Navigable.h"
  31. #include "NavigationMesh.h"
  32. #include "Profiler.h"
  33. #include "Scene.h"
  34. #include "StaticModel.h"
  35. #include "TerrainPatch.h"
  36. #include "VectorBuffer.h"
  37. #include <DetourNavMesh.h>
  38. #include <DetourNavMeshBuilder.h>
  39. #include <DetourNavMeshQuery.h>
  40. #include <Recast.h>
  41. #include "DebugNew.h"
  42. namespace Urho3D
  43. {
  44. static const int DEFAULT_TILE_SIZE = 128;
  45. static const float DEFAULT_CELL_SIZE = 0.3f;
  46. static const float DEFAULT_CELL_HEIGHT = 0.2f;
  47. static const float DEFAULT_AGENT_HEIGHT = 2.0f;
  48. static const float DEFAULT_AGENT_RADIUS = 0.6f;
  49. static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
  50. static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
  51. static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
  52. static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
  53. static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
  54. static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
  55. static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
  56. static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
  57. static const int MAX_POLYS = 2048;
  58. /// Temporary data for building one tile of the navigation mesh.
  59. struct NavigationBuildData
  60. {
  61. /// Construct.
  62. NavigationBuildData() :
  63. ctx_(new rcContext(false)),
  64. heightField_(0),
  65. compactHeightField_(0),
  66. contourSet_(0),
  67. polyMesh_(0),
  68. polyMeshDetail_(0)
  69. {
  70. }
  71. /// Destruct.
  72. ~NavigationBuildData()
  73. {
  74. delete(ctx_);
  75. rcFreeHeightField(heightField_);
  76. rcFreeCompactHeightfield(compactHeightField_);
  77. rcFreeContourSet(contourSet_);
  78. rcFreePolyMesh(polyMesh_);
  79. rcFreePolyMeshDetail(polyMeshDetail_);
  80. ctx_ = 0;
  81. heightField_ = 0;
  82. compactHeightField_ = 0;
  83. contourSet_ = 0;
  84. polyMesh_ = 0;
  85. polyMeshDetail_ = 0;
  86. }
  87. /// World-space bounding box of the navigation mesh tile.
  88. BoundingBox worldBoundingBox_;
  89. /// Vertices from geometries.
  90. PODVector<Vector3> vertices_;
  91. /// Triangle indices from geometries.
  92. PODVector<int> indices_;
  93. /// Recast context.
  94. rcContext* ctx_;
  95. /// Recast heightfield.
  96. rcHeightfield* heightField_;
  97. /// Recast compact heightfield.
  98. rcCompactHeightfield* compactHeightField_;
  99. /// Recast contour set.
  100. rcContourSet* contourSet_;
  101. /// Recast poly mesh.
  102. rcPolyMesh* polyMesh_;
  103. /// Recast detail poly mesh.
  104. rcPolyMeshDetail* polyMeshDetail_;
  105. };
  106. /// Temporary data for finding a path.
  107. struct FindPathData
  108. {
  109. // Polygons.
  110. dtPolyRef polys_[MAX_POLYS];
  111. // Polygons on the path.
  112. dtPolyRef pathPolys_[MAX_POLYS];
  113. // Points on the path.
  114. Vector3 pathPoints_[MAX_POLYS];
  115. // Flags on the path.
  116. unsigned char pathFlags_[MAX_POLYS];
  117. };
  118. OBJECTTYPESTATIC(NavigationMesh);
  119. NavigationMesh::NavigationMesh(Context* context) :
  120. Component(context),
  121. navMesh_(0),
  122. navMeshQuery_(0),
  123. queryFilter_(new dtQueryFilter()),
  124. pathData_(new FindPathData()),
  125. tileSize_(DEFAULT_TILE_SIZE),
  126. cellSize_(DEFAULT_CELL_SIZE),
  127. cellHeight_(DEFAULT_CELL_HEIGHT),
  128. agentHeight_(DEFAULT_AGENT_HEIGHT),
  129. agentRadius_(DEFAULT_AGENT_RADIUS),
  130. agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),
  131. agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),
  132. regionMinSize_(DEFAULT_REGION_MIN_SIZE),
  133. regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),
  134. edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),
  135. edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),
  136. detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),
  137. detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),
  138. numTilesX_(0),
  139. numTilesZ_(0)
  140. {
  141. }
  142. NavigationMesh::~NavigationMesh()
  143. {
  144. ReleaseNavigationMesh();
  145. delete queryFilter_;
  146. queryFilter_ = 0;
  147. delete pathData_;
  148. pathData_ = 0;
  149. }
  150. void NavigationMesh::RegisterObject(Context* context)
  151. {
  152. context->RegisterFactory<NavigationMesh>();
  153. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_INT, "Tile Size", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);
  154. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  155. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  156. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  157. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  158. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  159. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  160. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  161. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  162. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  163. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  164. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float, DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  165. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_FLOAT, "Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float, DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  166. ACCESSOR_ATTRIBUTE(NavigationMesh, VAR_BUFFER, "Navigation Data", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>, Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  167. }
  168. void NavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  169. {
  170. if (!navMesh_ || !node_)
  171. return;
  172. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  173. const dtNavMesh* navMesh = navMesh_;
  174. for (int z = 0; z < numTilesZ_; ++z)
  175. {
  176. for (int x = 0; x < numTilesX_; ++x)
  177. {
  178. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  179. if (!tile)
  180. continue;
  181. for (int i = 0; i < tile->header->polyCount; ++i)
  182. {
  183. dtPoly* poly = tile->polys + i;
  184. for (unsigned j = 0; j < poly->vertCount; ++j)
  185. {
  186. debug->AddLine(
  187. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  188. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  189. Color::YELLOW,
  190. depthTest
  191. );
  192. }
  193. }
  194. }
  195. }
  196. }
  197. void NavigationMesh::SetTileSize(int size)
  198. {
  199. tileSize_ = Max(size, 16);
  200. }
  201. void NavigationMesh::SetCellSize(float size)
  202. {
  203. cellSize_ = Max(size, M_EPSILON);
  204. }
  205. void NavigationMesh::SetCellHeight(float height)
  206. {
  207. cellHeight_ = Max(height, M_EPSILON);
  208. }
  209. void NavigationMesh::SetAgentHeight(float height)
  210. {
  211. agentHeight_ = Max(height, M_EPSILON);
  212. }
  213. void NavigationMesh::SetAgentRadius(float radius)
  214. {
  215. agentRadius_ = Max(radius, M_EPSILON);
  216. }
  217. void NavigationMesh::SetAgentMaxClimb(float maxClimb)
  218. {
  219. agentMaxClimb_ = Max(maxClimb, M_EPSILON);
  220. }
  221. void NavigationMesh::SetAgentMaxSlope(float maxSlope)
  222. {
  223. agentMaxSlope_ = Max(maxSlope, 0.0f);
  224. }
  225. void NavigationMesh::SetRegionMinSize(float size)
  226. {
  227. regionMinSize_ = Max(size, M_EPSILON);
  228. }
  229. void NavigationMesh::SetRegionMergeSize(float size)
  230. {
  231. regionMergeSize_ = Max(size, M_EPSILON);
  232. }
  233. void NavigationMesh::SetEdgeMaxLength(float length)
  234. {
  235. edgeMaxLength_ = Max(length, M_EPSILON);
  236. }
  237. void NavigationMesh::SetEdgeMaxError(float error)
  238. {
  239. edgeMaxError_ = Max(error, M_EPSILON);
  240. }
  241. void NavigationMesh::SetDetailSampleDistance(float distance)
  242. {
  243. detailSampleDistance_ = Max(distance, M_EPSILON);
  244. }
  245. void NavigationMesh::SetDetailSampleMaxError(float error)
  246. {
  247. detailSampleMaxError_ = Max(error, M_EPSILON);
  248. }
  249. bool NavigationMesh::Build()
  250. {
  251. PROFILE(BuildNavigationMesh);
  252. ReleaseNavigationMesh();
  253. if (!node_)
  254. return false;
  255. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  256. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  257. Vector<NavigationGeometryInfo> geometryList;
  258. CollectGeometries(geometryList);
  259. if (geometryList.Empty())
  260. return true; // Nothing to do
  261. // Build the combined bounding box
  262. for (unsigned i = 0; i < geometryList.Size(); ++i)
  263. boundingBox_.Merge(geometryList[i].boundingBox_);
  264. {
  265. PROFILE(BuildNavigationMesh);
  266. // Calculate number of tiles
  267. int gridW = 0, gridH = 0;
  268. float tileEdgeLength = (float)tileSize_ * cellSize_;
  269. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  270. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  271. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  272. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  273. unsigned maxTiles = NextPowerOfTwo(numTilesX_ * numTilesZ_);
  274. unsigned tileBits = 0;
  275. unsigned temp = maxTiles;
  276. while (temp > 1)
  277. {
  278. temp >>= 1;
  279. ++tileBits;
  280. }
  281. unsigned maxPolys = 1 << (22 - tileBits);
  282. dtNavMeshParams params;
  283. rcVcopy(params.orig, &boundingBox_.min_.x_);
  284. params.tileWidth = tileEdgeLength;
  285. params.tileHeight = tileEdgeLength;
  286. params.maxTiles = maxTiles;
  287. params.maxPolys = maxPolys;
  288. navMesh_ = dtAllocNavMesh();
  289. if (!navMesh_)
  290. {
  291. LOGERROR("Could not allocate navigation mesh");
  292. return false;
  293. }
  294. if (dtStatusFailed(navMesh_->init(&params)))
  295. {
  296. LOGERROR("Could not initialize navigation mesh");
  297. ReleaseNavigationMesh();
  298. return false;
  299. }
  300. // Build each tile
  301. unsigned numTiles = 0;
  302. for (int z = 0; z < numTilesZ_; ++z)
  303. {
  304. for (int x = 0; x < numTilesX_; ++x)
  305. {
  306. if (BuildTile(geometryList, x, z))
  307. ++numTiles;
  308. }
  309. }
  310. LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  311. return true;
  312. }
  313. }
  314. bool NavigationMesh::Build(const BoundingBox& boundingBox)
  315. {
  316. PROFILE(BuildPartialNavigationMesh);
  317. /// \todo Partial rebuild does not modify the bounding box. Modifying in Y-direction could be supported
  318. if (!node_)
  319. return false;
  320. if (!navMesh_)
  321. {
  322. LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  323. return false;
  324. }
  325. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  326. LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  327. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  328. float tileEdgeLength = (float)tileSize_ * cellSize_;
  329. Vector<NavigationGeometryInfo> geometryList;
  330. CollectGeometries(geometryList);
  331. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  332. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  333. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  334. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  335. unsigned numTiles = 0;
  336. for (int z = sz; z <= ez; ++z)
  337. {
  338. for (int x = sx; x <= ex; ++x)
  339. {
  340. if (BuildTile(geometryList, x, z))
  341. ++numTiles;
  342. }
  343. }
  344. LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  345. return true;
  346. }
  347. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)
  348. {
  349. PROFILE(FindPath);
  350. dest.Clear();
  351. if (!navMesh_ || !node_)
  352. return;
  353. if (!navMeshQuery_)
  354. {
  355. if (!InitializeQuery())
  356. return;
  357. }
  358. // Navigation data is in local space. Transform path points from world to local
  359. const Matrix3x4& transform = node_->GetWorldTransform();
  360. Matrix3x4 inverseTransform = transform.Inverse();
  361. Vector3 localStart = inverseTransform * start;
  362. Vector3 localEnd = inverseTransform * end;
  363. dtPolyRef startRef;
  364. dtPolyRef endRef;
  365. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  366. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);
  367. if (!startRef || !endRef)
  368. return;
  369. int numPolys = 0;
  370. int numPathPoints = 0;
  371. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,
  372. MAX_POLYS);
  373. if (!numPolys)
  374. return;
  375. Vector3 actualLocalEnd = localEnd;
  376. // If full path was not found, clamp end point to the end polygon
  377. if (pathData_->polys_[numPolys - 1] != endRef)
  378. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_);
  379. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  380. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  381. // Transform path result back to world space
  382. for (int i = 0; i < numPathPoints; ++i)
  383. dest.Push(transform * pathData_->pathPoints_[i]);
  384. }
  385. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  386. {
  387. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  388. }
  389. void NavigationMesh::SetNavigationDataAttr(PODVector<unsigned char> data)
  390. {
  391. ReleaseNavigationMesh();
  392. if (!data.Size())
  393. return;
  394. MemoryBuffer buffer(data);
  395. boundingBox_ = buffer.ReadBoundingBox();
  396. numTilesX_ = buffer.ReadInt();
  397. numTilesZ_ = buffer.ReadInt();
  398. dtNavMeshParams params;
  399. rcVcopy(params.orig, &boundingBox_.min_.x_);
  400. params.tileWidth = buffer.ReadFloat();
  401. params.tileHeight = buffer.ReadFloat();
  402. params.maxTiles = buffer.ReadInt();
  403. params.maxPolys = buffer.ReadInt();
  404. navMesh_ = dtAllocNavMesh();
  405. if (!navMesh_)
  406. {
  407. LOGERROR("Could not allocate navigation mesh");
  408. return;
  409. }
  410. if (dtStatusFailed(navMesh_->init(&params)))
  411. {
  412. LOGERROR("Could not initialize navigation mesh");
  413. ReleaseNavigationMesh();
  414. return;
  415. }
  416. unsigned numTiles = 0;
  417. while (!buffer.IsEof())
  418. {
  419. int x = buffer.ReadInt();
  420. int z = buffer.ReadInt();
  421. dtTileRef tileRef = buffer.ReadUInt();
  422. unsigned navDataSize = buffer.ReadUInt();
  423. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  424. if (!navData)
  425. {
  426. LOGERROR("Could not allocate data for navigation mesh tile");
  427. return;
  428. }
  429. buffer.Read(navData, navDataSize);
  430. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  431. {
  432. LOGERROR("Failed to add navigation mesh tile");
  433. dtFree(navData);
  434. return;
  435. }
  436. else
  437. ++numTiles;
  438. }
  439. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  440. }
  441. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  442. {
  443. VectorBuffer ret;
  444. if (navMesh_)
  445. {
  446. ret.WriteBoundingBox(boundingBox_);
  447. ret.WriteInt(numTilesX_);
  448. ret.WriteInt(numTilesZ_);
  449. const dtNavMeshParams* params = navMesh_->getParams();
  450. ret.WriteFloat(params->tileWidth);
  451. ret.WriteFloat(params->tileHeight);
  452. ret.WriteInt(params->maxTiles);
  453. ret.WriteInt(params->maxPolys);
  454. const dtNavMesh* navMesh = navMesh_;
  455. for (int z = 0; z < numTilesZ_; ++z)
  456. {
  457. for (int x = 0; x < numTilesX_; ++x)
  458. {
  459. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  460. if (!tile)
  461. continue;
  462. ret.WriteInt(x);
  463. ret.WriteInt(z);
  464. ret.WriteUInt(navMesh->getTileRef(tile));
  465. ret.WriteUInt(tile->dataSize);
  466. ret.Write(tile->data, tile->dataSize);
  467. }
  468. }
  469. }
  470. return ret.GetBuffer();
  471. }
  472. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  473. {
  474. PROFILE(CollectNavigationGeometry);
  475. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  476. // the scene into several navigation meshes
  477. PODVector<Navigable*> navigables;
  478. node_->GetComponents<Navigable>(navigables, true);
  479. HashSet<Node*> processedNodes;
  480. for (unsigned i = 0; i < navigables.Size(); ++i)
  481. {
  482. if (navigables[i]->IsEnabledEffective())
  483. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  484. }
  485. }
  486. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)
  487. {
  488. // Make sure nodes are not included twice
  489. if (processedNodes.Contains(node))
  490. return;
  491. processedNodes.Insert(node);
  492. Matrix3x4 inverseTransform = node_->GetWorldTransform().Inverse();
  493. /// \todo Prefer physics geometry if available
  494. PODVector<Drawable*> drawables;
  495. node->GetDerivedComponents<Drawable>(drawables);
  496. for (unsigned i = 0; i < drawables.Size(); ++i)
  497. {
  498. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  499. Drawable* drawable = drawables[i];
  500. if (!drawable->IsEnabledEffective())
  501. continue;
  502. NavigationGeometryInfo info;
  503. if (drawable->GetType() == StaticModel::GetTypeStatic())
  504. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  505. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  506. info.lodLevel_ = 0;
  507. else
  508. continue;
  509. info.component_ = drawable;
  510. info.transform_ = inverseTransform * node->GetWorldTransform();
  511. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverseTransform);
  512. geometryList.Push(info);
  513. }
  514. if (recursive)
  515. {
  516. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  517. for(unsigned i = 0; i < children.Size(); ++i)
  518. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  519. }
  520. }
  521. void NavigationMesh::GetTileGeometry(NavigationBuildData& build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  522. {
  523. for (unsigned i = 0; i < geometryList.Size(); ++i)
  524. {
  525. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  526. {
  527. const Matrix3x4& transform = geometryList[i].transform_;
  528. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  529. if (drawable)
  530. {
  531. const Vector<SourceBatch>& batches = drawable->GetBatches();
  532. for (unsigned j = 0; j < batches.Size(); ++j)
  533. {
  534. Geometry* geometry = drawable->GetLodGeometry(j, geometryList[i].lodLevel_);
  535. if (!geometry)
  536. continue;
  537. const unsigned char* vertexData;
  538. const unsigned char* indexData;
  539. unsigned vertexSize;
  540. unsigned indexSize;
  541. unsigned elementMask;
  542. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  543. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  544. continue;
  545. unsigned srcIndexStart = geometry->GetIndexStart();
  546. unsigned srcIndexCount = geometry->GetIndexCount();
  547. unsigned srcVertexStart = geometry->GetVertexStart();
  548. unsigned srcVertexCount = geometry->GetVertexCount();
  549. if (!srcIndexCount)
  550. continue;
  551. unsigned destVertexStart = build.vertices_.Size();
  552. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  553. {
  554. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  555. build.vertices_.Push(vertex);
  556. }
  557. // Copy remapped indices
  558. if (indexSize == sizeof(unsigned short))
  559. {
  560. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  561. const unsigned short* indicesEnd = indices + srcIndexCount;
  562. while (indices < indicesEnd)
  563. {
  564. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  565. ++indices;
  566. }
  567. }
  568. else
  569. {
  570. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  571. const unsigned* indicesEnd = indices + srcIndexCount;
  572. while (indices < indicesEnd)
  573. {
  574. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  575. ++indices;
  576. }
  577. }
  578. }
  579. }
  580. }
  581. }
  582. }
  583. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  584. {
  585. PROFILE(BuildNavigationMeshTile);
  586. float tileEdgeLength = (float)tileSize_ * cellSize_;
  587. BoundingBox tileBoundingBox(Vector3(
  588. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  589. boundingBox_.min_.y_,
  590. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  591. ),
  592. Vector3(
  593. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  594. boundingBox_.max_.y_,
  595. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  596. ));
  597. NavigationBuildData build;
  598. rcConfig cfg;
  599. memset(&cfg, 0, sizeof cfg);
  600. cfg.cs = cellSize_;
  601. cfg.ch = cellHeight_;
  602. cfg.walkableSlopeAngle = agentMaxSlope_;
  603. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  604. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  605. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  606. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  607. cfg.maxSimplificationError = edgeMaxError_;
  608. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  609. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  610. cfg.maxVertsPerPoly = 6;
  611. cfg.tileSize = tileSize_;
  612. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  613. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  614. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  615. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  616. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  617. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  618. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  619. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  620. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  621. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  622. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  623. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  624. GetTileGeometry(build, geometryList, expandedBox);
  625. build.heightField_ = rcAllocHeightfield();
  626. if (!build.heightField_)
  627. {
  628. LOGERROR("Could not allocate heightfield");
  629. return false;
  630. }
  631. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  632. cfg.ch))
  633. {
  634. LOGERROR("Could not create heightfield");
  635. return false;
  636. }
  637. unsigned numTriangles = build.indices_.Size() / 3;
  638. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  639. memset(triAreas.Get(), 0, numTriangles);
  640. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  641. &build.indices_[0], numTriangles, triAreas.Get());
  642. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  643. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  644. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  645. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  646. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  647. build.compactHeightField_ = rcAllocCompactHeightfield();
  648. if (!build.compactHeightField_)
  649. {
  650. LOGERROR("Could not allocate create compact heightfield");
  651. return false;
  652. }
  653. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  654. *build.compactHeightField_))
  655. {
  656. LOGERROR("Could not build compact heightfield");
  657. return false;
  658. }
  659. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  660. {
  661. LOGERROR("Could not erode compact heightfield");
  662. return false;
  663. }
  664. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  665. {
  666. LOGERROR("Could not build distance field");
  667. return false;
  668. }
  669. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  670. cfg.mergeRegionArea))
  671. {
  672. LOGERROR("Could not build regions");
  673. return false;
  674. }
  675. build.contourSet_ = rcAllocContourSet();
  676. if (!build.contourSet_)
  677. {
  678. LOGERROR("Could not allocate contour set");
  679. return false;
  680. }
  681. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  682. *build.contourSet_))
  683. {
  684. LOGERROR("Could not create contours");
  685. return false;
  686. }
  687. build.polyMesh_ = rcAllocPolyMesh();
  688. if (!build.polyMesh_)
  689. {
  690. LOGERROR("Could not allocate poly mesh");
  691. return false;
  692. }
  693. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  694. {
  695. LOGERROR("Could not triangulate contours");
  696. return false;
  697. }
  698. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  699. if (!build.polyMeshDetail_)
  700. {
  701. LOGERROR("Could not allocate detail mesh");
  702. return false;
  703. }
  704. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  705. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  706. {
  707. LOGERROR("Could not build detail mesh");
  708. return false;
  709. }
  710. // Set polygon flags
  711. /// \todo Allow to define custom flags
  712. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  713. {
  714. if (build.polyMesh_->areas[i] == RC_WALKABLE_AREA)
  715. build.polyMesh_->flags[i] = 0x1;
  716. }
  717. unsigned char* navData = 0;
  718. int navDataSize = 0;
  719. dtNavMeshCreateParams params;
  720. memset(&params, 0, sizeof params);
  721. params.verts = build.polyMesh_->verts;
  722. params.vertCount = build.polyMesh_->nverts;
  723. params.polys = build.polyMesh_->polys;
  724. params.polyAreas = build.polyMesh_->areas;
  725. params.polyFlags = build.polyMesh_->flags;
  726. params.polyCount = build.polyMesh_->npolys;
  727. params.nvp = build.polyMesh_->nvp;
  728. params.detailMeshes = build.polyMeshDetail_->meshes;
  729. params.detailVerts = build.polyMeshDetail_->verts;
  730. params.detailVertsCount = build.polyMeshDetail_->nverts;
  731. params.detailTris = build.polyMeshDetail_->tris;
  732. params.detailTriCount = build.polyMeshDetail_->ntris;
  733. params.walkableHeight = agentHeight_;
  734. params.walkableRadius = agentRadius_;
  735. params.walkableClimb = agentMaxClimb_;
  736. params.tileX = x;
  737. params.tileY = z;
  738. rcVcopy(params.bmin, build.polyMesh_->bmin);
  739. rcVcopy(params.bmax, build.polyMesh_->bmax);
  740. params.cs = cfg.cs;
  741. params.ch = cfg.ch;
  742. params.buildBvTree = true;
  743. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  744. {
  745. LOGERROR("Could not build navigation mesh tile data");
  746. return false;
  747. }
  748. // Remove previous tile (if any), then add new
  749. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  750. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  751. {
  752. LOGERROR("Failed to add navigation mesh tile");
  753. dtFree(navData);
  754. return false;
  755. }
  756. return true;
  757. }
  758. bool NavigationMesh::InitializeQuery()
  759. {
  760. navMeshQuery_ = dtAllocNavMeshQuery();
  761. if (!navMeshQuery_)
  762. {
  763. LOGERROR("Could not create navigation mesh query");
  764. return false;
  765. }
  766. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  767. {
  768. LOGERROR("Could not init navigation mesh query");
  769. return false;
  770. }
  771. return true;
  772. }
  773. void NavigationMesh::ReleaseNavigationMesh()
  774. {
  775. dtFreeNavMesh(navMesh_);
  776. navMesh_ = 0;
  777. dtFreeNavMeshQuery(navMeshQuery_);
  778. navMeshQuery_ = 0;
  779. numTilesX_ = 0;
  780. numTilesZ_ = 0;
  781. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  782. boundingBox_.defined_ = false;
  783. }
  784. }