NavigationMesh.cpp 49 KB

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