DynamicNavigationMesh.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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 "../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. static const unsigned 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_default((const char*)buffer, (char*)compressed, bufferSize, LZ4_compressBound(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. }
  198. void DynamicNavigationMesh::RegisterObject(Context* context)
  199. {
  200. context->RegisterFactory<DynamicNavigationMesh>(NAVIGATION_CATEGORY);
  201. URHO3D_COPY_BASE_ATTRIBUTES(NavigationMesh);
  202. URHO3D_ACCESSOR_ATTRIBUTE("Max Obstacles", GetMaxObstacles, SetMaxObstacles, unsigned, DEFAULT_MAX_OBSTACLES, AM_DEFAULT);
  203. URHO3D_ACCESSOR_ATTRIBUTE("Max Layers", GetMaxLayers, SetMaxLayers, unsigned, DEFAULT_MAX_LAYERS, AM_DEFAULT);
  204. URHO3D_ACCESSOR_ATTRIBUTE("Draw Obstacles", GetDrawObstacles, SetDrawObstacles, bool, false, AM_DEFAULT);
  205. }
  206. bool DynamicNavigationMesh::Build()
  207. {
  208. URHO3D_PROFILE(BuildNavigationMesh);
  209. // Release existing navigation data and zero the bounding box
  210. ReleaseNavigationMesh();
  211. if (!node_)
  212. return false;
  213. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  214. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  215. Vector<NavigationGeometryInfo> geometryList;
  216. CollectGeometries(geometryList);
  217. if (geometryList.Empty())
  218. return true; // Nothing to do
  219. // Build the combined bounding box
  220. for (unsigned i = 0; i < geometryList.Size(); ++i)
  221. boundingBox_.Merge(geometryList[i].boundingBox_);
  222. // Expand bounding box by padding
  223. boundingBox_.min_ -= padding_;
  224. boundingBox_.max_ += padding_;
  225. {
  226. URHO3D_PROFILE(BuildNavigationMesh);
  227. // Calculate number of tiles
  228. int gridW = 0, gridH = 0;
  229. float tileEdgeLength = (float)tileSize_ * cellSize_;
  230. rcCalcGridSize(&boundingBox_.min_.x_, &boundingBox_.max_.x_, cellSize_, &gridW, &gridH);
  231. numTilesX_ = (gridW + tileSize_ - 1) / tileSize_;
  232. numTilesZ_ = (gridH + tileSize_ - 1) / tileSize_;
  233. // Calculate max. number of tiles and polygons, 22 bits available to identify both tile & polygon within tile
  234. unsigned maxTiles = NextPowerOfTwo((unsigned)(numTilesX_ * numTilesZ_)) * maxLayers_;
  235. unsigned tileBits = 0;
  236. unsigned temp = maxTiles;
  237. while (temp > 1)
  238. {
  239. temp >>= 1;
  240. ++tileBits;
  241. }
  242. unsigned maxPolys = (unsigned)(1 << (22 - tileBits));
  243. dtNavMeshParams params;
  244. rcVcopy(params.orig, &boundingBox_.min_.x_);
  245. params.tileWidth = tileEdgeLength;
  246. params.tileHeight = tileEdgeLength;
  247. params.maxTiles = maxTiles;
  248. params.maxPolys = maxPolys;
  249. navMesh_ = dtAllocNavMesh();
  250. if (!navMesh_)
  251. {
  252. URHO3D_LOGERROR("Could not allocate navigation mesh");
  253. return false;
  254. }
  255. if (dtStatusFailed(navMesh_->init(&params)))
  256. {
  257. URHO3D_LOGERROR("Could not initialize navigation mesh");
  258. ReleaseNavigationMesh();
  259. return false;
  260. }
  261. dtTileCacheParams tileCacheParams;
  262. memset(&tileCacheParams, 0, sizeof(tileCacheParams));
  263. rcVcopy(tileCacheParams.orig, &boundingBox_.min_.x_);
  264. tileCacheParams.ch = cellHeight_;
  265. tileCacheParams.cs = cellSize_;
  266. tileCacheParams.width = tileSize_;
  267. tileCacheParams.height = tileSize_;
  268. tileCacheParams.maxSimplificationError = edgeMaxError_;
  269. tileCacheParams.maxTiles = numTilesX_ * numTilesZ_ * maxLayers_;
  270. tileCacheParams.maxObstacles = maxObstacles_;
  271. // Settings from NavigationMesh
  272. tileCacheParams.walkableClimb = agentMaxClimb_;
  273. tileCacheParams.walkableHeight = agentHeight_;
  274. tileCacheParams.walkableRadius = agentRadius_;
  275. tileCache_ = dtAllocTileCache();
  276. if (!tileCache_)
  277. {
  278. URHO3D_LOGERROR("Could not allocate tile cache");
  279. ReleaseNavigationMesh();
  280. return false;
  281. }
  282. if (dtStatusFailed(tileCache_->init(&tileCacheParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  283. {
  284. URHO3D_LOGERROR("Could not initialize tile cache");
  285. ReleaseNavigationMesh();
  286. return false;
  287. }
  288. // Build each tile
  289. unsigned numTiles = 0;
  290. for (int z = 0; z < numTilesZ_; ++z)
  291. {
  292. for (int x = 0; x < numTilesX_; ++x)
  293. {
  294. TileCacheData tiles[TILECACHE_MAXLAYERS];
  295. int layerCt = BuildTile(geometryList, x, z, tiles);
  296. for (int i = 0; i < layerCt; ++i)
  297. {
  298. dtCompressedTileRef tileRef;
  299. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  300. if (dtStatusFailed((dtStatus)status))
  301. {
  302. dtFree(tiles[i].data);
  303. tiles[i].data = 0x0;
  304. }
  305. }
  306. ++numTiles;
  307. }
  308. for (int x = 0; x < numTilesX_; ++x)
  309. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  310. }
  311. // For a full build it's necessary to update the nav mesh
  312. // not doing so will cause dependent components to crash, like CrowdManager
  313. tileCache_->update(0, navMesh_);
  314. URHO3D_LOGDEBUG("Built navigation mesh with " + String(numTiles) + " tiles");
  315. // Send a notification event to concerned parties that we've been fully rebuilt
  316. {
  317. using namespace NavigationMeshRebuilt;
  318. VariantMap& buildEventParams = GetContext()->GetEventDataMap();
  319. buildEventParams[P_NODE] = node_;
  320. buildEventParams[P_MESH] = this;
  321. SendEvent(E_NAVIGATION_MESH_REBUILT, buildEventParams);
  322. }
  323. // Scan for obstacles to insert into us
  324. PODVector<Node*> obstacles;
  325. GetScene()->GetChildrenWithComponent<Obstacle>(obstacles, true);
  326. for (unsigned i = 0; i < obstacles.Size(); ++i)
  327. {
  328. Obstacle* obs = obstacles[i]->GetComponent<Obstacle>();
  329. if (obs && obs->IsEnabledEffective())
  330. AddObstacle(obs);
  331. }
  332. return true;
  333. }
  334. }
  335. bool DynamicNavigationMesh::Build(const BoundingBox& boundingBox)
  336. {
  337. URHO3D_PROFILE(BuildPartialNavigationMesh);
  338. if (!node_)
  339. return false;
  340. if (!navMesh_)
  341. {
  342. URHO3D_LOGERROR("Navigation mesh must first be built fully before it can be partially rebuilt");
  343. return false;
  344. }
  345. if (!node_->GetWorldScale().Equals(Vector3::ONE))
  346. URHO3D_LOGWARNING("Navigation mesh root node has scaling. Agent parameters may not work as intended");
  347. BoundingBox localSpaceBox = boundingBox.Transformed(node_->GetWorldTransform().Inverse());
  348. float tileEdgeLength = (float)tileSize_ * cellSize_;
  349. Vector<NavigationGeometryInfo> geometryList;
  350. CollectGeometries(geometryList);
  351. int sx = Clamp((int)((localSpaceBox.min_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  352. int sz = Clamp((int)((localSpaceBox.min_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  353. int ex = Clamp((int)((localSpaceBox.max_.x_ - boundingBox_.min_.x_) / tileEdgeLength), 0, numTilesX_ - 1);
  354. int ez = Clamp((int)((localSpaceBox.max_.z_ - boundingBox_.min_.z_) / tileEdgeLength), 0, numTilesZ_ - 1);
  355. unsigned numTiles = 0;
  356. for (int z = sz; z <= ez; ++z)
  357. {
  358. for (int x = sx; x <= ex; ++x)
  359. {
  360. dtCompressedTileRef existing[TILECACHE_MAXLAYERS];
  361. const int existingCt = tileCache_->getTilesAt(x, z, existing, maxLayers_);
  362. for (int i = 0; i < existingCt; ++i)
  363. {
  364. unsigned char* data = 0x0;
  365. if (!dtStatusFailed(tileCache_->removeTile(existing[i], &data, 0)) && data != 0x0)
  366. dtFree(data);
  367. }
  368. TileCacheData tiles[TILECACHE_MAXLAYERS];
  369. int layerCt = BuildTile(geometryList, x, z, tiles);
  370. for (int i = 0; i < layerCt; ++i)
  371. {
  372. dtCompressedTileRef tileRef;
  373. int status = tileCache_->addTile(tiles[i].data, tiles[i].dataSize, DT_COMPRESSEDTILE_FREE_DATA, &tileRef);
  374. if (dtStatusFailed((dtStatus)status))
  375. {
  376. dtFree(tiles[i].data);
  377. tiles[i].data = 0x0;
  378. }
  379. else
  380. {
  381. tileCache_->buildNavMeshTile(tileRef, navMesh_);
  382. ++numTiles;
  383. }
  384. }
  385. }
  386. }
  387. URHO3D_LOGDEBUG("Rebuilt " + String(numTiles) + " tiles of the navigation mesh");
  388. return true;
  389. }
  390. void DynamicNavigationMesh::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  391. {
  392. if (!debug || !navMesh_ || !node_)
  393. return;
  394. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  395. const dtNavMesh* navMesh = navMesh_;
  396. for (int z = 0; z < numTilesZ_; ++z)
  397. {
  398. for (int x = 0; x < numTilesX_; ++x)
  399. {
  400. // Get the layers from the tile-cache
  401. const dtMeshTile* tiles[TILECACHE_MAXLAYERS];
  402. int tileCount = navMesh->getTilesAt(x, z, tiles, TILECACHE_MAXLAYERS);
  403. for (int i = 0; i < tileCount; ++i)
  404. {
  405. const dtMeshTile* tile = tiles[i];
  406. if (!tile)
  407. continue;
  408. for (int i = 0; i < tile->header->polyCount; ++i)
  409. {
  410. dtPoly* poly = tile->polys + i;
  411. for (unsigned j = 0; j < poly->vertCount; ++j)
  412. {
  413. debug->AddLine(worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[j] * 3]),
  414. worldTransform * *reinterpret_cast<const Vector3*>(&tile->verts[poly->verts[(j + 1) % poly->vertCount] * 3]),
  415. Color::YELLOW, depthTest);
  416. }
  417. }
  418. }
  419. }
  420. }
  421. Scene* scene = GetScene();
  422. if (scene)
  423. {
  424. // Draw Obstacle components
  425. if (drawObstacles_)
  426. {
  427. PODVector<Node*> obstacles;
  428. scene->GetChildrenWithComponent<Obstacle>(obstacles, true);
  429. for (unsigned i = 0; i < obstacles.Size(); ++i)
  430. {
  431. Obstacle* obstacle = obstacles[i]->GetComponent<Obstacle>();
  432. if (obstacle && obstacle->IsEnabledEffective())
  433. obstacle->DrawDebugGeometry(debug, depthTest);
  434. }
  435. }
  436. // Draw OffMeshConnection components
  437. if (drawOffMeshConnections_)
  438. {
  439. PODVector<Node*> connections;
  440. scene->GetChildrenWithComponent<OffMeshConnection>(connections, true);
  441. for (unsigned i = 0; i < connections.Size(); ++i)
  442. {
  443. OffMeshConnection* connection = connections[i]->GetComponent<OffMeshConnection>();
  444. if (connection && connection->IsEnabledEffective())
  445. connection->DrawDebugGeometry(debug, depthTest);
  446. }
  447. }
  448. // Draw NavArea components
  449. if (drawNavAreas_)
  450. {
  451. PODVector<Node*> areas;
  452. scene->GetChildrenWithComponent<NavArea>(areas, true);
  453. for (unsigned i = 0; i < areas.Size(); ++i)
  454. {
  455. NavArea* area = areas[i]->GetComponent<NavArea>();
  456. if (area && area->IsEnabledEffective())
  457. area->DrawDebugGeometry(debug, depthTest);
  458. }
  459. }
  460. }
  461. }
  462. void DynamicNavigationMesh::DrawDebugGeometry(bool depthTest)
  463. {
  464. Scene* scene = GetScene();
  465. if (scene)
  466. {
  467. DebugRenderer* debug = scene->GetComponent<DebugRenderer>();
  468. if (debug)
  469. DrawDebugGeometry(debug, depthTest);
  470. }
  471. }
  472. void DynamicNavigationMesh::SetNavigationDataAttr(const PODVector<unsigned char>& value)
  473. {
  474. ReleaseNavigationMesh();
  475. if (value.Empty())
  476. return;
  477. MemoryBuffer buffer(value);
  478. boundingBox_ = buffer.ReadBoundingBox();
  479. numTilesX_ = buffer.ReadInt();
  480. numTilesZ_ = buffer.ReadInt();
  481. dtNavMeshParams params;
  482. buffer.Read(&params, sizeof(dtNavMeshParams));
  483. navMesh_ = dtAllocNavMesh();
  484. if (!navMesh_)
  485. {
  486. URHO3D_LOGERROR("Could not allocate navigation mesh");
  487. return;
  488. }
  489. if (dtStatusFailed(navMesh_->init(&params)))
  490. {
  491. URHO3D_LOGERROR("Could not initialize navigation mesh");
  492. ReleaseNavigationMesh();
  493. return;
  494. }
  495. dtTileCacheParams tcParams;
  496. buffer.Read(&tcParams, sizeof(tcParams));
  497. tileCache_ = dtAllocTileCache();
  498. if (!tileCache_)
  499. {
  500. URHO3D_LOGERROR("Could not allocate tile cache");
  501. ReleaseNavigationMesh();
  502. return;
  503. }
  504. if (dtStatusFailed(tileCache_->init(&tcParams, allocator_.Get(), compressor_.Get(), meshProcessor_.Get())))
  505. {
  506. URHO3D_LOGERROR("Could not initialize tile cache");
  507. ReleaseNavigationMesh();
  508. return;
  509. }
  510. while (!buffer.IsEof())
  511. {
  512. dtTileCacheLayerHeader header;
  513. buffer.Read(&header, sizeof(dtTileCacheLayerHeader));
  514. const int dataSize = buffer.ReadInt();
  515. unsigned char* data = (unsigned char*)dtAlloc(dataSize, DT_ALLOC_PERM);
  516. buffer.Read(data, (unsigned)dataSize);
  517. if (dtStatusFailed(tileCache_->addTile(data, dataSize, DT_TILE_FREE_DATA, 0)))
  518. {
  519. URHO3D_LOGERROR("Failed to add tile");
  520. dtFree(data);
  521. return;
  522. }
  523. }
  524. for (int x = 0; x < numTilesX_; ++x)
  525. {
  526. for (int z = 0; z < numTilesZ_; ++z)
  527. tileCache_->buildNavMeshTilesAt(x, z, navMesh_);
  528. }
  529. tileCache_->update(0, navMesh_);
  530. }
  531. PODVector<unsigned char> DynamicNavigationMesh::GetNavigationDataAttr() const
  532. {
  533. VectorBuffer ret;
  534. if (navMesh_ && tileCache_)
  535. {
  536. ret.WriteBoundingBox(boundingBox_);
  537. ret.WriteInt(numTilesX_);
  538. ret.WriteInt(numTilesZ_);
  539. const dtNavMeshParams* params = navMesh_->getParams();
  540. ret.Write(params, sizeof(dtNavMeshParams));
  541. const dtTileCacheParams* tcParams = tileCache_->getParams();
  542. ret.Write(tcParams, sizeof(dtTileCacheParams));
  543. for (int z = 0; z < numTilesZ_; ++z)
  544. {
  545. for (int x = 0; x < numTilesX_; ++x)
  546. {
  547. dtCompressedTileRef tiles[TILECACHE_MAXLAYERS];
  548. const int ct = tileCache_->getTilesAt(x, z, tiles, maxLayers_);
  549. for (int i = 0; i < ct; ++i)
  550. {
  551. const dtCompressedTile* tile = tileCache_->getTileByRef(tiles[i]);
  552. if (!tile || !tile->header || !tile->dataSize)
  553. continue; // Don't write "void-space" tiles
  554. // The header conveniently has the majority of the information required
  555. ret.Write(tile->header, sizeof(dtTileCacheLayerHeader));
  556. ret.WriteInt(tile->dataSize);
  557. ret.Write(tile->data, (unsigned)tile->dataSize);
  558. }
  559. }
  560. }
  561. }
  562. return ret.GetBuffer();
  563. }
  564. void DynamicNavigationMesh::SetMaxLayers(unsigned maxLayers)
  565. {
  566. // Set 3 as a minimum due to the tendency of layers to be constructed inside the hollow space of stacked objects
  567. // That behavior is unlikely to be expected by the end user
  568. maxLayers_ = Max(3U, Min(maxLayers, TILECACHE_MAXLAYERS));
  569. }
  570. int DynamicNavigationMesh::BuildTile(Vector<NavigationGeometryInfo>& geometryList, int x, int z, TileCacheData* tiles)
  571. {
  572. URHO3D_PROFILE(BuildNavigationMeshTile);
  573. tileCache_->removeTile(navMesh_->getTileRefAt(x, z, 0), 0, 0);
  574. float tileEdgeLength = (float)tileSize_ * cellSize_;
  575. BoundingBox tileBoundingBox(Vector3(
  576. boundingBox_.min_.x_ + tileEdgeLength * (float)x,
  577. boundingBox_.min_.y_,
  578. boundingBox_.min_.z_ + tileEdgeLength * (float)z),
  579. Vector3(
  580. boundingBox_.min_.x_ + tileEdgeLength * (float)(x + 1),
  581. boundingBox_.max_.y_,
  582. boundingBox_.min_.z_ + tileEdgeLength * (float)(z + 1)));
  583. DynamicNavBuildData build(allocator_.Get());
  584. rcConfig cfg;
  585. memset(&cfg, 0, sizeof cfg);
  586. cfg.cs = cellSize_;
  587. cfg.ch = cellHeight_;
  588. cfg.walkableSlopeAngle = agentMaxSlope_;
  589. cfg.walkableHeight = (int)ceilf(agentHeight_ / cfg.ch);
  590. cfg.walkableClimb = (int)floorf(agentMaxClimb_ / cfg.ch);
  591. cfg.walkableRadius = (int)ceilf(agentRadius_ / cfg.cs);
  592. cfg.maxEdgeLen = (int)(edgeMaxLength_ / cellSize_);
  593. cfg.maxSimplificationError = edgeMaxError_;
  594. cfg.minRegionArea = (int)sqrtf(regionMinSize_);
  595. cfg.mergeRegionArea = (int)sqrtf(regionMergeSize_);
  596. cfg.maxVertsPerPoly = 6;
  597. cfg.tileSize = tileSize_;
  598. cfg.borderSize = cfg.walkableRadius + 3; // Add padding
  599. cfg.width = cfg.tileSize + cfg.borderSize * 2;
  600. cfg.height = cfg.tileSize + cfg.borderSize * 2;
  601. cfg.detailSampleDist = detailSampleDistance_ < 0.9f ? 0.0f : cellSize_ * detailSampleDistance_;
  602. cfg.detailSampleMaxError = cellHeight_ * detailSampleMaxError_;
  603. rcVcopy(cfg.bmin, &tileBoundingBox.min_.x_);
  604. rcVcopy(cfg.bmax, &tileBoundingBox.max_.x_);
  605. cfg.bmin[0] -= cfg.borderSize * cfg.cs;
  606. cfg.bmin[2] -= cfg.borderSize * cfg.cs;
  607. cfg.bmax[0] += cfg.borderSize * cfg.cs;
  608. cfg.bmax[2] += cfg.borderSize * cfg.cs;
  609. BoundingBox expandedBox(*reinterpret_cast<Vector3*>(cfg.bmin), *reinterpret_cast<Vector3*>(cfg.bmax));
  610. GetTileGeometry(&build, geometryList, expandedBox);
  611. if (build.vertices_.Empty() || build.indices_.Empty())
  612. return 0; // Nothing to do
  613. build.heightField_ = rcAllocHeightfield();
  614. if (!build.heightField_)
  615. {
  616. URHO3D_LOGERROR("Could not allocate heightfield");
  617. return 0;
  618. }
  619. if (!rcCreateHeightfield(build.ctx_, *build.heightField_, cfg.width, cfg.height, cfg.bmin, cfg.bmax, cfg.cs,
  620. cfg.ch))
  621. {
  622. URHO3D_LOGERROR("Could not create heightfield");
  623. return 0;
  624. }
  625. unsigned numTriangles = build.indices_.Size() / 3;
  626. SharedArrayPtr<unsigned char> triAreas(new unsigned char[numTriangles]);
  627. memset(triAreas.Get(), 0, numTriangles);
  628. rcMarkWalkableTriangles(build.ctx_, cfg.walkableSlopeAngle, &build.vertices_[0].x_, build.vertices_.Size(),
  629. &build.indices_[0], numTriangles, triAreas.Get());
  630. rcRasterizeTriangles(build.ctx_, &build.vertices_[0].x_, build.vertices_.Size(), &build.indices_[0],
  631. triAreas.Get(), numTriangles, *build.heightField_, cfg.walkableClimb);
  632. rcFilterLowHangingWalkableObstacles(build.ctx_, cfg.walkableClimb, *build.heightField_);
  633. rcFilterLedgeSpans(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_);
  634. rcFilterWalkableLowHeightSpans(build.ctx_, cfg.walkableHeight, *build.heightField_);
  635. build.compactHeightField_ = rcAllocCompactHeightfield();
  636. if (!build.compactHeightField_)
  637. {
  638. URHO3D_LOGERROR("Could not allocate create compact heightfield");
  639. return 0;
  640. }
  641. if (!rcBuildCompactHeightfield(build.ctx_, cfg.walkableHeight, cfg.walkableClimb, *build.heightField_,
  642. *build.compactHeightField_))
  643. {
  644. URHO3D_LOGERROR("Could not build compact heightfield");
  645. return 0;
  646. }
  647. if (!rcErodeWalkableArea(build.ctx_, cfg.walkableRadius, *build.compactHeightField_))
  648. {
  649. URHO3D_LOGERROR("Could not erode compact heightfield");
  650. return 0;
  651. }
  652. // area volumes
  653. for (unsigned i = 0; i < build.navAreas_.Size(); ++i)
  654. rcMarkBoxArea(build.ctx_, &build.navAreas_[i].bounds_.min_.x_, &build.navAreas_[i].bounds_.max_.x_,
  655. build.navAreas_[i].areaID_, *build.compactHeightField_);
  656. if (this->partitionType_ == NAVMESH_PARTITION_WATERSHED)
  657. {
  658. if (!rcBuildDistanceField(build.ctx_, *build.compactHeightField_))
  659. {
  660. URHO3D_LOGERROR("Could not build distance field");
  661. return 0;
  662. }
  663. if (!rcBuildRegions(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea,
  664. cfg.mergeRegionArea))
  665. {
  666. URHO3D_LOGERROR("Could not build regions");
  667. return 0;
  668. }
  669. }
  670. else
  671. {
  672. if (!rcBuildRegionsMonotone(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea))
  673. {
  674. URHO3D_LOGERROR("Could not build monotone regions");
  675. return 0;
  676. }
  677. }
  678. build.heightFieldLayers_ = rcAllocHeightfieldLayerSet();
  679. if (!build.heightFieldLayers_)
  680. {
  681. URHO3D_LOGERROR("Could not allocate height field layer set");
  682. return 0;
  683. }
  684. if (!rcBuildHeightfieldLayers(build.ctx_, *build.compactHeightField_, cfg.borderSize, cfg.walkableHeight,
  685. *build.heightFieldLayers_))
  686. {
  687. URHO3D_LOGERROR("Could not build height field layers");
  688. return 0;
  689. }
  690. int retCt = 0;
  691. for (int i = 0; i < build.heightFieldLayers_->nlayers; ++i)
  692. {
  693. dtTileCacheLayerHeader header;
  694. header.magic = DT_TILECACHE_MAGIC;
  695. header.version = DT_TILECACHE_VERSION;
  696. header.tx = x;
  697. header.ty = z;
  698. header.tlayer = i;
  699. rcHeightfieldLayer* layer = &build.heightFieldLayers_->layers[i];
  700. // Tile info.
  701. rcVcopy(header.bmin, layer->bmin);
  702. rcVcopy(header.bmax, layer->bmax);
  703. header.width = (unsigned char)layer->width;
  704. header.height = (unsigned char)layer->height;
  705. header.minx = (unsigned char)layer->minx;
  706. header.maxx = (unsigned char)layer->maxx;
  707. header.miny = (unsigned char)layer->miny;
  708. header.maxy = (unsigned char)layer->maxy;
  709. header.hmin = (unsigned short)layer->hmin;
  710. header.hmax = (unsigned short)layer->hmax;
  711. if (dtStatusFailed(
  712. dtBuildTileCacheLayer(compressor_.Get()/*compressor*/, &header, layer->heights, layer->areas/*areas*/, layer->cons,
  713. &(tiles[retCt].data), &tiles[retCt].dataSize)))
  714. {
  715. URHO3D_LOGERROR("Failed to build tile cache layers");
  716. return 0;
  717. }
  718. else
  719. ++retCt;
  720. }
  721. // Send a notification of the rebuild of this tile to anyone interested
  722. {
  723. using namespace NavigationAreaRebuilt;
  724. VariantMap& eventData = GetContext()->GetEventDataMap();
  725. eventData[P_NODE] = GetNode();
  726. eventData[P_MESH] = this;
  727. eventData[P_BOUNDSMIN] = Variant(tileBoundingBox.min_);
  728. eventData[P_BOUNDSMAX] = Variant(tileBoundingBox.max_);
  729. SendEvent(E_NAVIGATION_AREA_REBUILT, eventData);
  730. }
  731. return retCt;
  732. }
  733. PODVector<OffMeshConnection*> DynamicNavigationMesh::CollectOffMeshConnections(const BoundingBox& bounds)
  734. {
  735. PODVector<OffMeshConnection*> connections;
  736. node_->GetComponents<OffMeshConnection>(connections, true);
  737. for (unsigned i = 0; i < connections.Size(); ++i)
  738. {
  739. OffMeshConnection* connection = connections[i];
  740. if (!(connection->IsEnabledEffective() && connection->GetEndPoint()))
  741. {
  742. // discard this connection
  743. connections.Erase(i);
  744. --i;
  745. }
  746. }
  747. return connections;
  748. }
  749. void DynamicNavigationMesh::ReleaseNavigationMesh()
  750. {
  751. NavigationMesh::ReleaseNavigationMesh();
  752. ReleaseTileCache();
  753. }
  754. void DynamicNavigationMesh::ReleaseTileCache()
  755. {
  756. dtFreeTileCache(tileCache_);
  757. tileCache_ = 0;
  758. }
  759. void DynamicNavigationMesh::OnSceneSet(Scene* scene)
  760. {
  761. // Subscribe to the scene subsystem update, which will trigger the tile cache to update the nav mesh
  762. if (scene)
  763. SubscribeToEvent(scene, E_SCENESUBSYSTEMUPDATE, URHO3D_HANDLER(DynamicNavigationMesh, HandleSceneSubsystemUpdate));
  764. else
  765. UnsubscribeFromEvent(E_SCENESUBSYSTEMUPDATE);
  766. }
  767. void DynamicNavigationMesh::AddObstacle(Obstacle* obstacle, bool silent)
  768. {
  769. if (tileCache_)
  770. {
  771. float pos[3];
  772. Vector3 obsPos = obstacle->GetNode()->GetWorldPosition();
  773. rcVcopy(pos, &obsPos.x_);
  774. dtObstacleRef refHolder;
  775. // Because dtTileCache doesn't process obstacle requests while updating tiles
  776. // it's necessary update until sufficient request space is available
  777. while (tileCache_->isObstacleQueueFull())
  778. tileCache_->update(1, navMesh_);
  779. if (dtStatusFailed(tileCache_->addObstacle(pos, obstacle->GetRadius(), obstacle->GetHeight(), &refHolder)))
  780. {
  781. URHO3D_LOGERROR("Failed to add obstacle");
  782. return;
  783. }
  784. obstacle->obstacleId_ = refHolder;
  785. assert(refHolder > 0);
  786. if (!silent)
  787. {
  788. using namespace NavigationObstacleAdded;
  789. VariantMap& eventData = GetContext()->GetEventDataMap();
  790. eventData[P_NODE] = obstacle->GetNode();
  791. eventData[P_OBSTACLE] = obstacle;
  792. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  793. eventData[P_RADIUS] = obstacle->GetRadius();
  794. eventData[P_HEIGHT] = obstacle->GetHeight();
  795. SendEvent(E_NAVIGATION_OBSTACLE_ADDED, eventData);
  796. }
  797. }
  798. }
  799. void DynamicNavigationMesh::ObstacleChanged(Obstacle* obstacle)
  800. {
  801. if (tileCache_)
  802. {
  803. RemoveObstacle(obstacle, true);
  804. AddObstacle(obstacle, true);
  805. }
  806. }
  807. void DynamicNavigationMesh::RemoveObstacle(Obstacle* obstacle, bool silent)
  808. {
  809. if (tileCache_ && obstacle->obstacleId_ > 0)
  810. {
  811. // Because dtTileCache doesn't process obstacle requests while updating tiles
  812. // it's necessary update until sufficient request space is available
  813. while (tileCache_->isObstacleQueueFull())
  814. tileCache_->update(1, navMesh_);
  815. if (dtStatusFailed(tileCache_->removeObstacle(obstacle->obstacleId_)))
  816. {
  817. URHO3D_LOGERROR("Failed to remove obstacle");
  818. return;
  819. }
  820. obstacle->obstacleId_ = 0;
  821. // Require a node in order to send an event
  822. if (!silent && obstacle->GetNode())
  823. {
  824. using namespace NavigationObstacleRemoved;
  825. VariantMap& eventData = GetContext()->GetEventDataMap();
  826. eventData[P_NODE] = obstacle->GetNode();
  827. eventData[P_OBSTACLE] = obstacle;
  828. eventData[P_POSITION] = obstacle->GetNode()->GetWorldPosition();
  829. eventData[P_RADIUS] = obstacle->GetRadius();
  830. eventData[P_HEIGHT] = obstacle->GetHeight();
  831. SendEvent(E_NAVIGATION_OBSTACLE_REMOVED, eventData);
  832. }
  833. }
  834. }
  835. void DynamicNavigationMesh::HandleSceneSubsystemUpdate(StringHash eventType, VariantMap& eventData)
  836. {
  837. using namespace SceneSubsystemUpdate;
  838. if (tileCache_ && navMesh_ && IsEnabledEffective())
  839. tileCache_->update(eventData[P_TIMESTEP].GetFloat(), navMesh_);
  840. }
  841. }