NavigationMesh.cpp 49 KB

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