NavigationMesh.cpp 55 KB

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