DynamicNavigationMesh.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/Log.h"
  27. #include "../IO/MemoryBuffer.h"
  28. #include "../Navigation/CrowdAgent.h"
  29. #include "../Navigation/DynamicNavigationMesh.h"
  30. #include "../Navigation/NavArea.h"
  31. #include "../Navigation/NavBuildData.h"
  32. #include "../Navigation/NavigationEvents.h"
  33. #include "../Navigation/Obstacle.h"
  34. #include "../Navigation/OffMeshConnection.h"
  35. #include "../Scene/Node.h"
  36. #include "../Scene/Scene.h"
  37. #include "../Scene/SceneEvents.h"
  38. #include <LZ4/lz4.h>
  39. #include <Detour/DetourNavMesh.h>
  40. #include <Detour/DetourNavMeshBuilder.h>
  41. #include <DetourTileCache/DetourTileCache.h>
  42. #include <DetourTileCache/DetourTileCacheBuilder.h>
  43. #include <Recast/Recast.h>
  44. // DebugNew is deliberately not used because the macro 'free' conflicts with DetourTileCache's LinearAllocator interface
  45. //#include "../DebugNew.h"
  46. #define TILECACHE_MAXLAYERS 255
  47. namespace Urho3D
  48. {
  49. extern const char* NAVIGATION_CATEGORY;
  50. static const int DEFAULT_MAX_OBSTACLES = 1024;
  51. static const int DEFAULT_MAX_LAYERS = 16;
  52. struct DynamicNavigationMesh::TileCacheData
  53. {
  54. unsigned char* data;
  55. int dataSize;
  56. };
  57. struct TileCompressor : public dtTileCacheCompressor
  58. {
  59. virtual int maxCompressedSize(const int bufferSize)
  60. {
  61. return (int)(bufferSize * 1.05f);
  62. }
  63. virtual dtStatus compress(const unsigned char* buffer, const int bufferSize,
  64. unsigned char* compressed, const int /*maxCompressedSize*/, int* compressedSize)
  65. {
  66. *compressedSize = LZ4_compress((const char*)buffer, (char*)compressed, bufferSize);
  67. return DT_SUCCESS;
  68. }
  69. virtual dtStatus decompress(const unsigned char* compressed, const int compressedSize,
  70. unsigned char* buffer, const int maxBufferSize, int* bufferSize)
  71. {
  72. *bufferSize = LZ4_decompress_safe((const char*)compressed, (char*)buffer, compressedSize, maxBufferSize);
  73. return *bufferSize < 0 ? DT_FAILURE : DT_SUCCESS;
  74. }
  75. };
  76. struct MeshProcess : public dtTileCacheMeshProcess
  77. {
  78. DynamicNavigationMesh* owner_;
  79. PODVector<Vector3> offMeshVertices_;
  80. PODVector<float> offMeshRadii_;
  81. PODVector<unsigned short> offMeshFlags_;
  82. PODVector<unsigned char> offMeshAreas_;
  83. PODVector<unsigned char> offMeshDir_;
  84. inline MeshProcess(DynamicNavigationMesh* owner) :
  85. owner_(owner)
  86. {
  87. }
  88. virtual void process(struct dtNavMeshCreateParams* params, unsigned char* polyAreas, unsigned short* polyFlags)
  89. {
  90. // Update poly flags from areas.
  91. // \todo Assignment of flags from areas?
  92. for (int i = 0; i < params->polyCount; ++i)
  93. {
  94. if (polyAreas[i] != RC_NULL_AREA)
  95. polyFlags[i] = RC_WALKABLE_AREA;
  96. }
  97. BoundingBox bounds;
  98. rcVcopy(&bounds.min_.x_, params->bmin);
  99. rcVcopy(&bounds.max_.x_, params->bmin);
  100. // collect off-mesh connections
  101. PODVector<OffMeshConnection*> offMeshConnections = owner_->CollectOffMeshConnections(bounds);
  102. if (offMeshConnections.Size() > 0)
  103. {
  104. if (offMeshConnections.Size() != offMeshRadii_.Size())
  105. {
  106. Matrix3x4 inverse = owner_->GetNode()->GetWorldTransform().Inverse();
  107. ClearConnectionData();
  108. for (unsigned i = 0; i < offMeshConnections.Size(); ++i)
  109. {
  110. OffMeshConnection* connection = offMeshConnections[i];
  111. Vector3 start = inverse * connection->GetNode()->GetWorldPosition();
  112. Vector3 end = inverse * connection->GetEndPoint()->GetWorldPosition();
  113. offMeshVertices_.Push(start);
  114. offMeshVertices_.Push(end);
  115. offMeshRadii_.Push(connection->GetRadius());
  116. offMeshFlags_.Push((unsigned short)connection->GetMask());
  117. offMeshAreas_.Push((unsigned char)connection->GetAreaID());
  118. offMeshDir_.Push((unsigned char)(connection->IsBidirectional() ? DT_OFFMESH_CON_BIDIR : 0));
  119. }
  120. }
  121. params->offMeshConCount = offMeshRadii_.Size();
  122. params->offMeshConVerts = &offMeshVertices_[0].x_;
  123. params->offMeshConRad = &offMeshRadii_[0];
  124. params->offMeshConFlags = &offMeshFlags_[0];
  125. params->offMeshConAreas = &offMeshAreas_[0];
  126. params->offMeshConDir = &offMeshDir_[0];
  127. }
  128. }
  129. void ClearConnectionData()
  130. {
  131. offMeshVertices_.Clear();
  132. offMeshRadii_.Clear();
  133. offMeshFlags_.Clear();
  134. offMeshAreas_.Clear();
  135. offMeshDir_.Clear();
  136. }
  137. };
  138. // From the Detour/Recast Sample_TempObstacles.cpp
  139. struct LinearAllocator : public dtTileCacheAlloc
  140. {
  141. unsigned char* buffer;
  142. int capacity;
  143. int top;
  144. int high;
  145. LinearAllocator(const int cap) :
  146. buffer(0), capacity(0), top(0), high(0)
  147. {
  148. resize(cap);
  149. }
  150. ~LinearAllocator()
  151. {
  152. dtFree(buffer);
  153. }
  154. void resize(const int cap)
  155. {
  156. if (buffer)
  157. dtFree(buffer);
  158. buffer = (unsigned char*)dtAlloc(cap, DT_ALLOC_PERM);
  159. capacity = cap;
  160. }
  161. virtual void reset()
  162. {
  163. high = Max(high, top);
  164. top = 0;
  165. }
  166. virtual void* alloc(const int size)
  167. {
  168. if (!buffer)
  169. return 0;
  170. if (top + size > capacity)
  171. return 0;
  172. unsigned char* mem = &buffer[top];
  173. top += size;
  174. return mem;
  175. }
  176. virtual void free(void*)
  177. {
  178. }
  179. };
  180. DynamicNavigationMesh::DynamicNavigationMesh(Context* context) :
  181. NavigationMesh(context),
  182. tileCache_(0),
  183. maxObstacles_(1024),
  184. maxLayers_(DEFAULT_MAX_LAYERS),
  185. drawObstacles_(false)
  186. {
  187. //64 is the largest tile-size that DetourTileCache will tolerate without silently failing
  188. tileSize_ = 64;
  189. partitionType_ = NAVMESH_PARTITION_MONOTONE;
  190. allocator_ = new LinearAllocator(32000); //32kb to start
  191. compressor_ = new TileCompressor();
  192. meshProcessor_ = new MeshProcess(this);
  193. }
  194. DynamicNavigationMesh::~DynamicNavigationMesh()
  195. {
  196. ReleaseNavigationMesh();
  197. delete allocator_;
  198. allocator_ = 0;
  199. delete compressor_;
  200. compressor_ = 0;
  201. delete meshProcessor_;
  202. meshProcessor_ = 0;
  203. }
  204. void DynamicNavigationMesh::RegisterObject(Context* context)
  205. {
  206. context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY);
  207. URHO3D_COPY_BASE_ATTRIBUTES(NavigationMesh);
  208. URHO3D_ACCESSOR_ATTRIBUTE("Max Obstacles", GetMaxObstacles, SetMaxObstacles, unsigned, DEFAULT_MAX_OBSTACLES, AM_DEFAULT);
  209. URHO3D_ACCESSOR_ATTRIBUTE("Max Layers", GetMaxLayers, SetMaxLayers, unsigned, DEFAULT_MAX_LAYERS, AM_DEFAULT);
  210. URHO3D_ACCESSOR_ATTRIBUTE("Draw Obstacles", GetDrawObstacles, SetDrawObstacles, bool, false, AM_DEFAULT);
  211. }
  212. bool DynamicNavigationMesh::Build()
  213. {
  214. URHO3D_PROFILE(BuildNavigationMesh);
  215. // Release existing navigation data and zero the bounding box
  216. ReleaseNavigationMesh();
  217. if (!node_)
  218. return false;
  219. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  220. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  221. Vector<NavigationGeometryInfo> geometryList;
  222. CollectGeometries(geometryList);
  223. if (geometryList.Empty())
  224. return true; // Nothing to do
  225. // Build the combined bounding box
  226. for (unsigned i = 0; i < geometryList.Size(); ++i)
  227. boundingBox_.Merge(geometryList[i].boundingBox_);
  228. // Expand bounding box by padding
  229. boundingBox_.min_ -= padding_;
  230. boundingBox_.max_ += padding_;
  231. {
  232. URHO3D_PROFILE(BuildNavigationMesh);
  233. // Calculate number of tiles
  234. int gridW = 0, gridH = 0;
  235. float tileEdgeLength = (float)tileSize_ * cellSize_;
  236. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  237. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  238. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  239. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  240. unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_)) * maxLayers_;
  241. unsigned tileBits = 0;
  242. unsigned temp = maxTiles;
  243. while (temp > 1)
  244. {
  245. temp >>= 1;
  246. ++tileBits;
  247. }
  248. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  249. dtNavMeshParams params;
  250. rcVcopy(params.orig, &boundingBox_.min_.x_);
  251. params.tileWidth = tileEdgeLength;
  252. params.tileHeight = tileEdgeLength;
  253. params.maxTiles = maxTiles;
  254. params.maxPolys = maxPolys;
  255. navMesh_ = dtAllocNavMesh();
  256. if (!navMesh_)
  257. {
  258. URHO3D_LOGERROR("Could not allocate navigation mesh");
  259. return false;
  260. }
  261. if (dtStatusFailed(navMesh_->init(&params)))
  262. {
  263. URHO3D_LOGERROR("Could not initialize navigation mesh");
  264. ReleaseNavigationMesh();
  265. return false;
  266. }
  267. dtTileCacheParams tileCacheParams;
  268. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  269. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  270. tileCacheParams.ch = cellHeight_;
  271. tileCacheParams.cs = cellSize_;
  272. tileCacheParams.width = tileSize_;
  273. tileCacheParams.height = tileSize_;
  274. tileCacheParams.maxSimplificationError = edgeMaxError_;
  275. tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * maxLayers_;
  276. tileCacheParams.maxObstacles = maxObstacles_;
  277. // Settings from NavigationMesh
  278. tileCacheParams.walkableClimb = agentMaxClimb_;
  279. tileCacheParams.walkableHeight = agentHeight_;
  280. tileCacheParams.walkableRadius = agentRadius_;
  281. tileCache_ = dtAllocTileCache();
  282. if (!tileCache_)
  283. {
  284. URHO3D_LOGERROR("Could not allocate tile cache");
  285. ReleaseNavigationMesh();
  286. return false;
  287. }
  288. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_, compressor_, meshProcessor_)))
  289. {
  290. URHO3D_LOGERROR("Could not initialize tile cache");
  291. ReleaseNavigationMesh();
  292. return false;
  293. }
  294. // Build each tile
  295. unsigned numTiles = 0;
  296. for (int z = 0; z < numTilesZ_; ++z)
  297. {
  298. for (int x = 0; x < numTilesX_; ++x)
  299. {
  300. TileCacheData tiles[TILECACHE_MAXLAYERS];
  301. int layerCt = BuildTile(geometryList, x, z, tiles);
  302. for (int i = 0; i < layerCt; ++i)
  303. {
  304. dtCompressedTileRef tileRef;
  305. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  306. if (dtStatusFailed((dtStatus)status))
  307. {
  308. dtFree(tiles[i].data);
  309. tiles[i].data = 0x0;
  310. }
  311. }
  312. ++numTiles;
  313. }
  314. for (int x = 0; x < numTilesX_; ++x)
  315. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  316. }
  317. // For a full build it's necessary to update the nav mesh
  318. // not doing so will cause dependent components to crash, like CrowdManager
  319. tileCache_->update(0, navMesh_);
  320. URHO3D_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  321. // Send a notification event to concerned parties that we've been fully rebuilt
  322. {
  323. using namespace NavigationMeshRebuilt;
  324. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  325. buildEventParams[P_NODE] = node_;
  326. buildEventParams[P_MESH] = this;
  327. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  328. }
  329. // Scan for obstacles to insert into us
  330. PODVector<Node*> obstacles;
  331. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  332. for (unsigned i = 0; i < obstacles.Size(); ++i)
  333. {
  334. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  335. if (obs && obs->IsEnabledEffective())
  336. AddObstacle(obs);
  337. }
  338. return true;
  339. }
  340. }
  341. bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox)
  342. {
  343. URHO3D_PROFILE(BuildPartialNavigationMesh);
  344. if (!node_)
  345. return false;
  346. if (!navMesh_)
  347. {
  348. URHO3D_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  349. return false;
  350. }
  351. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  352. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  353. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  354. float tileEdgeLength = (float)tileSize_ * cellSize_;
  355. Vector<NavigationGeometryInfo> geometryList;
  356. CollectGeometries(geometryList);
  357. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  358. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  359. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  360. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  361. unsigned numTiles = 0;
  362. for (int z = sz; z <= ez; ++z)
  363. {
  364. for (int x = sx; x <= ex; ++x)
  365. {
  366. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  367. const int existingCt = tileCache_->getTilesAt(x, z, existing, maxLayers_);
  368. for (int i = 0; i < existingCt; ++i)
  369. {
  370. unsigned char* data = 0x0;
  371. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  372. dtFree(data);
  373. }
  374. TileCacheData tiles[TILECACHE_MAXLAYERS];
  375. int layerCt = BuildTile(geometryList, x, z, tiles);
  376. for (int i = 0; i < layerCt; ++i)
  377. {
  378. dtCompressedTileRef tileRef;
  379. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  380. if (dtStatusFailed((dtStatus)status))
  381. {
  382. dtFree(tiles[i].data);
  383. tiles[i].data = 0x0;
  384. }
  385. else
  386. {
  387. tileCache_->buildNavMeshTile(tileRef, navMesh_);
  388. ++numTiles;
  389. }
  390. }
  391. }
  392. }
  393. URHO3D_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  394. return true;
  395. }
  396. void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  397. {
  398. if (!debug || !navMesh_ || !node_)
  399. return;
  400. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  401. const dtNavMesh* navMesh = navMesh_;
  402. for (int z = 0; z < numTilesZ_; ++z)
  403. {
  404. for (int x = 0; x < numTilesX_; ++x)
  405. {
  406. // Get the layers from the tile-cache
  407. const dtMeshTile* tiles[TILECACHE_MAXLAYERS];
  408. int tileCount = navMesh->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  409. for (int i = 0; i < tileCount; ++i)
  410. {
  411. const dtMeshTile* tile = tiles[i];
  412. if (!tile)
  413. continue;
  414. for (int i = 0; i < tile->header->polyCount; ++i)
  415. {
  416. dtPoly* poly = tile->polys + i;
  417. for (unsigned j = 0; j < poly->vertCount; ++j)
  418. {
  419. debug->AddLine(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  420. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  421. Color::YELLOW, depthTest);
  422. }
  423. }
  424. }
  425. }
  426. }
  427. Scene* scene = GetScene();
  428. if (scene)
  429. {
  430. // Draw Obstacle components
  431. if (drawObstacles_)
  432. {
  433. PODVector<Node*> obstacles;
  434. scene->GetChildrenWithComponent<Obstacle>(obstacles, true);
  435. for (unsigned i = 0; i < obstacles.Size(); ++i)
  436. {
  437. Obstacle* obstacle = obstacles[i]->GetComponent<Obstacle>();
  438. if (obstacle && obstacle->IsEnabledEffective())
  439. obstacle->DrawDebugGeometry(debug, depthTest);
  440. }
  441. }
  442. // Draw OffMeshConnection components
  443. if (drawOffMeshConnections_)
  444. {
  445. PODVector<Node*> connections;
  446. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  447. for (unsigned i = 0; i < connections.Size(); ++i)
  448. {
  449. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  450. if (connection && connection->IsEnabledEffective())
  451. connection->DrawDebugGeometry(debug, depthTest);
  452. }
  453. }
  454. // Draw NavArea components
  455. if (drawNavAreas_)
  456. {
  457. PODVector<Node*> areas;
  458. scene->GetChildrenWithComponent<NavArea>(areas, true);
  459. for (unsigned i = 0; i < areas.Size(); ++i)
  460. {
  461. NavArea* area = areas[i]->GetComponent<NavArea>();
  462. if (area && area->IsEnabledEffective())
  463. area->DrawDebugGeometry(debug, depthTest);
  464. }
  465. }
  466. }
  467. }
  468. void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest)
  469. {
  470. Scene* scene = GetScene();
  471. if (scene)
  472. {
  473. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  474. if (debug)
  475. DrawDebugGeometry(debug, depthTest);
  476. }
  477. }
  478. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  479. {
  480. ReleaseNavigationMesh();
  481. if (value.Empty())
  482. return;
  483. MemoryBuffer buffer(value);
  484. boundingBox_ = buffer.ReadBoundingBox();
  485. numTilesX_ = buffer.ReadInt();
  486. numTilesZ_ = buffer.ReadInt();
  487. dtNavMeshParams params;
  488. buffer.Read(&params, sizeof(dtNavMeshParams));
  489. navMesh_ = dtAllocNavMesh();
  490. if (!navMesh_)
  491. {
  492. URHO3D_LOGERROR("Could not allocate navigation mesh");
  493. return;
  494. }
  495. if (dtStatusFailed(navMesh_->init(&params)))
  496. {
  497. URHO3D_LOGERROR("Could not initialize navigation mesh");
  498. ReleaseNavigationMesh();
  499. return;
  500. }
  501. dtTileCacheParams tcParams;
  502. buffer.Read(&tcParams, sizeof(tcParams));
  503. tileCache_ = dtAllocTileCache();
  504. if (!tileCache_)
  505. {
  506. URHO3D_LOGERROR("Could not allocate tile cache");
  507. ReleaseNavigationMesh();
  508. return;
  509. }
  510. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_, compressor_, meshProcessor_)))
  511. {
  512. URHO3D_LOGERROR("Could not initialize tile cache");
  513. ReleaseNavigationMesh();
  514. return;
  515. }
  516. while (!buffer.IsEof())
  517. {
  518. dtTileCacheLayerHeader header;
  519. buffer.Read(&header, sizeof(dtTileCacheLayerHeader));
  520. const int dataSize = buffer.ReadInt();
  521. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  522. buffer.Read(data, (unsigned)dataSize);
  523. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  524. {
  525. URHO3D_LOGERROR("Failed to add tile");
  526. dtFree(data);
  527. return;
  528. }
  529. }
  530. for (int x = 0; x < numTilesX_; ++x)
  531. {
  532. for (int z = 0; z < numTilesZ_; ++z)
  533. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  534. }
  535. tileCache_->update(0, navMesh_);
  536. }
  537. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  538. {
  539. VectorBuffer ret;
  540. if (navMesh_ && tileCache_)
  541. {
  542. ret.WriteBoundingBox(boundingBox_);
  543. ret.WriteInt(numTilesX_);
  544. ret.WriteInt(numTilesZ_);
  545. const dtNavMeshParams* params = navMesh_->getParams();
  546. ret.Write(params, sizeof(dtNavMeshParams));
  547. const dtTileCacheParams* tcParams = tileCache_->getParams();
  548. ret.Write(tcParams, sizeof(dtTileCacheParams));
  549. for (int z = 0; z < numTilesZ_; ++z)
  550. {
  551. for (int x = 0; x < numTilesX_; ++x)
  552. {
  553. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  554. const int ct = tileCache_->getTilesAt(x, z, tiles, maxLayers_);
  555. for (int i = 0; i < ct; ++i)
  556. {
  557. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  558. if (!tile || !tile->header || !tile->dataSize)
  559. continue; // Don't write "void-space" tiles
  560. // The header conveniently has the majority of the information required
  561. ret.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  562. ret.WriteInt(tile->dataSize);
  563. ret.Write(tile->data, (unsigned)tile->dataSize);
  564. }
  565. }
  566. }
  567. }
  568. return ret.GetBuffer();
  569. }
  570. void DynamicNavigationMesh::SetMaxLayers(unsigned maxLayers)
  571. {
  572. // Set 3 as a minimum due to the tendency of layers to be constructed inside the hollow space of stacked objects
  573. // That behavior is unlikely to be expected by the end user
  574. maxLayers_ = Max(3, Min(maxLayers, TILECACHE_MAXLAYERS));
  575. }
  576. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  577. {
  578. URHO3D_PROFILE(BuildNavigationMeshTile);
  579. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  580. float tileEdgeLength = (float)tileSize_ * cellSize_;
  581. BoundingBox tileBoundingBox(Vector3(
  582. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  583. boundingBox_.min_.y_,
  584. boundingBox_.min_.z_ + tileEdgeLength * (float)z),
  585. Vector3(
  586. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  587. boundingBox_.max_.y_,
  588. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
  589. DynamicNavBuildData build(allocator_);
  590. rcConfig cfg;
  591. memset(&cfg, 0, sizeof cfg);
  592. cfg.cs = cellSize_;
  593. cfg.ch = cellHeight_;
  594. cfg.walkableSlopeAngle = agentMaxSlope_;
  595. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  596. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  597. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  598. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  599. cfg.maxSimplificationError = edgeMaxError_;
  600. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  601. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  602. cfg.maxVertsPerPoly = 6;
  603. cfg.tileSize = tileSize_;
  604. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  605. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  606. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  607. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  608. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  609. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  610. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  611. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  612. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  613. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  614. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  615. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  616. GetTileGeometry(&build, geometryList, expandedBox);
  617. if (build.vertices_.Empty() || build.indices_.Empty())
  618. return 0; // Nothing to do
  619. build.heightField_ = rcAllocHeightfield();
  620. if (!build.heightField_)
  621. {
  622. URHO3D_LOGERROR("Could not allocate heightfield");
  623. return 0;
  624. }
  625. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  626. cfg.ch))
  627. {
  628. URHO3D_LOGERROR("Could not create heightfield");
  629. return 0;
  630. }
  631. unsigned numTriangles = build.indices_.Size() / 3;
  632. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  633. memset(triAreas.Get(), 0, numTriangles);
  634. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  635. &build.indices_[0], numTriangles, triAreas.Get());
  636. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  637. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  638. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  639. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  640. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  641. build.compactHeightField_ = rcAllocCompactHeightfield();
  642. if (!build.compactHeightField_)
  643. {
  644. URHO3D_LOGERROR("Could not allocate create compact heightfield");
  645. return 0;
  646. }
  647. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  648. *build.compactHeightField_))
  649. {
  650. URHO3D_LOGERROR("Could not build compact heightfield");
  651. return 0;
  652. }
  653. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  654. {
  655. URHO3D_LOGERROR("Could not erode compact heightfield");
  656. return 0;
  657. }
  658. // area volumes
  659. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  660. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  661. build.navAreas_[i].areaID_, *build.compactHeightField_);
  662. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  663. {
  664. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  665. {
  666. URHO3D_LOGERROR("Could not build distance field");
  667. return 0;
  668. }
  669. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  670. cfg.mergeRegionArea))
  671. {
  672. URHO3D_LOGERROR("Could not build regions");
  673. return 0;
  674. }
  675. }
  676. else
  677. {
  678. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  679. {
  680. URHO3D_LOGERROR("Could not build monotone regions");
  681. return 0;
  682. }
  683. }
  684. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  685. if (!build.heightFieldLayers_)
  686. {
  687. URHO3D_LOGERROR("Could not allocate height field layer set");
  688. return 0;
  689. }
  690. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight,
  691. *build.heightFieldLayers_))
  692. {
  693. URHO3D_LOGERROR("Could not build height field layers");
  694. return 0;
  695. }
  696. int retCt = 0;
  697. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  698. {
  699. dtTileCacheLayerHeader header;
  700. header.magic = DT_TILECACHE_MAGIC;
  701. header.version = DT_TILECACHE_VERSION;
  702. header.tx = x;
  703. header.ty = z;
  704. header.tlayer = i;
  705. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  706. // Tile info.
  707. rcVcopy(header.bmin, layer->bmin);
  708. rcVcopy(header.bmax, layer->bmax);
  709. header.width = (unsigned char)layer->width;
  710. header.height = (unsigned char)layer->height;
  711. header.minx = (unsigned char)layer->minx;
  712. header.maxx = (unsigned char)layer->maxx;
  713. header.miny = (unsigned char)layer->miny;
  714. header.maxy = (unsigned char)layer->maxy;
  715. header.hmin = (unsigned short)layer->hmin;
  716. header.hmax = (unsigned short)layer->hmax;
  717. if (dtStatusFailed(
  718. dtBuildTileCacheLayer(compressor_/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
  719. &(tiles[retCt].data), &tiles[retCt].dataSize)))
  720. {
  721. URHO3D_LOGERROR("Failed to build tile cache layers");
  722. return 0;
  723. }
  724. else
  725. ++retCt;
  726. }
  727. // Send a notification of the rebuild of this tile to anyone interested
  728. {
  729. using namespace NavigationAreaRebuilt;
  730. VariantMap& eventData = GetContext()->GetEventDataMap();
  731. eventData[P_NODE] = GetNode();
  732. eventData[P_MESH] = this;
  733. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  734. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  735. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  736. }
  737. return retCt;
  738. }
  739. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  740. {
  741. PODVector<OffMeshConnection*> connections;
  742. node_->GetComponents<OffMeshConnection>(connections, true);
  743. for (unsigned i = 0; i < connections.Size(); ++i)
  744. {
  745. OffMeshConnection* connection = connections[i];
  746. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  747. {
  748. // discard this connection
  749. connections.Erase(i);
  750. --i;
  751. }
  752. }
  753. return connections;
  754. }
  755. void DynamicNavigationMesh::ReleaseNavigationMesh()
  756. {
  757. NavigationMesh::ReleaseNavigationMesh();
  758. ReleaseTileCache();
  759. }
  760. void DynamicNavigationMesh::ReleaseTileCache()
  761. {
  762. dtFreeTileCache(tileCache_);
  763. tileCache_ = 0;
  764. }
  765. void DynamicNavigationMesh::OnSceneSet(Scene* scene)
  766. {
  767. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  768. if (scene)
  769. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, URHO3D_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  770. else
  771. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  772. }
  773. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  774. {
  775. if (tileCache_)
  776. {
  777. float pos[3];
  778. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  779. rcVcopy(pos, &obsPos.x_);
  780. dtObstacleRef refHolder;
  781. // Because dtTileCache doesn't process obstacle requests while updating tiles
  782. // it's necessary update until sufficient request space is available
  783. while (tileCache_->isObstacleQueueFull())
  784. tileCache_->update(1, navMesh_);
  785. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  786. {
  787. URHO3D_LOGERROR("Failed to add obstacle");
  788. return;
  789. }
  790. obstacle->obstacleId_ = refHolder;
  791. assert(refHolder > 0);
  792. if (!silent)
  793. {
  794. using namespace NavigationObstacleAdded;
  795. VariantMap& eventData = GetContext()->GetEventDataMap();
  796. eventData[P_NODE] = obstacle->GetNode();
  797. eventData[P_OBSTACLE] = obstacle;
  798. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  799. eventData[P_RADIUS] = obstacle->GetRadius();
  800. eventData[P_HEIGHT] = obstacle->GetHeight();
  801. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  802. }
  803. }
  804. }
  805. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  806. {
  807. if (tileCache_)
  808. {
  809. RemoveObstacle(obstacle, true);
  810. AddObstacle(obstacle, true);
  811. }
  812. }
  813. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  814. {
  815. if (tileCache_ && obstacle->obstacleId_ > 0)
  816. {
  817. // Because dtTileCache doesn't process obstacle requests while updating tiles
  818. // it's necessary update until sufficient request space is available
  819. while (tileCache_->isObstacleQueueFull())
  820. tileCache_->update(1, navMesh_);
  821. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  822. {
  823. URHO3D_LOGERROR("Failed to remove obstacle");
  824. return;
  825. }
  826. obstacle->obstacleId_ = 0;
  827. // Require a node in order to send an event
  828. if (!silent && obstacle->GetNode())
  829. {
  830. using namespace NavigationObstacleRemoved;
  831. VariantMap& eventData = GetContext()->GetEventDataMap();
  832. eventData[P_NODE] = obstacle->GetNode();
  833. eventData[P_OBSTACLE] = obstacle;
  834. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  835. eventData[P_RADIUS] = obstacle->GetRadius();
  836. eventData[P_HEIGHT] = obstacle->GetHeight();
  837. SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData);
  838. }
  839. }
  840. }
  841. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  842. {
  843. using namespace SceneSubsystemUpdate;
  844. if (tileCache_ && navMesh_ && IsEnabledEffective())
  845. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  846. }
  847. }