NavigationMesh.cpp 36 KB

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