NavigationMesh.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. //
  2. // Copyright (c) 2008-2015 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 "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../Graphics/Drawable.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Model.h"
  29. #include "../Graphics/StaticModel.h"
  30. #include "../Graphics/TerrainPatch.h"
  31. #include "../IO/Log.h"
  32. #include "../IO/MemoryBuffer.h"
  33. #include "../Navigation/CrowdAgent.h"
  34. #include "../Navigation/DynamicNavigationMesh.h"
  35. #include "../Navigation/NavArea.h"
  36. #include "../Navigation/NavBuildData.h"
  37. #include "../Navigation/Navigable.h"
  38. #include "../Navigation/NavigationEvents.h"
  39. #include "../Navigation/NavigationMesh.h"
  40. #include "../Navigation/Obstacle.h"
  41. #include "../Navigation/OffMeshConnection.h"
  42. #ifdef URHO3D_PHYSICS
  43. #include "../Physics/CollisionShape.h"
  44. #endif
  45. #include "../Scene/Scene.h"
  46. #include <cfloat>
  47. #include <Detour/DetourNavMesh.h>
  48. #include <Detour/DetourNavMeshBuilder.h>
  49. #include <Detour/DetourNavMeshQuery.h>
  50. #include <Recast/Recast.h>
  51. #include "../DebugNew.h"
  52. namespace Urho3D
  53. {
  54. const char* navmeshPartitionTypeNames[] =
  55. {
  56. "watershed",
  57. "monotone",
  58. 0
  59. };
  60. const char* NAVIGATION_CATEGORY = "Navigation";
  61. static const int DEFAULT_TILE_SIZE = 128;
  62. static const float DEFAULT_CELL_SIZE = 0.3f;
  63. static const float DEFAULT_CELL_HEIGHT = 0.2f;
  64. static const float DEFAULT_AGENT_HEIGHT = 2.0f;
  65. static const float DEFAULT_AGENT_RADIUS = 0.6f;
  66. static const float DEFAULT_AGENT_MAX_CLIMB = 0.9f;
  67. static const float DEFAULT_AGENT_MAX_SLOPE = 45.0f;
  68. static const float DEFAULT_REGION_MIN_SIZE = 8.0f;
  69. static const float DEFAULT_REGION_MERGE_SIZE = 20.0f;
  70. static const float DEFAULT_EDGE_MAX_LENGTH = 12.0f;
  71. static const float DEFAULT_EDGE_MAX_ERROR = 1.3f;
  72. static const float DEFAULT_DETAIL_SAMPLE_DISTANCE = 6.0f;
  73. static const float DEFAULT_DETAIL_SAMPLE_MAX_ERROR = 1.0f;
  74. static const int MAX_POLYS = 2048;
  75. /// Temporary data for finding a path.
  76. struct FindPathData
  77. {
  78. // Polygons.
  79. dtPolyRef polys_[MAX_POLYS];
  80. // Polygons on the path.
  81. dtPolyRef pathPolys_[MAX_POLYS];
  82. // Points on the path.
  83. Vector3 pathPoints_[MAX_POLYS];
  84. // Flags on the path.
  85. unsigned char pathFlags_[MAX_POLYS];
  86. // Area Ids on the path.
  87. unsigned char pathAreras_[MAX_POLYS];
  88. };
  89. NavigationMesh::NavigationMesh(Context* context) :
  90. Component(context),
  91. navMesh_(0),
  92. navMeshQuery_(0),
  93. queryFilter_(new dtQueryFilter()),
  94. pathData_(new FindPathData()),
  95. tileSize_(DEFAULT_TILE_SIZE),
  96. cellSize_(DEFAULT_CELL_SIZE),
  97. cellHeight_(DEFAULT_CELL_HEIGHT),
  98. agentHeight_(DEFAULT_AGENT_HEIGHT),
  99. agentRadius_(DEFAULT_AGENT_RADIUS),
  100. agentMaxClimb_(DEFAULT_AGENT_MAX_CLIMB),
  101. agentMaxSlope_(DEFAULT_AGENT_MAX_SLOPE),
  102. regionMinSize_(DEFAULT_REGION_MIN_SIZE),
  103. regionMergeSize_(DEFAULT_REGION_MERGE_SIZE),
  104. edgeMaxLength_(DEFAULT_EDGE_MAX_LENGTH),
  105. edgeMaxError_(DEFAULT_EDGE_MAX_ERROR),
  106. detailSampleDistance_(DEFAULT_DETAIL_SAMPLE_DISTANCE),
  107. detailSampleMaxError_(DEFAULT_DETAIL_SAMPLE_MAX_ERROR),
  108. padding_(Vector3::ONE),
  109. numTilesX_(0),
  110. numTilesZ_(0),
  111. partitionType_(NAVMESH_PARTITION_WATERSHED),
  112. keepInterResults_(false),
  113. drawOffMeshConnections_(false),
  114. drawNavAreas_(false)
  115. {
  116. }
  117. NavigationMesh::~NavigationMesh()
  118. {
  119. ReleaseNavigationMesh();
  120. delete queryFilter_;
  121. queryFilter_ = 0;
  122. delete pathData_;
  123. pathData_ = 0;
  124. }
  125. void NavigationMesh::RegisterObject(Context* context)
  126. {
  127. context->RegisterFactory<NavigationMesh>(NAVIGATION_CATEGORY);
  128. URHO3D_ACCESSOR_ATTRIBUTE("Tile Size", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);
  129. URHO3D_ACCESSOR_ATTRIBUTE("Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  130. URHO3D_ACCESSOR_ATTRIBUTE("Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  131. URHO3D_ACCESSOR_ATTRIBUTE("Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  132. URHO3D_ACCESSOR_ATTRIBUTE("Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  133. URHO3D_ACCESSOR_ATTRIBUTE("Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  134. URHO3D_ACCESSOR_ATTRIBUTE("Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  135. URHO3D_ACCESSOR_ATTRIBUTE("Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  136. URHO3D_ACCESSOR_ATTRIBUTE("Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  137. URHO3D_ACCESSOR_ATTRIBUTE("Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  138. URHO3D_ACCESSOR_ATTRIBUTE("Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  139. URHO3D_ACCESSOR_ATTRIBUTE("Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float,
  140. DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  141. URHO3D_ACCESSOR_ATTRIBUTE("Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float,
  142. DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  143. URHO3D_ACCESSOR_ATTRIBUTE("Bounding Box Padding", GetPadding, SetPadding, Vector3, Vector3::ONE, AM_DEFAULT);
  144. URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Navigation Data", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>,
  145. Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  146. URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Partition Type", GetPartitionType, SetPartitionType, NavmeshPartitionType, navmeshPartitionTypeNames,
  147. NAVMESH_PARTITION_WATERSHED, AM_DEFAULT);
  148. URHO3D_ACCESSOR_ATTRIBUTE("Draw OffMeshConnections", GetDrawOffMeshConnections, SetDrawOffMeshConnections, bool, false, AM_DEFAULT);
  149. URHO3D_ACCESSOR_ATTRIBUTE("Draw NavAreas", GetDrawNavAreas, SetDrawNavAreas, bool, false, AM_DEFAULT);
  150. }
  151. void NavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  152. {
  153. if (!debug || !navMesh_ || !node_)
  154. return;
  155. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  156. const dtNavMesh* navMesh = navMesh_;
  157. for (int z = 0; z < numTilesZ_; ++z)
  158. {
  159. for (int x = 0; x < numTilesX_; ++x)
  160. {
  161. for (int i = 0; i < 128; ++i)
  162. {
  163. const dtMeshTile* tile = navMesh->getTileAt(x, z, i);
  164. if (!tile)
  165. continue;
  166. for (int i = 0; i < tile->header->polyCount; ++i)
  167. {
  168. dtPoly* poly = tile->polys + i;
  169. for (unsigned j = 0; j < poly->vertCount; ++j)
  170. {
  171. debug->AddLine(
  172. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  173. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  174. Color::YELLOW,
  175. depthTest
  176. );
  177. }
  178. }
  179. }
  180. }
  181. }
  182. Scene* scene = GetScene();
  183. if (scene)
  184. {
  185. // Draw OffMeshConnection components
  186. if (drawOffMeshConnections_)
  187. {
  188. PODVector<Node*> connections;
  189. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  190. for (unsigned i = 0; i < connections.Size(); ++i)
  191. {
  192. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  193. if (connection && connection->IsEnabledEffective())
  194. connection->DrawDebugGeometry(debug, depthTest);
  195. }
  196. }
  197. // Draw NavArea components
  198. if (drawNavAreas_)
  199. {
  200. PODVector<Node*> areas;
  201. scene->GetChildrenWithComponent<NavArea>(areas, true);
  202. for (unsigned i = 0; i < areas.Size(); ++i)
  203. {
  204. NavArea* area = areas[i]->GetComponent<NavArea>();
  205. if (area && area->IsEnabledEffective())
  206. area->DrawDebugGeometry(debug, depthTest);
  207. }
  208. }
  209. }
  210. }
  211. void NavigationMesh::SetMeshName(const String& newName)
  212. {
  213. meshName_ = newName;
  214. }
  215. void NavigationMesh::SetTileSize(int size)
  216. {
  217. tileSize_ = Max(size, 16);
  218. MarkNetworkUpdate();
  219. }
  220. void NavigationMesh::SetCellSize(float size)
  221. {
  222. cellSize_ = Max(size, M_EPSILON);
  223. MarkNetworkUpdate();
  224. }
  225. void NavigationMesh::SetCellHeight(float height)
  226. {
  227. cellHeight_ = Max(height, M_EPSILON);
  228. MarkNetworkUpdate();
  229. }
  230. void NavigationMesh::SetAgentHeight(float height)
  231. {
  232. agentHeight_ = Max(height, M_EPSILON);
  233. MarkNetworkUpdate();
  234. }
  235. void NavigationMesh::SetAgentRadius(float radius)
  236. {
  237. agentRadius_ = Max(radius, M_EPSILON);
  238. MarkNetworkUpdate();
  239. }
  240. void NavigationMesh::SetAgentMaxClimb(float maxClimb)
  241. {
  242. agentMaxClimb_ = Max(maxClimb, M_EPSILON);
  243. MarkNetworkUpdate();
  244. }
  245. void NavigationMesh::SetAgentMaxSlope(float maxSlope)
  246. {
  247. agentMaxSlope_ = Max(maxSlope, 0.0f);
  248. MarkNetworkUpdate();
  249. }
  250. void NavigationMesh::SetRegionMinSize(float size)
  251. {
  252. regionMinSize_ = Max(size, M_EPSILON);
  253. MarkNetworkUpdate();
  254. }
  255. void NavigationMesh::SetRegionMergeSize(float size)
  256. {
  257. regionMergeSize_ = Max(size, M_EPSILON);
  258. MarkNetworkUpdate();
  259. }
  260. void NavigationMesh::SetEdgeMaxLength(float length)
  261. {
  262. edgeMaxLength_ = Max(length, M_EPSILON);
  263. MarkNetworkUpdate();
  264. }
  265. void NavigationMesh::SetEdgeMaxError(float error)
  266. {
  267. edgeMaxError_ = Max(error, M_EPSILON);
  268. MarkNetworkUpdate();
  269. }
  270. void NavigationMesh::SetDetailSampleDistance(float distance)
  271. {
  272. detailSampleDistance_ = Max(distance, M_EPSILON);
  273. MarkNetworkUpdate();
  274. }
  275. void NavigationMesh::SetDetailSampleMaxError(float error)
  276. {
  277. detailSampleMaxError_ = Max(error, M_EPSILON);
  278. MarkNetworkUpdate();
  279. }
  280. void NavigationMesh::SetPadding(const Vector3& padding)
  281. {
  282. padding_ = padding;
  283. MarkNetworkUpdate();
  284. }
  285. bool NavigationMesh::Build()
  286. {
  287. URHO3D_PROFILE(BuildNavigationMesh);
  288. // Release existing navigation data and zero the bounding box
  289. ReleaseNavigationMesh();
  290. if (!node_)
  291. return false;
  292. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  293. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  294. Vector<NavigationGeometryInfo> geometryList;
  295. CollectGeometries(geometryList);
  296. if (geometryList.Empty())
  297. return true; // Nothing to do
  298. // Build the combined bounding box
  299. for (unsigned i = 0; i < geometryList.Size(); ++i)
  300. boundingBox_.Merge(geometryList[i].boundingBox_);
  301. // Expand bounding box by padding
  302. boundingBox_.min_ -= padding_;
  303. boundingBox_.max_ += padding_;
  304. {
  305. URHO3D_PROFILE(BuildNavigationMesh);
  306. // Calculate number of tiles
  307. int gridW = 0, gridH = 0;
  308. float tileEdgeLength = (float)tileSize_ * cellSize_;
  309. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  310. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  311. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  312. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  313. unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_));
  314. unsigned tileBits = 0;
  315. unsigned temp = maxTiles;
  316. while (temp > 1)
  317. {
  318. temp >>= 1;
  319. ++tileBits;
  320. }
  321. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  322. dtNavMeshParams params;
  323. rcVcopy(params.orig, &boundingBox_.min_.x_);
  324. params.tileWidth = tileEdgeLength;
  325. params.tileHeight = tileEdgeLength;
  326. params.maxTiles = maxTiles;
  327. params.maxPolys = maxPolys;
  328. navMesh_ = dtAllocNavMesh();
  329. if (!navMesh_)
  330. {
  331. URHO3D_LOGERROR("Could not allocate navigation mesh");
  332. return false;
  333. }
  334. if (dtStatusFailed(navMesh_->init(&params)))
  335. {
  336. URHO3D_LOGERROR("Could not initialize navigation mesh");
  337. ReleaseNavigationMesh();
  338. return false;
  339. }
  340. // Build each tile
  341. unsigned numTiles = 0;
  342. for (int z = 0; z < numTilesZ_; ++z)
  343. {
  344. for (int x = 0; x < numTilesX_; ++x)
  345. {
  346. if (BuildTile(geometryList, x, z))
  347. ++numTiles;
  348. }
  349. }
  350. URHO3D_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  351. // Send a notification event to concerned parties that we've been fully rebuilt
  352. {
  353. using namespace NavigationMeshRebuilt;
  354. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  355. buildEventParams[P_NODE] = node_;
  356. buildEventParams[P_MESH] = this;
  357. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  358. }
  359. return true;
  360. }
  361. }
  362. bool NavigationMesh::Build(const BoundingBox& boundingBox)
  363. {
  364. URHO3D_PROFILE(BuildPartialNavigationMesh);
  365. if (!node_)
  366. return false;
  367. if (!navMesh_)
  368. {
  369. URHO3D_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  370. return false;
  371. }
  372. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  373. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  374. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  375. float tileEdgeLength = (float)tileSize_ * cellSize_;
  376. Vector<NavigationGeometryInfo> geometryList;
  377. CollectGeometries(geometryList);
  378. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  379. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  380. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  381. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  382. unsigned numTiles = 0;
  383. for (int z = sz; z <= ez; ++z)
  384. {
  385. for (int x = sx; x <= ex; ++x)
  386. {
  387. if (BuildTile(geometryList, x, z))
  388. ++numTiles;
  389. }
  390. }
  391. URHO3D_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  392. return true;
  393. }
  394. Vector3 NavigationMesh::FindNearestPoint(const Vector3& point, const Vector3& extents, const dtQueryFilter* filter,
  395. dtPolyRef* nearestRef)
  396. {
  397. if (!InitializeQuery())
  398. return point;
  399. const Matrix3x4& transform = node_->GetWorldTransform();
  400. Matrix3x4 inverse = transform.Inverse();
  401. Vector3 localPoint = inverse * point;
  402. Vector3 nearestPoint;
  403. dtPolyRef pointRef;
  404. if (!nearestRef)
  405. nearestRef = &pointRef;
  406. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, filter ? filter : queryFilter_, nearestRef, &nearestPoint.x_);
  407. return *nearestRef ? transform * nearestPoint : point;
  408. }
  409. Vector3 NavigationMesh::MoveAlongSurface(const Vector3& start, const Vector3& end, const Vector3& extents, int maxVisited,
  410. const dtQueryFilter* filter)
  411. {
  412. if (!InitializeQuery())
  413. return end;
  414. const Matrix3x4& transform = node_->GetWorldTransform();
  415. Matrix3x4 inverse = transform.Inverse();
  416. Vector3 localStart = inverse * start;
  417. Vector3 localEnd = inverse * end;
  418. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  419. dtPolyRef startRef;
  420. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
  421. if (!startRef)
  422. return end;
  423. Vector3 resultPos;
  424. int visitedCount = 0;
  425. maxVisited = Max(maxVisited, 0);
  426. PODVector<dtPolyRef> visited((unsigned)maxVisited);
  427. navMeshQuery_->moveAlongSurface(startRef, &localStart.x_, &localEnd.x_, queryFilter, &resultPos.x_, maxVisited ?
  428. &visited[0] : (dtPolyRef*)0, &visitedCount, maxVisited);
  429. return transform * resultPos;
  430. }
  431. void NavigationMesh::FindPath(PODVector<Vector3>& dest, const Vector3& start, const Vector3& end, const Vector3& extents,
  432. const dtQueryFilter* filter)
  433. {
  434. URHO3D_PROFILE(FindPath);
  435. dest.Clear();
  436. if (!InitializeQuery())
  437. return;
  438. // Navigation data is in local space. Transform path points from world to local
  439. const Matrix3x4& transform = node_->GetWorldTransform();
  440. Matrix3x4 inverse = transform.Inverse();
  441. Vector3 localStart = inverse * start;
  442. Vector3 localEnd = inverse * end;
  443. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  444. dtPolyRef startRef;
  445. dtPolyRef endRef;
  446. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
  447. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter, &endRef, 0);
  448. if (!startRef || !endRef)
  449. return;
  450. int numPolys = 0;
  451. int numPathPoints = 0;
  452. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter, pathData_->polys_, &numPolys,
  453. MAX_POLYS);
  454. if (!numPolys)
  455. return;
  456. Vector3 actualLocalEnd = localEnd;
  457. // If full path was not found, clamp end point to the end polygon
  458. if (pathData_->polys_[numPolys - 1] != endRef)
  459. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_, 0);
  460. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  461. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  462. // Transform path result back to world space
  463. for (int i = 0; i < numPathPoints; ++i)
  464. dest.Push(transform * pathData_->pathPoints_[i]);
  465. }
  466. void NavigationMesh::FindPath(NavigationPathData& dest, const Vector3& start, const Vector3& end, const Vector3& extents,
  467. const dtQueryFilter* filter)
  468. {
  469. URHO3D_PROFILE(FindPath);
  470. dest.pathPoints_.Clear();
  471. dest.pathFlags_.Clear();
  472. dest.pathAreas_.Clear();
  473. if (!InitializeQuery())
  474. return;
  475. // Navigation data is in local space. Transform path points from world to local
  476. const Matrix3x4& transform = node_->GetWorldTransform();
  477. Matrix3x4 inverse = transform.Inverse();
  478. Vector3 localStart = inverse * start;
  479. Vector3 localEnd = inverse * end;
  480. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  481. dtPolyRef startRef;
  482. dtPolyRef endRef;
  483. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
  484. navMeshQuery_->findNearestPoly(&localEnd.x_, &extents.x_, queryFilter, &endRef, 0);
  485. if (!startRef || !endRef)
  486. return;
  487. int numPolys = 0;
  488. int numPathPoints = 0;
  489. navMeshQuery_->findPath(startRef, endRef, &localStart.x_, &localEnd.x_, queryFilter, pathData_->polys_, &numPolys,
  490. MAX_POLYS);
  491. if (!numPolys)
  492. return;
  493. Vector3 actualLocalEnd = localEnd;
  494. // If full path was not found, clamp end point to the end polygon
  495. if (pathData_->polys_[numPolys - 1] != endRef)
  496. navMeshQuery_->closestPointOnPoly(pathData_->polys_[numPolys - 1], &localEnd.x_, &actualLocalEnd.x_, 0);
  497. navMeshQuery_->findStraightPath(&localStart.x_, &actualLocalEnd.x_, pathData_->polys_, numPolys,
  498. &pathData_->pathPoints_[0].x_, pathData_->pathFlags_, pathData_->pathPolys_, &numPathPoints, MAX_POLYS);
  499. // Transform path result back to world space
  500. for (int i = 0; i < numPathPoints; ++i)
  501. {
  502. dest.pathPoints_.Push(transform * pathData_->pathPoints_[i]);
  503. dest.pathAreas_.Push(pathData_->pathAreras_[i]);
  504. dest.pathFlags_.Push(pathData_->pathFlags_[i]);
  505. }
  506. }
  507. Vector3 NavigationMesh::GetRandomPoint(const dtQueryFilter* filter, dtPolyRef* randomRef)
  508. {
  509. if (!InitializeQuery())
  510. return Vector3::ZERO;
  511. dtPolyRef polyRef;
  512. Vector3 point(Vector3::ZERO);
  513. navMeshQuery_->findRandomPoint(filter ? filter : queryFilter_, Random, randomRef ? randomRef : &polyRef, &point.x_);
  514. return node_->GetWorldTransform() * point;
  515. }
  516. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents,
  517. const dtQueryFilter* filter, dtPolyRef* randomRef)
  518. {
  519. if (randomRef)
  520. *randomRef = 0;
  521. if (!InitializeQuery())
  522. return center;
  523. const Matrix3x4& transform = node_->GetWorldTransform();
  524. Matrix3x4 inverse = transform.Inverse();
  525. Vector3 localCenter = inverse * center;
  526. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  527. dtPolyRef startRef;
  528. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter, &startRef, 0);
  529. if (!startRef)
  530. return center;
  531. dtPolyRef polyRef;
  532. if (!randomRef)
  533. randomRef = &polyRef;
  534. Vector3 point(localCenter);
  535. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter, Random, randomRef, &point.x_);
  536. return transform * point;
  537. }
  538. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents, const dtQueryFilter* filter,
  539. Vector3* hitPos, Vector3* hitNormal)
  540. {
  541. if (hitPos)
  542. *hitPos = Vector3::ZERO;
  543. if (hitNormal)
  544. *hitNormal = Vector3::DOWN;
  545. if (!InitializeQuery())
  546. return radius;
  547. const Matrix3x4& transform = node_->GetWorldTransform();
  548. Matrix3x4 inverse = transform.Inverse();
  549. Vector3 localPoint = inverse * point;
  550. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  551. dtPolyRef startRef;
  552. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter, &startRef, 0);
  553. if (!startRef)
  554. return radius;
  555. float hitDist = radius;
  556. Vector3 pos;
  557. if (!hitPos)
  558. hitPos = &pos;
  559. Vector3 normal;
  560. if (!hitNormal)
  561. hitNormal = &normal;
  562. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter, &hitDist, &hitPos->x_, &hitNormal->x_);
  563. return hitDist;
  564. }
  565. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents, const dtQueryFilter* filter,
  566. Vector3* hitNormal)
  567. {
  568. if (hitNormal)
  569. *hitNormal = Vector3::DOWN;
  570. if (!InitializeQuery())
  571. return end;
  572. const Matrix3x4& transform = node_->GetWorldTransform();
  573. Matrix3x4 inverse = transform.Inverse();
  574. Vector3 localStart = inverse * start;
  575. Vector3 localEnd = inverse * end;
  576. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  577. dtPolyRef startRef;
  578. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
  579. if (!startRef)
  580. return end;
  581. Vector3 normal;
  582. if (!hitNormal)
  583. hitNormal = &normal;
  584. float t;
  585. int numPolys;
  586. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter, &t, &hitNormal->x_, pathData_->polys_, &numPolys,
  587. MAX_POLYS);
  588. if (t == FLT_MAX)
  589. t = 1.0f;
  590. return start.Lerp(end, t);
  591. }
  592. void NavigationMesh::DrawDebugGeometry(bool depthTest)
  593. {
  594. Scene* scene = GetScene();
  595. if (scene)
  596. {
  597. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  598. if (debug)
  599. DrawDebugGeometry(debug, depthTest);
  600. }
  601. }
  602. void NavigationMesh::SetAreaCost(unsigned areaID, float cost)
  603. {
  604. if (queryFilter_)
  605. queryFilter_->setAreaCost((int)areaID, cost);
  606. }
  607. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  608. {
  609. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  610. }
  611. float NavigationMesh::GetAreaCost(unsigned areaID) const
  612. {
  613. if (queryFilter_)
  614. return queryFilter_->getAreaCost((int)areaID);
  615. return 1.0f;
  616. }
  617. void NavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  618. {
  619. ReleaseNavigationMesh();
  620. if (value.Empty())
  621. return;
  622. MemoryBuffer buffer(value);
  623. boundingBox_ = buffer.ReadBoundingBox();
  624. numTilesX_ = buffer.ReadInt();
  625. numTilesZ_ = buffer.ReadInt();
  626. dtNavMeshParams params;
  627. rcVcopy(params.orig, &boundingBox_.min_.x_);
  628. params.tileWidth = buffer.ReadFloat();
  629. params.tileHeight = buffer.ReadFloat();
  630. params.maxTiles = buffer.ReadInt();
  631. params.maxPolys = buffer.ReadInt();
  632. navMesh_ = dtAllocNavMesh();
  633. if (!navMesh_)
  634. {
  635. URHO3D_LOGERROR("Could not allocate navigation mesh");
  636. return;
  637. }
  638. if (dtStatusFailed(navMesh_->init(&params)))
  639. {
  640. URHO3D_LOGERROR("Could not initialize navigation mesh");
  641. ReleaseNavigationMesh();
  642. return;
  643. }
  644. unsigned numTiles = 0;
  645. while (!buffer.IsEof())
  646. {
  647. /*int x =*/ buffer.ReadInt();
  648. /*int z =*/ buffer.ReadInt();
  649. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  650. unsigned navDataSize = buffer.ReadUInt();
  651. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  652. if (!navData)
  653. {
  654. URHO3D_LOGERROR("Could not allocate data for navigation mesh tile");
  655. return;
  656. }
  657. buffer.Read(navData, navDataSize);
  658. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  659. {
  660. URHO3D_LOGERROR("Failed to add navigation mesh tile");
  661. dtFree(navData);
  662. return;
  663. }
  664. else
  665. ++numTiles;
  666. }
  667. URHO3D_LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  668. }
  669. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  670. {
  671. VectorBuffer ret;
  672. if (navMesh_)
  673. {
  674. ret.WriteBoundingBox(boundingBox_);
  675. ret.WriteInt(numTilesX_);
  676. ret.WriteInt(numTilesZ_);
  677. const dtNavMeshParams* params = navMesh_->getParams();
  678. ret.WriteFloat(params->tileWidth);
  679. ret.WriteFloat(params->tileHeight);
  680. ret.WriteInt(params->maxTiles);
  681. ret.WriteInt(params->maxPolys);
  682. const dtNavMesh* navMesh = navMesh_;
  683. for (int z = 0; z < numTilesZ_; ++z)
  684. {
  685. for (int x = 0; x < numTilesX_; ++x)
  686. {
  687. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  688. if (!tile)
  689. continue;
  690. ret.WriteInt(x);
  691. ret.WriteInt(z);
  692. ret.WriteUInt(navMesh->getTileRef(tile));
  693. ret.WriteUInt((unsigned)tile->dataSize);
  694. ret.Write(tile->data, (unsigned)tile->dataSize);
  695. }
  696. }
  697. }
  698. return ret.GetBuffer();
  699. }
  700. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  701. {
  702. URHO3D_PROFILE(CollectNavigationGeometry);
  703. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  704. // the scene into several navigation meshes
  705. PODVector<Navigable*> navigables;
  706. node_->GetComponents<Navigable>(navigables, true);
  707. HashSet<Node*> processedNodes;
  708. for (unsigned i = 0; i < navigables.Size(); ++i)
  709. {
  710. if (navigables[i]->IsEnabledEffective())
  711. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  712. }
  713. // Get offmesh connections
  714. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  715. PODVector<OffMeshConnection*> connections;
  716. node_->GetComponents<OffMeshConnection>(connections, true);
  717. for (unsigned i = 0; i < connections.Size(); ++i)
  718. {
  719. OffMeshConnection* connection = connections[i];
  720. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  721. {
  722. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  723. NavigationGeometryInfo info;
  724. info.component_ = connection;
  725. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  726. geometryList.Push(info);
  727. }
  728. }
  729. // Get nav area volumes
  730. PODVector<NavArea*> navAreas;
  731. node_->GetComponents<NavArea>(navAreas, true);
  732. for (unsigned i = 0; i < navAreas.Size(); ++i)
  733. {
  734. NavArea* area = navAreas[i];
  735. // Ignore disabled AND any areas that have no meaningful settings
  736. if (area->IsEnabledEffective() && area->GetAreaID() != 0)
  737. {
  738. NavigationGeometryInfo info;
  739. info.component_ = area;
  740. info.boundingBox_ = area->GetWorldBoundingBox();
  741. geometryList.Push(info);
  742. }
  743. }
  744. }
  745. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes,
  746. bool recursive)
  747. {
  748. // Make sure nodes are not included twice
  749. if (processedNodes.Contains(node))
  750. return;
  751. // Exclude obstacles from consideration
  752. if (node->HasComponent<Obstacle>())
  753. return;
  754. processedNodes.Insert(node);
  755. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  756. #ifdef URHO3D_PHYSICS
  757. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  758. // Then fallback to visible geometry
  759. PODVector<CollisionShape*> collisionShapes;
  760. node->GetComponents<CollisionShape>(collisionShapes);
  761. bool collisionShapeFound = false;
  762. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  763. {
  764. CollisionShape* shape = collisionShapes[i];
  765. if (!shape->IsEnabledEffective())
  766. continue;
  767. ShapeType type = shape->GetShapeType();
  768. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  769. {
  770. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  771. NavigationGeometryInfo info;
  772. info.component_ = shape;
  773. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  774. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  775. geometryList.Push(info);
  776. collisionShapeFound = true;
  777. }
  778. }
  779. if (!collisionShapeFound)
  780. #endif
  781. {
  782. PODVector<Drawable*> drawables;
  783. node->GetDerivedComponents<Drawable>(drawables);
  784. for (unsigned i = 0; i < drawables.Size(); ++i)
  785. {
  786. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  787. Drawable* drawable = drawables[i];
  788. if (!drawable->IsEnabledEffective())
  789. continue;
  790. NavigationGeometryInfo info;
  791. if (drawable->GetType() == StaticModel::GetTypeStatic())
  792. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  793. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  794. info.lodLevel_ = 0;
  795. else
  796. continue;
  797. info.component_ = drawable;
  798. info.transform_ = inverse * node->GetWorldTransform();
  799. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  800. geometryList.Push(info);
  801. }
  802. }
  803. if (recursive)
  804. {
  805. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  806. for (unsigned i = 0; i < children.Size(); ++i)
  807. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  808. }
  809. }
  810. void NavigationMesh::GetTileGeometry(NavBuildData* build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  811. {
  812. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  813. for (unsigned i = 0; i < geometryList.Size(); ++i)
  814. {
  815. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  816. {
  817. const Matrix3x4& transform = geometryList[i].transform_;
  818. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  819. {
  820. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  821. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  822. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  823. build->offMeshVertices_.Push(start);
  824. build->offMeshVertices_.Push(end);
  825. build->offMeshRadii_.Push(connection->GetRadius());
  826. build->offMeshFlags_.Push((unsigned short)connection->GetMask());
  827. build->offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  828. build->offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0));
  829. continue;
  830. }
  831. else if (geometryList[i].component_->GetType() == NavArea::GetTypeStatic())
  832. {
  833. NavArea* area = static_cast<NavArea*>(geometryList[i].component_);
  834. NavAreaStub stub;
  835. stub.areaID_ = (unsigned char)area->GetAreaID();
  836. stub.bounds_ = area->GetWorldBoundingBox();
  837. build->navAreas_.Push(stub);
  838. continue;
  839. }
  840. #ifdef URHO3D_PHYSICS
  841. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  842. if (shape)
  843. {
  844. switch (shape->GetShapeType())
  845. {
  846. case SHAPE_TRIANGLEMESH:
  847. {
  848. Model* model = shape->GetModel();
  849. if (!model)
  850. continue;
  851. unsigned lodLevel = shape->GetLodLevel();
  852. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  853. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  854. }
  855. break;
  856. case SHAPE_CONVEXHULL:
  857. {
  858. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  859. if (!data)
  860. continue;
  861. unsigned numVertices = data->vertexCount_;
  862. unsigned numIndices = data->indexCount_;
  863. unsigned destVertexStart = build->vertices_.Size();
  864. for (unsigned j = 0; j < numVertices; ++j)
  865. build->vertices_.Push(transform * data->vertexData_[j]);
  866. for (unsigned j = 0; j < numIndices; ++j)
  867. build->indices_.Push(data->indexData_[j] + destVertexStart);
  868. }
  869. break;
  870. case SHAPE_BOX:
  871. {
  872. unsigned destVertexStart = build->vertices_.Size();
  873. build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  874. build->vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  875. build->vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));
  876. build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));
  877. build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));
  878. build->vertices_.Push(transform * Vector3(0.5f, 0.5f, 0.5f));
  879. build->vertices_.Push(transform * Vector3(0.5f, -0.5f, 0.5f));
  880. build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, 0.5f));
  881. const unsigned indices[] = {
  882. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  883. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  884. };
  885. for (unsigned j = 0; j < 36; ++j)
  886. build->indices_.Push(indices[j] + destVertexStart);
  887. }
  888. break;
  889. default:
  890. break;
  891. }
  892. continue;
  893. }
  894. #endif
  895. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  896. if (drawable)
  897. {
  898. const Vector<SourceBatch>& batches = drawable->GetBatches();
  899. for (unsigned j = 0; j < batches.Size(); ++j)
  900. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  901. }
  902. }
  903. }
  904. }
  905. void NavigationMesh::AddTriMeshGeometry(NavBuildData* build, Geometry* geometry, const Matrix3x4& transform)
  906. {
  907. if (!geometry)
  908. return;
  909. const unsigned char* vertexData;
  910. const unsigned char* indexData;
  911. unsigned vertexSize;
  912. unsigned indexSize;
  913. unsigned elementMask;
  914. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  915. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  916. return;
  917. unsigned srcIndexStart = geometry->GetIndexStart();
  918. unsigned srcIndexCount = geometry->GetIndexCount();
  919. unsigned srcVertexStart = geometry->GetVertexStart();
  920. unsigned srcVertexCount = geometry->GetVertexCount();
  921. if (!srcIndexCount)
  922. return;
  923. unsigned destVertexStart = build->vertices_.Size();
  924. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  925. {
  926. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  927. build->vertices_.Push(vertex);
  928. }
  929. // Copy remapped indices
  930. if (indexSize == sizeof(unsigned short))
  931. {
  932. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  933. const unsigned short* indicesEnd = indices + srcIndexCount;
  934. while (indices < indicesEnd)
  935. {
  936. build->indices_.Push(*indices - srcVertexStart + destVertexStart);
  937. ++indices;
  938. }
  939. }
  940. else
  941. {
  942. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  943. const unsigned* indicesEnd = indices + srcIndexCount;
  944. while (indices < indicesEnd)
  945. {
  946. build->indices_.Push(*indices - srcVertexStart + destVertexStart);
  947. ++indices;
  948. }
  949. }
  950. }
  951. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  952. {
  953. URHO3D_PROFILE(BuildNavigationMeshTile);
  954. // Remove previous tile (if any)
  955. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  956. float tileEdgeLength = (float)tileSize_ * cellSize_;
  957. BoundingBox tileBoundingBox(Vector3(
  958. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  959. boundingBox_.min_.y_,
  960. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  961. ),
  962. Vector3(
  963. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  964. boundingBox_.max_.y_,
  965. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  966. ));
  967. SimpleNavBuildData build;
  968. rcConfig cfg;
  969. memset(&cfg, 0, sizeof cfg);
  970. cfg.cs = cellSize_;
  971. cfg.ch = cellHeight_;
  972. cfg.walkableSlopeAngle = agentMaxSlope_;
  973. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  974. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  975. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  976. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  977. cfg.maxSimplificationError = edgeMaxError_;
  978. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  979. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  980. cfg.maxVertsPerPoly = 6;
  981. cfg.tileSize = tileSize_;
  982. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  983. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  984. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  985. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  986. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  987. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  988. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  989. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  990. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  991. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  992. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  993. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  994. GetTileGeometry(&build, geometryList, expandedBox);
  995. if (build.vertices_.Empty() || build.indices_.Empty())
  996. return true; // Nothing to do
  997. build.heightField_ = rcAllocHeightfield();
  998. if (!build.heightField_)
  999. {
  1000. URHO3D_LOGERROR("Could not allocate heightfield");
  1001. return false;
  1002. }
  1003. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  1004. cfg.ch))
  1005. {
  1006. URHO3D_LOGERROR("Could not create heightfield");
  1007. return false;
  1008. }
  1009. unsigned numTriangles = build.indices_.Size() / 3;
  1010. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  1011. memset(triAreas.Get(), 0, numTriangles);
  1012. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  1013. &build.indices_[0], numTriangles, triAreas.Get());
  1014. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  1015. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  1016. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  1017. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  1018. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  1019. build.compactHeightField_ = rcAllocCompactHeightfield();
  1020. if (!build.compactHeightField_)
  1021. {
  1022. URHO3D_LOGERROR("Could not allocate create compact heightfield");
  1023. return false;
  1024. }
  1025. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  1026. *build.compactHeightField_))
  1027. {
  1028. URHO3D_LOGERROR("Could not build compact heightfield");
  1029. return false;
  1030. }
  1031. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  1032. {
  1033. URHO3D_LOGERROR("Could not erode compact heightfield");
  1034. return false;
  1035. }
  1036. // Mark area volumes
  1037. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  1038. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  1039. build.navAreas_[i].areaID_, *build.compactHeightField_);
  1040. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  1041. {
  1042. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  1043. {
  1044. URHO3D_LOGERROR("Could not build distance field");
  1045. return false;
  1046. }
  1047. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  1048. cfg.mergeRegionArea))
  1049. {
  1050. URHO3D_LOGERROR("Could not build regions");
  1051. return false;
  1052. }
  1053. }
  1054. else
  1055. {
  1056. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  1057. {
  1058. URHO3D_LOGERROR("Could not build monotone regions");
  1059. return false;
  1060. }
  1061. }
  1062. build.contourSet_ = rcAllocContourSet();
  1063. if (!build.contourSet_)
  1064. {
  1065. URHO3D_LOGERROR("Could not allocate contour set");
  1066. return false;
  1067. }
  1068. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  1069. *build.contourSet_))
  1070. {
  1071. URHO3D_LOGERROR("Could not create contours");
  1072. return false;
  1073. }
  1074. build.polyMesh_ = rcAllocPolyMesh();
  1075. if (!build.polyMesh_)
  1076. {
  1077. URHO3D_LOGERROR("Could not allocate poly mesh");
  1078. return false;
  1079. }
  1080. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  1081. {
  1082. URHO3D_LOGERROR("Could not triangulate contours");
  1083. return false;
  1084. }
  1085. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  1086. if (!build.polyMeshDetail_)
  1087. {
  1088. URHO3D_LOGERROR("Could not allocate detail mesh");
  1089. return false;
  1090. }
  1091. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  1092. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  1093. {
  1094. URHO3D_LOGERROR("Could not build detail mesh");
  1095. return false;
  1096. }
  1097. // Set polygon flags
  1098. /// \todo Assignment of flags from navigation areas?
  1099. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  1100. {
  1101. if (build.polyMesh_->areas[i] != RC_NULL_AREA)
  1102. build.polyMesh_->flags[i] = 0x1;
  1103. }
  1104. unsigned char* navData = 0;
  1105. int navDataSize = 0;
  1106. dtNavMeshCreateParams params;
  1107. memset(&params, 0, sizeof params);
  1108. params.verts = build.polyMesh_->verts;
  1109. params.vertCount = build.polyMesh_->nverts;
  1110. params.polys = build.polyMesh_->polys;
  1111. params.polyAreas = build.polyMesh_->areas;
  1112. params.polyFlags = build.polyMesh_->flags;
  1113. params.polyCount = build.polyMesh_->npolys;
  1114. params.nvp = build.polyMesh_->nvp;
  1115. params.detailMeshes = build.polyMeshDetail_->meshes;
  1116. params.detailVerts = build.polyMeshDetail_->verts;
  1117. params.detailVertsCount = build.polyMeshDetail_->nverts;
  1118. params.detailTris = build.polyMeshDetail_->tris;
  1119. params.detailTriCount = build.polyMeshDetail_->ntris;
  1120. params.walkableHeight = agentHeight_;
  1121. params.walkableRadius = agentRadius_;
  1122. params.walkableClimb = agentMaxClimb_;
  1123. params.tileX = x;
  1124. params.tileY = z;
  1125. rcVcopy(params.bmin, build.polyMesh_->bmin);
  1126. rcVcopy(params.bmax, build.polyMesh_->bmax);
  1127. params.cs = cfg.cs;
  1128. params.ch = cfg.ch;
  1129. params.buildBvTree = true;
  1130. // Add off-mesh connections if have them
  1131. if (build.offMeshRadii_.Size())
  1132. {
  1133. params.offMeshConCount = build.offMeshRadii_.Size();
  1134. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  1135. params.offMeshConRad = &build.offMeshRadii_[0];
  1136. params.offMeshConFlags = &build.offMeshFlags_[0];
  1137. params.offMeshConAreas = &build.offMeshAreas_[0];
  1138. params.offMeshConDir = &build.offMeshDir_[0];
  1139. }
  1140. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1141. {
  1142. URHO3D_LOGERROR("Could not build navigation mesh tile data");
  1143. return false;
  1144. }
  1145. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  1146. {
  1147. URHO3D_LOGERROR("Failed to add navigation mesh tile");
  1148. dtFree(navData);
  1149. return false;
  1150. }
  1151. // Send a notification of the rebuild of this tile to anyone interested
  1152. {
  1153. using namespace NavigationAreaRebuilt;
  1154. VariantMap& eventData = GetContext()->GetEventDataMap();
  1155. eventData[P_NODE] = GetNode();
  1156. eventData[P_MESH] = this;
  1157. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  1158. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  1159. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  1160. }
  1161. return true;
  1162. }
  1163. bool NavigationMesh::InitializeQuery()
  1164. {
  1165. if (!navMesh_ || !node_)
  1166. return false;
  1167. if (navMeshQuery_)
  1168. return true;
  1169. navMeshQuery_ = dtAllocNavMeshQuery();
  1170. if (!navMeshQuery_)
  1171. {
  1172. URHO3D_LOGERROR("Could not create navigation mesh query");
  1173. return false;
  1174. }
  1175. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  1176. {
  1177. URHO3D_LOGERROR("Could not init navigation mesh query");
  1178. return false;
  1179. }
  1180. return true;
  1181. }
  1182. void NavigationMesh::ReleaseNavigationMesh()
  1183. {
  1184. dtFreeNavMesh(navMesh_);
  1185. navMesh_ = 0;
  1186. dtFreeNavMeshQuery(navMeshQuery_);
  1187. navMeshQuery_ = 0;
  1188. numTilesX_ = 0;
  1189. numTilesZ_ = 0;
  1190. boundingBox_.Clear();
  1191. }
  1192. void NavigationMesh::SetPartitionType(NavmeshPartitionType ptype)
  1193. {
  1194. partitionType_ = ptype;
  1195. MarkNetworkUpdate();
  1196. }
  1197. void RegisterNavigationLibrary(Context* context)
  1198. {
  1199. Navigable::RegisterObject(context);
  1200. NavigationMesh::RegisterObject(context);
  1201. OffMeshConnection::RegisterObject(context);
  1202. CrowdAgent::RegisterObject(context);
  1203. CrowdManager::RegisterObject(context);
  1204. DynamicNavigationMesh::RegisterObject(context);
  1205. Obstacle::RegisterObject(context);
  1206. NavArea::RegisterObject(context);
  1207. }
  1208. }