NavigationMesh.cpp 42 KB

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