NavigationMesh.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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 "../Atomic3D//Model.h"
  29. #include "../Atomic3D/StaticModel.h"
  30. #include "../Atomic3D/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 ATOMIC_PHYSICS
  43. #include "../Physics/CollisionShape.h"
  44. #endif
  45. #include "../Scene/Scene.h"
  46. #include <cfloat>
  47. #include <Detour/include/DetourNavMesh.h>
  48. #include <Detour/include/DetourNavMeshBuilder.h>
  49. #include <Detour/include/DetourNavMeshQuery.h>
  50. #include <Recast/include/Recast.h>
  51. #include "../DebugNew.h"
  52. namespace Atomic
  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. ACCESSOR_ATTRIBUTE("Tile Size", GetTileSize, SetTileSize, int, DEFAULT_TILE_SIZE, AM_DEFAULT);
  129. ACCESSOR_ATTRIBUTE("Cell Size", GetCellSize, SetCellSize, float, DEFAULT_CELL_SIZE, AM_DEFAULT);
  130. ACCESSOR_ATTRIBUTE("Cell Height", GetCellHeight, SetCellHeight, float, DEFAULT_CELL_HEIGHT, AM_DEFAULT);
  131. ACCESSOR_ATTRIBUTE("Agent Height", GetAgentHeight, SetAgentHeight, float, DEFAULT_AGENT_HEIGHT, AM_DEFAULT);
  132. ACCESSOR_ATTRIBUTE("Agent Radius", GetAgentRadius, SetAgentRadius, float, DEFAULT_AGENT_RADIUS, AM_DEFAULT);
  133. ACCESSOR_ATTRIBUTE("Agent Max Climb", GetAgentMaxClimb, SetAgentMaxClimb, float, DEFAULT_AGENT_MAX_CLIMB, AM_DEFAULT);
  134. ACCESSOR_ATTRIBUTE("Agent Max Slope", GetAgentMaxSlope, SetAgentMaxSlope, float, DEFAULT_AGENT_MAX_SLOPE, AM_DEFAULT);
  135. ACCESSOR_ATTRIBUTE("Region Min Size", GetRegionMinSize, SetRegionMinSize, float, DEFAULT_REGION_MIN_SIZE, AM_DEFAULT);
  136. ACCESSOR_ATTRIBUTE("Region Merge Size", GetRegionMergeSize, SetRegionMergeSize, float, DEFAULT_REGION_MERGE_SIZE, AM_DEFAULT);
  137. ACCESSOR_ATTRIBUTE("Edge Max Length", GetEdgeMaxLength, SetEdgeMaxLength, float, DEFAULT_EDGE_MAX_LENGTH, AM_DEFAULT);
  138. ACCESSOR_ATTRIBUTE("Edge Max Error", GetEdgeMaxError, SetEdgeMaxError, float, DEFAULT_EDGE_MAX_ERROR, AM_DEFAULT);
  139. ACCESSOR_ATTRIBUTE("Detail Sample Distance", GetDetailSampleDistance, SetDetailSampleDistance, float,
  140. DEFAULT_DETAIL_SAMPLE_DISTANCE, AM_DEFAULT);
  141. ACCESSOR_ATTRIBUTE("Detail Sample Max Error", GetDetailSampleMaxError, SetDetailSampleMaxError, float,
  142. DEFAULT_DETAIL_SAMPLE_MAX_ERROR, AM_DEFAULT);
  143. ACCESSOR_ATTRIBUTE("Bounding Box Padding", GetPadding, SetPadding, Vector3, Vector3::ONE, AM_DEFAULT);
  144. MIXED_ACCESSOR_ATTRIBUTE("Navigation Data", GetNavigationDataAttr, SetNavigationDataAttr, PODVector<unsigned char>,
  145. Variant::emptyBuffer, AM_FILE | AM_NOEDIT);
  146. ENUM_ACCESSOR_ATTRIBUTE("Partition Type", GetPartitionType, SetPartitionType, NavmeshPartitionType, navmeshPartitionTypeNames,
  147. NAVMESH_PARTITION_WATERSHED, AM_DEFAULT);
  148. ACCESSOR_ATTRIBUTE("Draw OffMeshConnections", GetDrawOffMeshConnections, SetDrawOffMeshConnections, bool, false, AM_DEFAULT);
  149. 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. 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. 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. 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. LOGERROR("Could not allocate navigation mesh");
  332. return false;
  333. }
  334. if (dtStatusFailed(navMesh_->init(&params)))
  335. {
  336. 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. 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. PROFILE(BuildPartialNavigationMesh);
  365. if (!node_)
  366. return false;
  367. if (!navMesh_)
  368. {
  369. 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. 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. 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. 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. Vector3 NavigationMesh::GetRandomPoint(const dtQueryFilter* filter, dtPolyRef* randomRef)
  467. {
  468. if (!InitializeQuery())
  469. return Vector3::ZERO;
  470. dtPolyRef polyRef;
  471. Vector3 point(Vector3::ZERO);
  472. navMeshQuery_->findRandomPoint(filter ? filter : queryFilter_, Random, randomRef ? randomRef : &polyRef, &point.x_);
  473. return node_->GetWorldTransform() * point;
  474. }
  475. Vector3 NavigationMesh::GetRandomPointInCircle(const Vector3& center, float radius, const Vector3& extents,
  476. const dtQueryFilter* filter, dtPolyRef* randomRef)
  477. {
  478. if (randomRef)
  479. *randomRef = 0;
  480. if (!InitializeQuery())
  481. return center;
  482. const Matrix3x4& transform = node_->GetWorldTransform();
  483. Matrix3x4 inverse = transform.Inverse();
  484. Vector3 localCenter = inverse * center;
  485. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  486. dtPolyRef startRef;
  487. navMeshQuery_->findNearestPoly(&localCenter.x_, &extents.x_, queryFilter, &startRef, 0);
  488. if (!startRef)
  489. return center;
  490. dtPolyRef polyRef;
  491. if (!randomRef)
  492. randomRef = &polyRef;
  493. Vector3 point(localCenter);
  494. navMeshQuery_->findRandomPointAroundCircle(startRef, &localCenter.x_, radius, queryFilter, Random, randomRef, &point.x_);
  495. return transform * point;
  496. }
  497. float NavigationMesh::GetDistanceToWall(const Vector3& point, float radius, const Vector3& extents, const dtQueryFilter* filter,
  498. Vector3* hitPos, Vector3* hitNormal)
  499. {
  500. if (hitPos)
  501. *hitPos = Vector3::ZERO;
  502. if (hitNormal)
  503. *hitNormal = Vector3::DOWN;
  504. if (!InitializeQuery())
  505. return radius;
  506. const Matrix3x4& transform = node_->GetWorldTransform();
  507. Matrix3x4 inverse = transform.Inverse();
  508. Vector3 localPoint = inverse * point;
  509. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  510. dtPolyRef startRef;
  511. navMeshQuery_->findNearestPoly(&localPoint.x_, &extents.x_, queryFilter, &startRef, 0);
  512. if (!startRef)
  513. return radius;
  514. float hitDist = radius;
  515. Vector3 pos;
  516. if (!hitPos)
  517. hitPos = &pos;
  518. Vector3 normal;
  519. if (!hitNormal)
  520. hitNormal = &normal;
  521. navMeshQuery_->findDistanceToWall(startRef, &localPoint.x_, radius, queryFilter, &hitDist, &hitPos->x_, &hitNormal->x_);
  522. return hitDist;
  523. }
  524. Vector3 NavigationMesh::Raycast(const Vector3& start, const Vector3& end, const Vector3& extents, const dtQueryFilter* filter,
  525. Vector3* hitNormal)
  526. {
  527. if (hitNormal)
  528. *hitNormal = Vector3::DOWN;
  529. if (!InitializeQuery())
  530. return end;
  531. const Matrix3x4& transform = node_->GetWorldTransform();
  532. Matrix3x4 inverse = transform.Inverse();
  533. Vector3 localStart = inverse * start;
  534. Vector3 localEnd = inverse * end;
  535. const dtQueryFilter* queryFilter = filter ? filter : queryFilter_;
  536. dtPolyRef startRef;
  537. navMeshQuery_->findNearestPoly(&localStart.x_, &extents.x_, queryFilter, &startRef, 0);
  538. if (!startRef)
  539. return end;
  540. Vector3 normal;
  541. if (!hitNormal)
  542. hitNormal = &normal;
  543. float t;
  544. int numPolys;
  545. navMeshQuery_->raycast(startRef, &localStart.x_, &localEnd.x_, queryFilter, &t, &hitNormal->x_, pathData_->polys_, &numPolys,
  546. MAX_POLYS);
  547. if (t == FLT_MAX)
  548. t = 1.0f;
  549. return start.Lerp(end, t);
  550. }
  551. void NavigationMesh::DrawDebugGeometry(bool depthTest)
  552. {
  553. Scene* scene = GetScene();
  554. if (scene)
  555. {
  556. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  557. if (debug)
  558. DrawDebugGeometry(debug, depthTest);
  559. }
  560. }
  561. void NavigationMesh::SetAreaCost(unsigned areaID, float cost)
  562. {
  563. if (queryFilter_)
  564. queryFilter_->setAreaCost((int)areaID, cost);
  565. }
  566. BoundingBox NavigationMesh::GetWorldBoundingBox() const
  567. {
  568. return node_ ? boundingBox_.Transformed(node_->GetWorldTransform()) : boundingBox_;
  569. }
  570. float NavigationMesh::GetAreaCost(unsigned areaID) const
  571. {
  572. if (queryFilter_)
  573. return queryFilter_->getAreaCost((int)areaID);
  574. return 1.0f;
  575. }
  576. void NavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  577. {
  578. ReleaseNavigationMesh();
  579. if (value.Empty())
  580. return;
  581. MemoryBuffer buffer(value);
  582. boundingBox_ = buffer.ReadBoundingBox();
  583. numTilesX_ = buffer.ReadInt();
  584. numTilesZ_ = buffer.ReadInt();
  585. dtNavMeshParams params;
  586. rcVcopy(params.orig, &boundingBox_.min_.x_);
  587. params.tileWidth = buffer.ReadFloat();
  588. params.tileHeight = buffer.ReadFloat();
  589. params.maxTiles = buffer.ReadInt();
  590. params.maxPolys = buffer.ReadInt();
  591. navMesh_ = dtAllocNavMesh();
  592. if (!navMesh_)
  593. {
  594. LOGERROR("Could not allocate navigation mesh");
  595. return;
  596. }
  597. if (dtStatusFailed(navMesh_->init(&params)))
  598. {
  599. LOGERROR("Could not initialize navigation mesh");
  600. ReleaseNavigationMesh();
  601. return;
  602. }
  603. unsigned numTiles = 0;
  604. while (!buffer.IsEof())
  605. {
  606. /*int x =*/ buffer.ReadInt();
  607. /*int z =*/ buffer.ReadInt();
  608. /*dtTileRef tileRef =*/ buffer.ReadUInt();
  609. unsigned navDataSize = buffer.ReadUInt();
  610. unsigned char* navData = (unsigned char*)dtAlloc(navDataSize, DT_ALLOC_PERM);
  611. if (!navData)
  612. {
  613. LOGERROR("Could not allocate data for navigation mesh tile");
  614. return;
  615. }
  616. buffer.Read(navData, navDataSize);
  617. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  618. {
  619. LOGERROR("Failed to add navigation mesh tile");
  620. dtFree(navData);
  621. return;
  622. }
  623. else
  624. ++numTiles;
  625. }
  626. LOGDEBUG("Created navigation mesh with " + String(numTiles) + " tiles from serialized data");
  627. }
  628. PODVector<unsigned char> NavigationMesh::GetNavigationDataAttr() const
  629. {
  630. VectorBuffer ret;
  631. if (navMesh_)
  632. {
  633. ret.WriteBoundingBox(boundingBox_);
  634. ret.WriteInt(numTilesX_);
  635. ret.WriteInt(numTilesZ_);
  636. const dtNavMeshParams* params = navMesh_->getParams();
  637. ret.WriteFloat(params->tileWidth);
  638. ret.WriteFloat(params->tileHeight);
  639. ret.WriteInt(params->maxTiles);
  640. ret.WriteInt(params->maxPolys);
  641. const dtNavMesh* navMesh = navMesh_;
  642. for (int z = 0; z < numTilesZ_; ++z)
  643. {
  644. for (int x = 0; x < numTilesX_; ++x)
  645. {
  646. const dtMeshTile* tile = navMesh->getTileAt(x, z, 0);
  647. if (!tile)
  648. continue;
  649. ret.WriteInt(x);
  650. ret.WriteInt(z);
  651. ret.WriteUInt(navMesh->getTileRef(tile));
  652. ret.WriteUInt((unsigned)tile->dataSize);
  653. ret.Write(tile->data, (unsigned)tile->dataSize);
  654. }
  655. }
  656. }
  657. return ret.GetBuffer();
  658. }
  659. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList)
  660. {
  661. PROFILE(CollectNavigationGeometry);
  662. // Get Navigable components from child nodes, not from whole scene. This makes it possible to partition
  663. // the scene into several navigation meshes
  664. PODVector<Navigable*> navigables;
  665. node_->GetComponents<Navigable>(navigables, true);
  666. HashSet<Node*> processedNodes;
  667. for (unsigned i = 0; i < navigables.Size(); ++i)
  668. {
  669. if (navigables[i]->IsEnabledEffective())
  670. CollectGeometries(geometryList, navigables[i]->GetNode(), processedNodes, navigables[i]->IsRecursive());
  671. }
  672. // Get offmesh connections
  673. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  674. PODVector<OffMeshConnection*> connections;
  675. node_->GetComponents<OffMeshConnection>(connections, true);
  676. for (unsigned i = 0; i < connections.Size(); ++i)
  677. {
  678. OffMeshConnection* connection = connections[i];
  679. if (connection->IsEnabledEffective() && connection->GetEndPoint())
  680. {
  681. const Matrix3x4& transform = connection->GetNode()->GetWorldTransform();
  682. NavigationGeometryInfo info;
  683. info.component_ = connection;
  684. info.boundingBox_ = BoundingBox(Sphere(transform.Translation(), connection->GetRadius())).Transformed(inverse);
  685. geometryList.Push(info);
  686. }
  687. }
  688. // Get nav area volumes
  689. PODVector<NavArea*> navAreas;
  690. node_->GetComponents<NavArea>(navAreas, true);
  691. for (unsigned i = 0; i < navAreas.Size(); ++i)
  692. {
  693. NavArea* area = navAreas[i];
  694. // Ignore disabled AND any areas that have no meaningful settings
  695. if (area->IsEnabledEffective() && area->GetAreaID() != 0)
  696. {
  697. NavigationGeometryInfo info;
  698. info.component_ = area;
  699. info.boundingBox_ = area->GetWorldBoundingBox();
  700. geometryList.Push(info);
  701. }
  702. }
  703. }
  704. void NavigationMesh::CollectGeometries(Vector<NavigationGeometryInfo>& geometryList, Node* node, HashSet<Node*>& processedNodes,
  705. bool recursive)
  706. {
  707. // Make sure nodes are not included twice
  708. if (processedNodes.Contains(node))
  709. return;
  710. // Exclude obstacles from consideration
  711. if (node->HasComponent<Obstacle>())
  712. return;
  713. processedNodes.Insert(node);
  714. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  715. #ifdef ATOMIC_PHYSICS
  716. // Prefer compatible physics collision shapes (triangle mesh, convex hull, box) if found.
  717. // Then fallback to visible geometry
  718. PODVector<CollisionShape*> collisionShapes;
  719. node->GetComponents<CollisionShape>(collisionShapes);
  720. bool collisionShapeFound = false;
  721. for (unsigned i = 0; i < collisionShapes.Size(); ++i)
  722. {
  723. CollisionShape* shape = collisionShapes[i];
  724. if (!shape->IsEnabledEffective())
  725. continue;
  726. ShapeType type = shape->GetShapeType();
  727. if ((type == SHAPE_BOX || type == SHAPE_TRIANGLEMESH || type == SHAPE_CONVEXHULL) && shape->GetCollisionShape())
  728. {
  729. Matrix3x4 shapeTransform(shape->GetPosition(), shape->GetRotation(), shape->GetSize());
  730. NavigationGeometryInfo info;
  731. info.component_ = shape;
  732. info.transform_ = inverse * node->GetWorldTransform() * shapeTransform;
  733. info.boundingBox_ = shape->GetWorldBoundingBox().Transformed(inverse);
  734. geometryList.Push(info);
  735. collisionShapeFound = true;
  736. }
  737. }
  738. if (!collisionShapeFound)
  739. #endif
  740. {
  741. PODVector<Drawable*> drawables;
  742. node->GetDerivedComponents<Drawable>(drawables);
  743. for (unsigned i = 0; i < drawables.Size(); ++i)
  744. {
  745. /// \todo Evaluate whether should handle other types. Now StaticModel & TerrainPatch are supported, others skipped
  746. Drawable* drawable = drawables[i];
  747. if (!drawable->IsEnabledEffective())
  748. continue;
  749. NavigationGeometryInfo info;
  750. if (drawable->GetType() == StaticModel::GetTypeStatic())
  751. info.lodLevel_ = static_cast<StaticModel*>(drawable)->GetOcclusionLodLevel();
  752. else if (drawable->GetType() == TerrainPatch::GetTypeStatic())
  753. info.lodLevel_ = 0;
  754. else
  755. continue;
  756. info.component_ = drawable;
  757. info.transform_ = inverse * node->GetWorldTransform();
  758. info.boundingBox_ = drawable->GetWorldBoundingBox().Transformed(inverse);
  759. geometryList.Push(info);
  760. }
  761. }
  762. if (recursive)
  763. {
  764. const Vector<SharedPtr<Node> >& children = node->GetChildren();
  765. for (unsigned i = 0; i < children.Size(); ++i)
  766. CollectGeometries(geometryList, children[i], processedNodes, recursive);
  767. }
  768. }
  769. void NavigationMesh::GetTileGeometry(NavBuildData* build, Vector<NavigationGeometryInfo>& geometryList, BoundingBox& box)
  770. {
  771. Matrix3x4 inverse = node_->GetWorldTransform().Inverse();
  772. for (unsigned i = 0; i < geometryList.Size(); ++i)
  773. {
  774. if (box.IsInsideFast(geometryList[i].boundingBox_) != OUTSIDE)
  775. {
  776. const Matrix3x4& transform = geometryList[i].transform_;
  777. if (geometryList[i].component_->GetType() == OffMeshConnection::GetTypeStatic())
  778. {
  779. OffMeshConnection* connection = static_cast<OffMeshConnection*>(geometryList[i].component_);
  780. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  781. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  782. build->offMeshVertices_.Push(start);
  783. build->offMeshVertices_.Push(end);
  784. build->offMeshRadii_.Push(connection->GetRadius());
  785. build->offMeshFlags_.Push((unsigned short)connection->GetMask());
  786. build->offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  787. build->offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0));
  788. continue;
  789. }
  790. else if (geometryList[i].component_->GetType() == NavArea::GetTypeStatic())
  791. {
  792. NavArea* area = static_cast<NavArea*>(geometryList[i].component_);
  793. NavAreaStub stub;
  794. stub.areaID_ = (unsigned char)area->GetAreaID();
  795. stub.bounds_ = area->GetWorldBoundingBox();
  796. build->navAreas_.Push(stub);
  797. continue;
  798. }
  799. #ifdef ATOMIC_PHYSICS
  800. CollisionShape* shape = dynamic_cast<CollisionShape*>(geometryList[i].component_);
  801. if (shape)
  802. {
  803. switch (shape->GetShapeType())
  804. {
  805. case SHAPE_TRIANGLEMESH:
  806. {
  807. Model* model = shape->GetModel();
  808. if (!model)
  809. continue;
  810. unsigned lodLevel = shape->GetLodLevel();
  811. for (unsigned j = 0; j < model->GetNumGeometries(); ++j)
  812. AddTriMeshGeometry(build, model->GetGeometry(j, lodLevel), transform);
  813. }
  814. break;
  815. case SHAPE_CONVEXHULL:
  816. {
  817. ConvexData* data = static_cast<ConvexData*>(shape->GetGeometryData());
  818. if (!data)
  819. continue;
  820. unsigned numVertices = data->vertexCount_;
  821. unsigned numIndices = data->indexCount_;
  822. unsigned destVertexStart = build->vertices_.Size();
  823. for (unsigned j = 0; j < numVertices; ++j)
  824. build->vertices_.Push(transform * data->vertexData_[j]);
  825. for (unsigned j = 0; j < numIndices; ++j)
  826. build->indices_.Push(data->indexData_[j] + destVertexStart);
  827. }
  828. break;
  829. case SHAPE_BOX:
  830. {
  831. unsigned destVertexStart = build->vertices_.Size();
  832. build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, -0.5f));
  833. build->vertices_.Push(transform * Vector3(0.5f, 0.5f, -0.5f));
  834. build->vertices_.Push(transform * Vector3(0.5f, -0.5f, -0.5f));
  835. build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, -0.5f));
  836. build->vertices_.Push(transform * Vector3(-0.5f, 0.5f, 0.5f));
  837. build->vertices_.Push(transform * Vector3(0.5f, 0.5f, 0.5f));
  838. build->vertices_.Push(transform * Vector3(0.5f, -0.5f, 0.5f));
  839. build->vertices_.Push(transform * Vector3(-0.5f, -0.5f, 0.5f));
  840. const unsigned indices[] = {
  841. 0, 1, 2, 0, 2, 3, 1, 5, 6, 1, 6, 2, 4, 5, 1, 4, 1, 0, 5, 4, 7, 5, 7, 6,
  842. 4, 0, 3, 4, 3, 7, 1, 0, 4, 1, 4, 5
  843. };
  844. for (unsigned j = 0; j < 36; ++j)
  845. build->indices_.Push(indices[j] + destVertexStart);
  846. }
  847. break;
  848. default:
  849. break;
  850. }
  851. continue;
  852. }
  853. #endif
  854. Drawable* drawable = dynamic_cast<Drawable*>(geometryList[i].component_);
  855. if (drawable)
  856. {
  857. const Vector<SourceBatch>& batches = drawable->GetBatches();
  858. for (unsigned j = 0; j < batches.Size(); ++j)
  859. AddTriMeshGeometry(build, drawable->GetLodGeometry(j, geometryList[i].lodLevel_), transform);
  860. }
  861. }
  862. }
  863. }
  864. void NavigationMesh::AddTriMeshGeometry(NavBuildData* build, Geometry* geometry, const Matrix3x4& transform)
  865. {
  866. if (!geometry)
  867. return;
  868. const unsigned char* vertexData;
  869. const unsigned char* indexData;
  870. unsigned vertexSize;
  871. unsigned indexSize;
  872. unsigned elementMask;
  873. geometry->GetRawData(vertexData, vertexSize, indexData, indexSize, elementMask);
  874. if (!vertexData || !indexData || (elementMask & MASK_POSITION) == 0)
  875. return;
  876. unsigned srcIndexStart = geometry->GetIndexStart();
  877. unsigned srcIndexCount = geometry->GetIndexCount();
  878. unsigned srcVertexStart = geometry->GetVertexStart();
  879. unsigned srcVertexCount = geometry->GetVertexCount();
  880. if (!srcIndexCount)
  881. return;
  882. unsigned destVertexStart = build->vertices_.Size();
  883. for (unsigned k = srcVertexStart; k < srcVertexStart + srcVertexCount; ++k)
  884. {
  885. Vector3 vertex = transform * *((const Vector3*)(&vertexData[k * vertexSize]));
  886. build->vertices_.Push(vertex);
  887. }
  888. // Copy remapped indices
  889. if (indexSize == sizeof(unsigned short))
  890. {
  891. const unsigned short* indices = ((const unsigned short*)indexData) + srcIndexStart;
  892. const unsigned short* indicesEnd = indices + srcIndexCount;
  893. while (indices < indicesEnd)
  894. {
  895. build->indices_.Push(*indices - srcVertexStart + destVertexStart);
  896. ++indices;
  897. }
  898. }
  899. else
  900. {
  901. const unsigned* indices = ((const unsigned*)indexData) + srcIndexStart;
  902. const unsigned* indicesEnd = indices + srcIndexCount;
  903. while (indices < indicesEnd)
  904. {
  905. build->indices_.Push(*indices - srcVertexStart + destVertexStart);
  906. ++indices;
  907. }
  908. }
  909. }
  910. bool NavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z)
  911. {
  912. PROFILE(BuildNavigationMeshTile);
  913. // Remove previous tile (if any)
  914. navMesh_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  915. float tileEdgeLength = (float)tileSize_ * cellSize_;
  916. BoundingBox tileBoundingBox(Vector3(
  917. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  918. boundingBox_.min_.y_,
  919. boundingBox_.min_.z_ + tileEdgeLength * (float)z
  920. ),
  921. Vector3(
  922. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  923. boundingBox_.max_.y_,
  924. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)
  925. ));
  926. SimpleNavBuildData build;
  927. rcConfig cfg;
  928. memset(&cfg, 0, sizeof cfg);
  929. cfg.cs = cellSize_;
  930. cfg.ch = cellHeight_;
  931. cfg.walkableSlopeAngle = agentMaxSlope_;
  932. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  933. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  934. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  935. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  936. cfg.maxSimplificationError = edgeMaxError_;
  937. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  938. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  939. cfg.maxVertsPerPoly = 6;
  940. cfg.tileSize = tileSize_;
  941. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  942. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  943. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  944. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  945. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  946. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  947. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  948. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  949. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  950. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  951. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  952. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  953. GetTileGeometry(&build, geometryList, expandedBox);
  954. if (build.vertices_.Empty() || build.indices_.Empty())
  955. return true; // Nothing to do
  956. build.heightField_ = rcAllocHeightfield();
  957. if (!build.heightField_)
  958. {
  959. LOGERROR("Could not allocate heightfield");
  960. return false;
  961. }
  962. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  963. cfg.ch))
  964. {
  965. LOGERROR("Could not create heightfield");
  966. return false;
  967. }
  968. unsigned numTriangles = build.indices_.Size() / 3;
  969. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  970. memset(triAreas.Get(), 0, numTriangles);
  971. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  972. &build.indices_[0], numTriangles, triAreas.Get());
  973. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  974. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  975. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  976. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  977. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  978. build.compactHeightField_ = rcAllocCompactHeightfield();
  979. if (!build.compactHeightField_)
  980. {
  981. LOGERROR("Could not allocate create compact heightfield");
  982. return false;
  983. }
  984. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  985. *build.compactHeightField_))
  986. {
  987. LOGERROR("Could not build compact heightfield");
  988. return false;
  989. }
  990. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  991. {
  992. LOGERROR("Could not erode compact heightfield");
  993. return false;
  994. }
  995. // Mark area volumes
  996. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  997. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  998. build.navAreas_[i].areaID_, *build.compactHeightField_);
  999. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  1000. {
  1001. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  1002. {
  1003. LOGERROR("Could not build distance field");
  1004. return false;
  1005. }
  1006. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  1007. cfg.mergeRegionArea))
  1008. {
  1009. LOGERROR("Could not build regions");
  1010. return false;
  1011. }
  1012. }
  1013. else
  1014. {
  1015. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  1016. {
  1017. LOGERROR("Could not build monotone regions");
  1018. return false;
  1019. }
  1020. }
  1021. build.contourSet_ = rcAllocContourSet();
  1022. if (!build.contourSet_)
  1023. {
  1024. LOGERROR("Could not allocate contour set");
  1025. return false;
  1026. }
  1027. if (!rcBuildContours(build.ctx_, *build.compactHeightField_, cfg.maxSimplificationError, cfg.maxEdgeLen,
  1028. *build.contourSet_))
  1029. {
  1030. LOGERROR("Could not create contours");
  1031. return false;
  1032. }
  1033. build.polyMesh_ = rcAllocPolyMesh();
  1034. if (!build.polyMesh_)
  1035. {
  1036. LOGERROR("Could not allocate poly mesh");
  1037. return false;
  1038. }
  1039. if (!rcBuildPolyMesh(build.ctx_, *build.contourSet_, cfg.maxVertsPerPoly, *build.polyMesh_))
  1040. {
  1041. LOGERROR("Could not triangulate contours");
  1042. return false;
  1043. }
  1044. build.polyMeshDetail_ = rcAllocPolyMeshDetail();
  1045. if (!build.polyMeshDetail_)
  1046. {
  1047. LOGERROR("Could not allocate detail mesh");
  1048. return false;
  1049. }
  1050. if (!rcBuildPolyMeshDetail(build.ctx_, *build.polyMesh_, *build.compactHeightField_, cfg.detailSampleDist,
  1051. cfg.detailSampleMaxError, *build.polyMeshDetail_))
  1052. {
  1053. LOGERROR("Could not build detail mesh");
  1054. return false;
  1055. }
  1056. // Set polygon flags
  1057. /// \todo Assignment of flags from navigation areas?
  1058. for (int i = 0; i < build.polyMesh_->npolys; ++i)
  1059. {
  1060. if (build.polyMesh_->areas[i] != RC_NULL_AREA)
  1061. build.polyMesh_->flags[i] = 0x1;
  1062. }
  1063. unsigned char* navData = 0;
  1064. int navDataSize = 0;
  1065. dtNavMeshCreateParams params;
  1066. memset(&params, 0, sizeof params);
  1067. params.verts = build.polyMesh_->verts;
  1068. params.vertCount = build.polyMesh_->nverts;
  1069. params.polys = build.polyMesh_->polys;
  1070. params.polyAreas = build.polyMesh_->areas;
  1071. params.polyFlags = build.polyMesh_->flags;
  1072. params.polyCount = build.polyMesh_->npolys;
  1073. params.nvp = build.polyMesh_->nvp;
  1074. params.detailMeshes = build.polyMeshDetail_->meshes;
  1075. params.detailVerts = build.polyMeshDetail_->verts;
  1076. params.detailVertsCount = build.polyMeshDetail_->nverts;
  1077. params.detailTris = build.polyMeshDetail_->tris;
  1078. params.detailTriCount = build.polyMeshDetail_->ntris;
  1079. params.walkableHeight = agentHeight_;
  1080. params.walkableRadius = agentRadius_;
  1081. params.walkableClimb = agentMaxClimb_;
  1082. params.tileX = x;
  1083. params.tileY = z;
  1084. rcVcopy(params.bmin, build.polyMesh_->bmin);
  1085. rcVcopy(params.bmax, build.polyMesh_->bmax);
  1086. params.cs = cfg.cs;
  1087. params.ch = cfg.ch;
  1088. params.buildBvTree = true;
  1089. // Add off-mesh connections if have them
  1090. if (build.offMeshRadii_.Size())
  1091. {
  1092. params.offMeshConCount = build.offMeshRadii_.Size();
  1093. params.offMeshConVerts = &build.offMeshVertices_[0].x_;
  1094. params.offMeshConRad = &build.offMeshRadii_[0];
  1095. params.offMeshConFlags = &build.offMeshFlags_[0];
  1096. params.offMeshConAreas = &build.offMeshAreas_[0];
  1097. params.offMeshConDir = &build.offMeshDir_[0];
  1098. }
  1099. if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
  1100. {
  1101. LOGERROR("Could not build navigation mesh tile data");
  1102. return false;
  1103. }
  1104. if (dtStatusFailed(navMesh_->addTile(navData, navDataSize, DT_TILE_FREE_DATA, 0, 0)))
  1105. {
  1106. LOGERROR("Failed to add navigation mesh tile");
  1107. dtFree(navData);
  1108. return false;
  1109. }
  1110. // Send a notification of the rebuild of this tile to anyone interested
  1111. {
  1112. using namespace NavigationAreaRebuilt;
  1113. VariantMap& eventData = GetContext()->GetEventDataMap();
  1114. eventData[P_NODE] = GetNode();
  1115. eventData[P_MESH] = this;
  1116. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  1117. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  1118. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  1119. }
  1120. return true;
  1121. }
  1122. bool NavigationMesh::InitializeQuery()
  1123. {
  1124. if (!navMesh_ || !node_)
  1125. return false;
  1126. if (navMeshQuery_)
  1127. return true;
  1128. navMeshQuery_ = dtAllocNavMeshQuery();
  1129. if (!navMeshQuery_)
  1130. {
  1131. LOGERROR("Could not create navigation mesh query");
  1132. return false;
  1133. }
  1134. if (dtStatusFailed(navMeshQuery_->init(navMesh_, MAX_POLYS)))
  1135. {
  1136. LOGERROR("Could not init navigation mesh query");
  1137. return false;
  1138. }
  1139. return true;
  1140. }
  1141. void NavigationMesh::ReleaseNavigationMesh()
  1142. {
  1143. dtFreeNavMesh(navMesh_);
  1144. navMesh_ = 0;
  1145. dtFreeNavMeshQuery(navMeshQuery_);
  1146. navMeshQuery_ = 0;
  1147. numTilesX_ = 0;
  1148. numTilesZ_ = 0;
  1149. boundingBox_.min_ = boundingBox_.max_ = Vector3::ZERO;
  1150. boundingBox_.defined_ = false;
  1151. }
  1152. void NavigationMesh::SetPartitionType(NavmeshPartitionType ptype)
  1153. {
  1154. partitionType_ = ptype;
  1155. MarkNetworkUpdate();
  1156. }
  1157. void RegisterNavigationLibrary(Context* context)
  1158. {
  1159. Navigable::RegisterObject(context);
  1160. NavigationMesh::RegisterObject(context);
  1161. OffMeshConnection::RegisterObject(context);
  1162. CrowdAgent::RegisterObject(context);
  1163. CrowdManager::RegisterObject(context);
  1164. DynamicNavigationMesh::RegisterObject(context);
  1165. Obstacle::RegisterObject(context);
  1166. NavArea::RegisterObject(context);
  1167. }
  1168. }