NavigationMesh.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. //
  2. // Copyright (c) 2008-2014 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. const char* NAVIGATION_CATEGORY = "Navigation";
  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. Vector3 NavigationMesh::FindNearestPoint(const Vector3& point, const Vector3& extents)
  384. {
  385. if(!InitializeQuery())
  386. return point;
  387. const Matrix3x4& transform = node_->GetWorldTransform();
  388. Matrix3x4 inverse = transform.Inverse();
  389. Vector3 localPoint = inverse * point;
  390. Vector3 nearestPoint;
  391. dtPolyRef pointRef;
  392. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &pointRef, &nearestPoint.x_);
  393. if (!pointRef)
  394. return point;
  395. return transform*nearestPoint;
  396. }
  397. Vector3 NavigationMesh::MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents, int maxVisited)
  398. {
  399. if (!InitializeQuery())
  400. return end;
  401. const Matrix3x4& transform = node_->GetWorldTransform();
  402. Matrix3x4 inverse = transform.Inverse();
  403. Vector3 localStart = inverse * start;
  404. Vector3 localEnd = inverse * end;
  405. dtPolyRef startRef;
  406. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  407. if (!startRef)
  408. return end;
  409. Vector3 resultPos;
  410. int visitedCount = 0;
  411. maxVisited = Max(maxVisited, 0);
  412. PODVector<dtPolyRef> visited(maxVisited);
  413. navMeshQuery_->moveAlongSurface(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &resultPos.x_, maxVisited ?
  414. &visited[0] : (dtPolyRef*)0, &visitedCount, maxVisited);
  415. return transform * resultPos;
  416. }
  417. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents)
  418. {
  419. PROFILE(FindPath);
  420. dest.Clear();
  421. if (!InitializeQuery())
  422. return;
  423. // Navigation data is in local space. Transform path points from world to local
  424. const Matrix3x4& transform = node_->GetWorldTransform();
  425. Matrix3x4 inverse = transform.Inverse();
  426. Vector3 localStart = inverse * start;
  427. Vector3 localEnd = inverse * end;
  428. dtPolyRef startRef;
  429. dtPolyRef endRef;
  430. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  431. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter_, &endRef, 0);
  432. if (!startRef || !endRef)
  433. return;
  434. int numPolys = 0;
  435. int numPathPoints = 0;
  436. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter_, pathData_->polys_, &numPolys,
  437. MAX_POLYS);
  438. if (!numPolys)
  439. return;
  440. Vector3 actualLocalEnd = localEnd;
  441. // If full path was not found, clamp end point to the end polygon
  442. if (pathData_->polys_[numPolys - 1] != endRef)
  443. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_, 0);
  444. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  445. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  446. // Transform path result back to world space
  447. for (int i = 0; i < numPathPoints; ++i)
  448. dest.Push(transform * pathData_->pathPoints_[i]);
  449. }
  450. Vector3 NavigationMesh::GetRandomPoint()
  451. {
  452. if (!InitializeQuery())
  453. return Vector3::ZERO;
  454. dtPolyRef polyRef;
  455. Vector3 point(Vector3::ZERO);
  456. navMeshQuery_->findRandomPoint(queryFilter_, Random, &polyRef, &point.x_);
  457. return node_->GetWorldTransform() * point;
  458. }
  459. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents)
  460. {
  461. if (!InitializeQuery())
  462. return center;
  463. const Matrix3x4& transform = node_->GetWorldTransform();
  464. Matrix3x4 inverse = transform.Inverse();
  465. Vector3 localCenter = inverse * center;
  466. dtPolyRef startRef;
  467. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter_, &startRef, 0);
  468. if (!startRef)
  469. return center;
  470. dtPolyRef polyRef;
  471. Vector3 point(localCenter);
  472. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter_, Random, &polyRef, &point.x_);
  473. return transform * point;
  474. }
  475. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents)
  476. {
  477. if (!InitializeQuery())
  478. return radius;
  479. const Matrix3x4& transform = node_->GetWorldTransform();
  480. Matrix3x4 inverse = transform.Inverse();
  481. Vector3 localPoint = inverse * point;
  482. dtPolyRef startRef;
  483. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter_, &startRef, 0);
  484. if (!startRef)
  485. return radius;
  486. float hitDist = radius;
  487. Vector3 hitPos;
  488. Vector3 hitNormal;
  489. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter_, &hitDist, &hitPos.x_, &hitNormal.x_);
  490. return hitDist;
  491. }
  492. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents)
  493. {
  494. if (!InitializeQuery())
  495. return end;
  496. const Matrix3x4& transform = node_->GetWorldTransform();
  497. Matrix3x4 inverse = transform.Inverse();
  498. Vector3 localStart = inverse * start;
  499. Vector3 localEnd = inverse * end;
  500. dtPolyRef startRef;
  501. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter_, &startRef, 0);
  502. if (!startRef)
  503. return end;
  504. Vector3 localHitNormal;
  505. float t;
  506. int numPolys;
  507. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter_, &t, &localHitNormal.x_, pathData_->polys_, &numPolys, MAX_POLYS);
  508. if (t == FLT_MAX)
  509. t = 1.0f;
  510. return start.Lerp(end, t);
  511. }
  512. void NavigationMesh::DrawDebugGeometry(bool depthTest)
  513. {
  514. Scene* scene = GetScene();
  515. if (scene)
  516. {
  517. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  518. if (debug)
  519. DrawDebugGeometry(debug, depthTest);
  520. }
  521. }
  522. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  523. {
  524. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  525. }
  526. void NavigationMesh::SetNavigationDataAttr(PODVector<unsigned char> value)
  527. {
  528. ReleaseNavigationMesh();
  529. if (value.Empty())
  530. return;
  531. MemoryBuffer buffer(value);
  532. boundingBox_ = buffer.ReadBoundingBox();
  533. numTilesX_ = buffer.ReadInt();
  534. numTilesZ_ = buffer.ReadInt();
  535. dtNavMeshParams params;
  536. rcVcopy(params.orig, &boundingBox_.min_.x_);
  537. params.tileWidth = buffer.ReadFloat();
  538. params.tileHeight = buffer.ReadFloat();
  539. params.maxTiles = buffer.ReadInt();
  540. params.maxPolys = buffer.ReadInt();
  541. navMesh_ = dtAllocNavMesh();
  542. if (!navMesh_)
  543. {
  544. LOGERROR("Could not allocate navigation mesh");
  545. return;
  546. }
  547. if (dtStatusFailed(navMesh_->init(&params)))
  548. {
  549. LOGERROR("Could not initialize navigation mesh");
  550. ReleaseNavigationMesh();
  551. return;
  552. }
  553. unsigned numTiles = 0;
  554. while (!buffer.IsEof())
  555. {
  556. /*int x =*/ buffer.ReadInt();
  557. /*int z =*/ buffer.ReadInt();
  558. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  559. unsigned navDataSize = buffer.ReadUInt();
  560. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  561. if (!navData)
  562. {
  563. LOGERROR("Could not allocate data for navigation mesh tile");
  564. return;
  565. }
  566. buffer.Read(navData, navDataSize);
  567. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  568. {
  569. LOGERROR("Failed to add navigation mesh tile");
  570. dtFree(navData);
  571. return;
  572. }
  573. else
  574. ++numTiles;
  575. }
  576. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  577. }
  578. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  579. {
  580. VectorBuffer ret;
  581. if (navMesh_)
  582. {
  583. ret.WriteBoundingBox(boundingBox_);
  584. ret.WriteInt(numTilesX_);
  585. ret.WriteInt(numTilesZ_);
  586. const dtNavMeshParams* params = navMesh_->getParams();
  587. ret.WriteFloat(params->tileWidth);
  588. ret.WriteFloat(params->tileHeight);
  589. ret.WriteInt(params->maxTiles);
  590. ret.WriteInt(params->maxPolys);
  591. const dtNavMesh* navMesh = navMesh_;
  592. for (int z = 0; z < numTilesZ_; ++z)
  593. {
  594. for (int x = 0; x < numTilesX_; ++x)
  595. {
  596. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  597. if (!tile)
  598. continue;
  599. ret.WriteInt(x);
  600. ret.WriteInt(z);
  601. ret.WriteUInt(navMesh->getTileRef(tile));
  602. ret.WriteUInt(tile->dataSize);
  603. ret.Write(tile->data, tile->dataSize);
  604. }
  605. }
  606. }
  607. return ret.GetBuffer();
  608. }
  609. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  610. {
  611. PROFILE(CollectNavigationGeometry);
  612. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  613. // the scene into several navigation meshes
  614. PODVector<Navigable*> navigables;
  615. node_->GetComponents<Navigable>(navigables, true);
  616. HashSet<Node*> processedNodes;
  617. for (unsigned i = 0; i < navigables.Size(); ++i)
  618. {
  619. if (navigables[i]->IsEnabledEffective())
  620. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  621. }
  622. // Get offmesh connections
  623. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  624. PODVector<OffMeshConnection*> connections;
  625. node_->GetComponents<OffMeshConnection>(connections, true);
  626. for (unsigned i = 0; i < connections.Size(); ++i)
  627. {
  628. OffMeshConnection* connection = connections[i];
  629. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  630. {
  631. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  632. NavigationGeometryInfo info;
  633. info.component_ = connection;
  634. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  635. geometryList.Push(info);
  636. }
  637. }
  638. }
  639. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes, bool recursive)
  640. {
  641. // Make sure nodes are not included twice
  642. if (processedNodes.Contains(node))
  643. return;
  644. processedNodes.Insert(node);
  645. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  646. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  647. // Then fallback to visible geometry
  648. PODVector<CollisionShape*> collisionShapes;
  649. node->GetComponents<CollisionShape>(collisionShapes);
  650. bool collisionShapeFound = false;
  651. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  652. {
  653. CollisionShape* shape = collisionShapes[i];
  654. if (!shape->IsEnabledEffective())
  655. continue;
  656. ShapeType type = shape->GetShapeType();
  657. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  658. {
  659. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  660. NavigationGeometryInfo info;
  661. info.component_ = shape;
  662. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  663. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  664. geometryList.Push(info);
  665. collisionShapeFound = true;
  666. }
  667. }
  668. if (!collisionShapeFound)
  669. {
  670. PODVector<Drawable*> drawables;
  671. node->GetDerivedComponents<Drawable>(drawables);
  672. for (unsigned i = 0; i < drawables.Size(); ++i)
  673. {
  674. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  675. Drawable* drawable = drawables[i];
  676. if (!drawable->IsEnabledEffective())
  677. continue;
  678. NavigationGeometryInfo info;
  679. if (drawable->GetType() == StaticModel::GetTypeStatic())
  680. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  681. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  682. info.lodLevel_ = 0;
  683. else
  684. continue;
  685. info.component_ = drawable;
  686. info.transform_ = inverse * node->GetWorldTransform();
  687. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  688. geometryList.Push(info);
  689. }
  690. }
  691. if (recursive)
  692. {
  693. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  694. for(unsigned i = 0; i < children.Size(); ++i)
  695. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  696. }
  697. }
  698. void NavigationMesh::GetTileGeometry(NavigationBuildData& build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  699. {
  700. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  701. for (unsigned i = 0; i < geometryList.Size(); ++i)
  702. {
  703. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  704. {
  705. const Matrix3x4& transform = geometryList[i].transform_;
  706. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  707. {
  708. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  709. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  710. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  711. build.offMeshVertices_.Push(start);
  712. build.offMeshVertices_.Push(end);
  713. build.offMeshRadii_.Push(connection->GetRadius());
  714. /// \todo Allow to define custom flags
  715. build.offMeshFlags_.Push(0x1);
  716. build.offMeshAreas_.Push(0);
  717. build.offMeshDir_.Push(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0);
  718. continue;
  719. }
  720. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  721. if (shape)
  722. {
  723. switch (shape->GetShapeType())
  724. {
  725. case SHAPE_TRIANGLEMESH:
  726. {
  727. Model* model = shape->GetModel();
  728. if (!model)
  729. continue;
  730. unsigned lodLevel = shape->GetLodLevel();
  731. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  732. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  733. }
  734. break;
  735. case SHAPE_CONVEXHULL:
  736. {
  737. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  738. if (!data)
  739. continue;
  740. unsigned numVertices = data->vertexCount_;
  741. unsigned numIndices = data->indexCount_;
  742. unsigned destVertexStart = build.vertices_.Size();
  743. for (unsigned j = 0; j < numVertices; ++j)
  744. build.vertices_.Push(transform * data->vertexData_[j]);
  745. for (unsigned j = 0; j < numIndices; ++j)
  746. build.indices_.Push(data->indexData_[j] + destVertexStart);
  747. }
  748. break;
  749. case SHAPE_BOX:
  750. {
  751. unsigned destVertexStart = build.vertices_.Size();
  752. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  753. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  754. build.vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));
  755. build.vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));
  756. build.vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));
  757. build.vertices_.Push(transform * Vector3(0.5f, 0.5f, 0.5f));
  758. build.vertices_.Push(transform * Vector3(0.5f, -0.5f, 0.5f));
  759. build.vertices_.Push(transform * Vector3(-0.5f, -0.5f, 0.5f));
  760. const unsigned indices[] = {
  761. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  762. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  763. };
  764. for (unsigned j = 0; j < 36; ++j)
  765. build.indices_.Push(indices[j] + destVertexStart);
  766. }
  767. break;
  768. default:
  769. break;
  770. }
  771. continue;
  772. }
  773. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  774. if (drawable)
  775. {
  776. const Vector<SourceBatch>& batches = drawable->GetBatches();
  777. for (unsigned j = 0; j < batches.Size(); ++j)
  778. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  779. }
  780. }
  781. }
  782. }
  783. void NavigationMesh::AddTriMeshGeometry(NavigationBuildData& build, Geometry* geometry, const Matrix3x4& transform)
  784. {
  785. if (!geometry)
  786. return;
  787. const unsigned char* vertexData;
  788. const unsigned char* indexData;
  789. unsigned vertexSize;
  790. unsigned indexSize;
  791. unsigned elementMask;
  792. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  793. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  794. return;
  795. unsigned srcIndexStart = geometry->GetIndexStart();
  796. unsigned srcIndexCount = geometry->GetIndexCount();
  797. unsigned srcVertexStart = geometry->GetVertexStart();
  798. unsigned srcVertexCount = geometry->GetVertexCount();
  799. if (!srcIndexCount)
  800. return;
  801. unsigned destVertexStart = build.vertices_.Size();
  802. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  803. {
  804. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  805. build.vertices_.Push(vertex);
  806. }
  807. // Copy remapped indices
  808. if (indexSize == sizeof(unsigned short))
  809. {
  810. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  811. const unsigned short* indicesEnd = indices + srcIndexCount;
  812. while (indices < indicesEnd)
  813. {
  814. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  815. ++indices;
  816. }
  817. }
  818. else
  819. {
  820. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  821. const unsigned* indicesEnd = indices + srcIndexCount;
  822. while (indices < indicesEnd)
  823. {
  824. build.indices_.Push(*indices - srcVertexStart + destVertexStart);
  825. ++indices;
  826. }
  827. }
  828. }
  829. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  830. {
  831. PROFILE(BuildNavigationMeshTile);
  832. // Remove previous tile (if any)
  833. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  834. float tileEdgeLength = (float)tileSize_ * cellSize_;
  835. BoundingBox tileBoundingBox(Vector3(
  836. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  837. boundingBox_.min_.y_,
  838. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  839. ),
  840. Vector3(
  841. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  842. boundingBox_.max_.y_,
  843. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  844. ));
  845. NavigationBuildData build;
  846. rcConfig cfg;
  847. memset(&cfg, 0, sizeof cfg);
  848. cfg.cs = cellSize_;
  849. cfg.ch = cellHeight_;
  850. cfg.walkableSlopeAngle = agentMaxSlope_;
  851. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  852. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  853. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  854. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  855. cfg.maxSimplificationError = edgeMaxError_;
  856. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  857. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  858. cfg.maxVertsPerPoly = 6;
  859. cfg.tileSize = tileSize_;
  860. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  861. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  862. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  863. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  864. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  865. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  866. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  867. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  868. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  869. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  870. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  871. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  872. GetTileGeometry(build, geometryList, expandedBox);
  873. if (build.vertices_.Empty() || build.indices_.Empty())
  874. return true; // Nothing to do
  875. build.heightField_ = rcAllocHeightfield();
  876. if (!build.heightField_)
  877. {
  878. LOGERROR("Could not allocate heightfield");
  879. return false;
  880. }
  881. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  882. cfg.ch))
  883. {
  884. LOGERROR("Could not create heightfield");
  885. return false;
  886. }
  887. unsigned numTriangles = build.indices_.Size() / 3;
  888. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  889. memset(triAreas.Get(), 0, numTriangles);
  890. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  891. &build.indices_[0], numTriangles, triAreas.Get());
  892. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  893. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  894. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  895. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  896. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  897. build.compactHeightField_ = rcAllocCompactHeightfield();
  898. if (!build.compactHeightField_)
  899. {
  900. LOGERROR("Could not allocate create compact heightfield");
  901. return false;
  902. }
  903. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  904. *build.compactHeightField_))
  905. {
  906. LOGERROR("Could not build compact heightfield");
  907. return false;
  908. }
  909. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  910. {
  911. LOGERROR("Could not erode compact heightfield");
  912. return false;
  913. }
  914. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  915. {
  916. LOGERROR("Could not build distance field");
  917. return false;
  918. }
  919. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  920. cfg.mergeRegionArea))
  921. {
  922. LOGERROR("Could not build regions");
  923. return false;
  924. }
  925. build.contourSet_ = rcAllocContourSet();
  926. if (!build.contourSet_)
  927. {
  928. LOGERROR("Could not allocate contour set");
  929. return false;
  930. }
  931. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  932. *build.contourSet_))
  933. {
  934. LOGERROR("Could not create contours");
  935. return false;
  936. }
  937. build.polyMesh_ = rcAllocPolyMesh();
  938. if (!build.polyMesh_)
  939. {
  940. LOGERROR("Could not allocate poly mesh");
  941. return false;
  942. }
  943. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  944. {
  945. LOGERROR("Could not triangulate contours");
  946. return false;
  947. }
  948. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  949. if (!build.polyMeshDetail_)
  950. {
  951. LOGERROR("Could not allocate detail mesh");
  952. return false;
  953. }
  954. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  955. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  956. {
  957. LOGERROR("Could not build detail mesh");
  958. return false;
  959. }
  960. // Set polygon flags
  961. /// \todo Allow to define custom flags
  962. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  963. {
  964. if (build.polyMesh_->areas[i] == RC_WALKABLE_AREA)
  965. build.polyMesh_->flags[i] = 0x1;
  966. }
  967. unsigned char* navData = 0;
  968. int navDataSize = 0;
  969. dtNavMeshCreateParams params;
  970. memset(&params, 0, sizeof params);
  971. params.verts = build.polyMesh_->verts;
  972. params.vertCount = build.polyMesh_->nverts;
  973. params.polys = build.polyMesh_->polys;
  974. params.polyAreas = build.polyMesh_->areas;
  975. params.polyFlags = build.polyMesh_->flags;
  976. params.polyCount = build.polyMesh_->npolys;
  977. params.nvp = build.polyMesh_->nvp;
  978. params.detailMeshes = build.polyMeshDetail_->meshes;
  979. params.detailVerts = build.polyMeshDetail_->verts;
  980. params.detailVertsCount = build.polyMeshDetail_->nverts;
  981. params.detailTris = build.polyMeshDetail_->tris;
  982. params.detailTriCount = build.polyMeshDetail_->ntris;
  983. params.walkableHeight = agentHeight_;
  984. params.walkableRadius = agentRadius_;
  985. params.walkableClimb = agentMaxClimb_;
  986. params.tileX = x;
  987. params.tileY = z;
  988. rcVcopy(params.bmin, build.polyMesh_->bmin);
  989. rcVcopy(params.bmax, build.polyMesh_->bmax);
  990. params.cs = cfg.cs;
  991. params.ch = cfg.ch;
  992. params.buildBvTree = true;
  993. // Add off-mesh connections if have them
  994. if (build.offMeshRadii_.Size())
  995. {
  996. params.offMeshConCount = build.offMeshRadii_.Size();
  997. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  998. params.offMeshConRad = &build.offMeshRadii_[0];
  999. params.offMeshConFlags = &build.offMeshFlags_[0];
  1000. params.offMeshConAreas = &build.offMeshAreas_[0];
  1001. params.offMeshConDir = &build.offMeshDir_[0];
  1002. }
  1003. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1004. {
  1005. LOGERROR("Could not build navigation mesh tile data");
  1006. return false;
  1007. }
  1008. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  1009. {
  1010. LOGERROR("Failed to add navigation mesh tile");
  1011. dtFree(navData);
  1012. return false;
  1013. }
  1014. return true;
  1015. }
  1016. bool NavigationMesh::InitializeQuery()
  1017. {
  1018. if (!navMesh_ || !node_)
  1019. return false;
  1020. if (navMeshQuery_)
  1021. return true;
  1022. navMeshQuery_ = dtAllocNavMeshQuery();
  1023. if (!navMeshQuery_)
  1024. {
  1025. LOGERROR("Could not create navigation mesh query");
  1026. return false;
  1027. }
  1028. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  1029. {
  1030. LOGERROR("Could not init navigation mesh query");
  1031. return false;
  1032. }
  1033. return true;
  1034. }
  1035. void NavigationMesh::ReleaseNavigationMesh()
  1036. {
  1037. dtFreeNavMesh(navMesh_);
  1038. navMesh_ = 0;
  1039. dtFreeNavMeshQuery(navMeshQuery_);
  1040. navMeshQuery_ = 0;
  1041. numTilesX_ = 0;
  1042. numTilesZ_ = 0;
  1043. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  1044. boundingBox_.defined_ = false;
  1045. }
  1046. void RegisterNavigationLibrary(Context* context)
  1047. {
  1048. Navigable::RegisterObject(context);
  1049. NavigationMesh::RegisterObject(context);
  1050. OffMeshConnection::RegisterObject(context);
  1051. }
  1052. }