NavigationMesh.cpp 49 KB

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