NavigationMesh.cpp 42 KB

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