2
0

NavigationMesh.cpp 41 KB

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