Core/MMaps: serialize tile loading per map, Recast/Detour overflow and cycle guards (#35)
- MMapManager: per-map load lock around loadMap, loadMapInstance and the unloads. Instance copies of a map are updated by different map threads and can share one mesh, so concurrent addTile/removeTile corrupted the tile link list (later connectExtLinks walk hung until the freeze detector aborted). loadedTiles is atomic. - Detour getPathToNode: fails instead of looping forever on a parent-chain cycle. - Recast (mmaps generator): sweep buffers sized by the real span count per row (upstream issue #317), sweep/region id overflow checks, degenerate polygon and out-of-range vertex index guards in RecastMesh. Co-authored-by: Karrz1 <[email protected]>
This commit is contained in:
@@ -1142,9 +1142,17 @@ dtStatus dtNavMeshQuery::getPathToNode(dtNode* endNode, dtPolyRef* path, int* pa
|
||||
// Find the length of the entire path.
|
||||
dtNode* curNode = endNode;
|
||||
int length = 0;
|
||||
// TRINITYCORE FIX: guard against an endless loop on a parent-chain cycle (A.pidx=B while B.pidx=A), which an
|
||||
// inadmissible area cost or corrupt navmesh data can produce. The chain can never be longer than the node pool.
|
||||
int const maxChainLen = m_nodePool->getMaxNodes() + 1;
|
||||
do
|
||||
{
|
||||
length++;
|
||||
if (length > maxChainLen)
|
||||
{
|
||||
*pathCount = 0;
|
||||
return DT_FAILURE;
|
||||
}
|
||||
curNode = m_nodePool->getNodeAtIdx(curNode->pidx);
|
||||
} while (curNode);
|
||||
|
||||
|
||||
@@ -108,7 +108,24 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
}
|
||||
memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
|
||||
|
||||
const int nsweeps = chf.width;
|
||||
// TRINITYCORE FIX (same class as recastnavigation issue #317): the sweep
|
||||
// buffer was sized per grid COLUMN (chf.width) but sweep ids are
|
||||
// allocated per SPAN below (sid = sweepId++) — a row whose total span
|
||||
// count exceeds the width (tall stacked geometry; rcCompactCell::count
|
||||
// is 8 bits, so up to 255 spans per cell) writes sweeps[sid] past the
|
||||
// allocation. Size by the exact worst case: the maximum total span
|
||||
// count over any single row. Capped at 256 because sid is an unsigned
|
||||
// char with 0xff reserved as the "no sweep" sentinel — the sweepId
|
||||
// exhaustion guard below fails soft before that bound can be exceeded.
|
||||
int maxSpansPerRow = 0;
|
||||
for (int y = 0; y < chf.height; ++y)
|
||||
{
|
||||
int rowSpans = 0;
|
||||
for (int x = 0; x < chf.width; ++x)
|
||||
rowSpans += (int)chf.cells[x+y*chf.width].count;
|
||||
maxSpansPerRow = rcMax(maxSpansPerRow, rowSpans);
|
||||
}
|
||||
const int nsweeps = rcMin(maxSpansPerRow + 2, 256);
|
||||
rcScopedDelete<rcLayerSweepSpan> sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));
|
||||
if (!sweeps)
|
||||
{
|
||||
@@ -149,6 +166,15 @@ bool rcBuildHeightfieldLayers(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
|
||||
if (sid == 0xff)
|
||||
{
|
||||
// TRINITYCORE FIX: sweepId is an unsigned char with 0xff
|
||||
// reserved as the sentinel — 255 sweeps in one row would
|
||||
// hand out sid==0xff (corrupting the sentinel semantics)
|
||||
// and then wrap. Fail soft instead.
|
||||
if (sweepId == 0xff)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: too many sweeps in one row (>= 255).");
|
||||
return false;
|
||||
}
|
||||
sid = sweepId++;
|
||||
sweeps[sid].nei = 0xff;
|
||||
sweeps[sid].ns = 0;
|
||||
|
||||
@@ -62,6 +62,15 @@ static bool buildMeshAdjacency(unsigned short* polys, const int npolys,
|
||||
if (t[j] == RC_MESH_NULL_IDX) break;
|
||||
unsigned short v0 = t[j];
|
||||
unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
|
||||
// TRINITYCORE FIX: a polygon referencing a vertex index >= nverts would
|
||||
// write firstEdge[v0] past the end of the allocation (heap corruption).
|
||||
// Such indices can only come from corrupted/degenerate input; fail soft.
|
||||
if (v0 >= nverts || v1 >= nverts)
|
||||
{
|
||||
rcFree(firstEdge);
|
||||
rcFree(edges);
|
||||
return false;
|
||||
}
|
||||
if (v0 < v1)
|
||||
{
|
||||
rcEdge& edge = edges[edgeCount];
|
||||
@@ -87,6 +96,16 @@ static bool buildMeshAdjacency(unsigned short* polys, const int npolys,
|
||||
if (t[j] == RC_MESH_NULL_IDX) break;
|
||||
unsigned short v0 = t[j];
|
||||
unsigned short v1 = (j+1 >= vertsPerPoly || t[j+1] == RC_MESH_NULL_IDX) ? t[0] : t[j+1];
|
||||
// TRINITYCORE FIX: see matching bounds check in the first edge pass.
|
||||
// firstEdge[v1] below must not be indexed with a corrupt vertex index;
|
||||
// a wild value would follow a bogus edge chain and write out of bounds
|
||||
// through edges[e].
|
||||
if (v0 >= nverts || v1 >= nverts)
|
||||
{
|
||||
rcFree(firstEdge);
|
||||
rcFree(edges);
|
||||
return false;
|
||||
}
|
||||
if (v0 > v1)
|
||||
{
|
||||
for (unsigned short e = firstEdge[v1]; e != RC_MESH_NULL_IDX; e = nextEdge[e])
|
||||
@@ -340,7 +359,18 @@ static int triangulate(int n, const int* verts, int* indices, int* tris)
|
||||
{
|
||||
int ntris = 0;
|
||||
int* dst = tris;
|
||||
|
||||
|
||||
// TRINITYCORE FIX (no upstream equivalent as of recastnavigation main, 2026-06):
|
||||
// A degenerate input polygon (n < 3) used to fall through to the final
|
||||
// "append remaining triangle" block below, reading indices[1]/indices[2]
|
||||
// out of bounds of the caller's buffer and emitting a triangle with garbage
|
||||
// indices. removeVertex() can produce such input (nhole < 3) from degenerate
|
||||
// source polygons; the garbage vertex indices then propagate into
|
||||
// rcPolyMesh::polys and corrupt the heap in buildMeshAdjacency().
|
||||
// Fail soft instead: report 0 triangles.
|
||||
if (n < 3)
|
||||
return 0;
|
||||
|
||||
// The last bit of the index is used to indicate if the vertex can be removed.
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
@@ -822,6 +852,21 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
|
||||
break;
|
||||
}
|
||||
|
||||
// TRINITYCORE FIX (no upstream equivalent as of recastnavigation main, 2026-06):
|
||||
// Degenerate input polygons (e.g. the removed vertex occurring more than once
|
||||
// in a single polygon, produced by overlapping/duplicated collision geometry)
|
||||
// can pass canRemoveVertex() yet leave a hole boundary with fewer than 3
|
||||
// vertices here. Triangulating such a hole read past 'thole'/'hole' and fed
|
||||
// garbage vertex indices into mesh.polys, corrupting the heap later in
|
||||
// buildMeshAdjacency(). The mesh is still consistent at this point (the
|
||||
// degenerate polygons and the vertex have been removed), so leave the
|
||||
// degenerate hole unfilled and report success.
|
||||
if (nhole < 3)
|
||||
{
|
||||
ctx->log(RC_LOG_WARNING, "removeVertex: Degenerate hole boundary (nhole=%d) while removing vertex %d. Skipping hole triangulation.", nhole, (int)rem);
|
||||
return true;
|
||||
}
|
||||
|
||||
rcScopedDelete<int> tris((int*)rcAlloc(sizeof(int)*nhole*3, RC_ALLOC_TEMP));
|
||||
if (!tris)
|
||||
{
|
||||
@@ -890,6 +935,15 @@ static bool removeVertex(rcContext* ctx, rcPolyMesh& mesh, const unsigned short
|
||||
for (int j = 0; j < ntris; ++j)
|
||||
{
|
||||
int* t = &tris[j*3];
|
||||
// TRINITYCORE FIX: defend against out-of-range triangle indices. All
|
||||
// indices triangulate() emits must address the 'hole'/'hreg'/'harea'
|
||||
// arrays (size nhole); anything else would read wild memory and store
|
||||
// garbage vertex indices into mesh.polys (heap corruption downstream).
|
||||
if (t[0] < 0 || t[0] >= nhole || t[1] < 0 || t[1] >= nhole || t[2] < 0 || t[2] >= nhole)
|
||||
{
|
||||
ctx->log(RC_LOG_WARNING, "removeVertex: triangulate() returned out of range index (%d/%d/%d, nhole=%d). Skipping triangle.", t[0], t[1], t[2], nhole);
|
||||
continue;
|
||||
}
|
||||
if (t[0] != t[1] && t[0] != t[2] && t[1] != t[2])
|
||||
{
|
||||
polys[npolys*nvp+0] = (unsigned short)hole[t[0]];
|
||||
|
||||
@@ -1331,6 +1331,29 @@ struct rcSweepSpan
|
||||
unsigned short nei; // neighbour id
|
||||
};
|
||||
|
||||
// TRINITYCORE FIX (upstream issue #317, still unfixed in recastnavigation main
|
||||
// as of 2026-06): rcBuildRegionsMonotone and rcBuildLayerRegions sized their
|
||||
// 'sweeps' buffer as rcMax(width, height), i.e. one entry per grid column.
|
||||
// But a new sweep id is allocated per *span* that does not inherit a region
|
||||
// from its -x neighbour, and a single cell can stack up to 255 spans (layered
|
||||
// geometry such as multi-floor raid WMOs). On span-dense rows the sweep id
|
||||
// counter exceeds the buffer size and 'sweeps[previd] = ...' writes past the
|
||||
// rcAlloc'd allocation (heap corruption). Size the buffer by the worst-case
|
||||
// span count of any single row instead; each span can introduce at most one
|
||||
// new sweep id and 'rid' starts at 1, so maxRowSpans+2 entries always suffice.
|
||||
static int countMaxSpansPerRow(const rcCompactHeightfield& chf)
|
||||
{
|
||||
int maxRowSpans = 0;
|
||||
for (int y = 0; y < chf.height; ++y)
|
||||
{
|
||||
int rowSpans = 0;
|
||||
for (int x = 0; x < chf.width; ++x)
|
||||
rowSpans += (int)chf.cells[x + y*chf.width].count;
|
||||
maxRowSpans = rcMax(maxRowSpans, rowSpans);
|
||||
}
|
||||
return maxRowSpans;
|
||||
}
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// Non-null regions will consist of connected, non-overlapping walkable spans that form a single contour.
|
||||
@@ -1369,7 +1392,9 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
}
|
||||
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
|
||||
|
||||
const int nsweeps = rcMax(chf.width,chf.height);
|
||||
// TRINITYCORE FIX: was rcMax(chf.width,chf.height) — too small for rows with
|
||||
// stacked spans, leading to out-of-bounds writes. See countMaxSpansPerRow.
|
||||
const int nsweeps = countMaxSpansPerRow(chf) + 2;
|
||||
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
|
||||
if (!sweeps)
|
||||
{
|
||||
@@ -1425,6 +1450,15 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
|
||||
if (!previd)
|
||||
{
|
||||
// TRINITYCORE FIX: 'rid' is 16-bit; if a single row produces
|
||||
// more than 0xFFFE sweep spans it would wrap and alias earlier
|
||||
// sweeps (sweeps[] itself is sized for the worst case above).
|
||||
// Fail soft instead of producing a corrupt region partition.
|
||||
if (rid == 0xFFFF)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildRegions(Monotone/Layer): sweep id overflow on row %d.", y);
|
||||
return false;
|
||||
}
|
||||
previd = rid++;
|
||||
sweeps[previd].rid = previd;
|
||||
sweeps[previd].ns = 0;
|
||||
@@ -1467,6 +1501,16 @@ bool rcBuildRegionsMonotone(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
}
|
||||
else
|
||||
{
|
||||
// TRINITYCORE FIX: region ids share their 16-bit value space with
|
||||
// the RC_BORDER_REG flag (0x8000). An id reaching that bit would be
|
||||
// misinterpreted as a border region, and a full 16-bit wrap would
|
||||
// shrink the 'prev' table below the ids still referenced by
|
||||
// 'prev[nr]++' (heap corruption). Fail soft before either happens.
|
||||
if (id >= RC_BORDER_REG)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildRegions(Monotone/Layer): region id overflow (%d regions).", (int)id);
|
||||
return false;
|
||||
}
|
||||
sweeps[i].id = id++;
|
||||
}
|
||||
}
|
||||
@@ -1678,7 +1722,9 @@ bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
}
|
||||
memset(srcReg,0,sizeof(unsigned short)*chf.spanCount);
|
||||
|
||||
const int nsweeps = rcMax(chf.width,chf.height);
|
||||
// TRINITYCORE FIX: was rcMax(chf.width,chf.height) — too small for rows with
|
||||
// stacked spans, leading to out-of-bounds writes. See countMaxSpansPerRow.
|
||||
const int nsweeps = countMaxSpansPerRow(chf) + 2;
|
||||
rcScopedDelete<rcSweepSpan> sweeps((rcSweepSpan*)rcAlloc(sizeof(rcSweepSpan)*nsweeps, RC_ALLOC_TEMP));
|
||||
if (!sweeps)
|
||||
{
|
||||
@@ -1734,6 +1780,15 @@ bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
|
||||
if (!previd)
|
||||
{
|
||||
// TRINITYCORE FIX: 'rid' is 16-bit; if a single row produces
|
||||
// more than 0xFFFE sweep spans it would wrap and alias earlier
|
||||
// sweeps (sweeps[] itself is sized for the worst case above).
|
||||
// Fail soft instead of producing a corrupt region partition.
|
||||
if (rid == 0xFFFF)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildRegions(Monotone/Layer): sweep id overflow on row %d.", y);
|
||||
return false;
|
||||
}
|
||||
previd = rid++;
|
||||
sweeps[previd].rid = previd;
|
||||
sweeps[previd].ns = 0;
|
||||
@@ -1776,6 +1831,16 @@ bool rcBuildLayerRegions(rcContext* ctx, rcCompactHeightfield& chf,
|
||||
}
|
||||
else
|
||||
{
|
||||
// TRINITYCORE FIX: region ids share their 16-bit value space with
|
||||
// the RC_BORDER_REG flag (0x8000). An id reaching that bit would be
|
||||
// misinterpreted as a border region, and a full 16-bit wrap would
|
||||
// shrink the 'prev' table below the ids still referenced by
|
||||
// 'prev[nr]++' (heap corruption). Fail soft before either happens.
|
||||
if (id >= RC_BORDER_REG)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildRegions(Monotone/Layer): region id overflow (%d regions).", (int)id);
|
||||
return false;
|
||||
}
|
||||
sweeps[i].id = id++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "MapUtils.h"
|
||||
#include "Memory.h"
|
||||
#include <algorithm>
|
||||
#include <mutex>
|
||||
|
||||
namespace MMAP
|
||||
{
|
||||
@@ -43,6 +44,11 @@ namespace MMAP
|
||||
// dummy struct to hold map's mmap data
|
||||
struct MMapData
|
||||
{
|
||||
// Serializes tile loading and unloading of one map. Instance copies of a map are updated by different map threads and can share
|
||||
// one mesh (GetInstanceIdForMeshLookup), so two threads could run meshData.try_emplace and dtNavMesh::addTile/removeTile on it at
|
||||
// once, which corrupts the tile link list (a later connectExtLinks walk then hangs until the freeze detector aborts).
|
||||
std::mutex loadLock;
|
||||
|
||||
MeshDataMap meshData;
|
||||
|
||||
// we have to use single dtNavMeshQuery for every instance, since those are not thread safe
|
||||
@@ -205,6 +211,13 @@ namespace MMAP
|
||||
|
||||
LoadResult MMapManager::loadMap(std::string_view basePath, uint32 mapId, uint32 instanceId, int32 x, int32 y)
|
||||
{
|
||||
// loadedMMaps is filled once at startup (InitializeThreadUnsafe), so this lookup is read only
|
||||
MMapData* mmap = Trinity::Containers::MapGetValuePtr(loadedMMaps, mapId);
|
||||
if (!mmap)
|
||||
return LoadResult::FileNotFound;
|
||||
|
||||
std::lock_guard<std::mutex> lock(mmap->loadLock);
|
||||
|
||||
// make sure the mmap is loaded and ready to load tiles
|
||||
switch (LoadResult mapResult = loadMapData(basePath, mapId, instanceId))
|
||||
{
|
||||
@@ -216,7 +229,6 @@ namespace MMAP
|
||||
}
|
||||
|
||||
// get this mmap data
|
||||
MMapData* mmap = Trinity::Containers::MapGetValuePtr(loadedMMaps, mapId);
|
||||
MMapMapData& meshData = mmap->GetMeshData(mapId, instanceId).first->second;
|
||||
|
||||
// check if we already have this tile loaded
|
||||
@@ -304,6 +316,12 @@ namespace MMAP
|
||||
|
||||
bool MMapManager::loadMapInstance(std::string_view basePath, uint32 meshMapId, uint32 instanceMapId, uint32 instanceId)
|
||||
{
|
||||
MMapData* mmap = Trinity::Containers::MapGetValuePtr(loadedMMaps, meshMapId);
|
||||
if (!mmap)
|
||||
return false;
|
||||
|
||||
std::lock_guard<std::mutex> lock(mmap->loadLock);
|
||||
|
||||
switch (loadMapData(basePath, meshMapId, instanceId))
|
||||
{
|
||||
case LoadResult::Success:
|
||||
@@ -313,7 +331,6 @@ namespace MMAP
|
||||
return false;
|
||||
}
|
||||
|
||||
MMapData* mmap = Trinity::Containers::MapGetValuePtr(loadedMMaps, meshMapId);
|
||||
auto [queryItr, inserted] = mmap->navMeshQueries.try_emplace({ instanceMapId, instanceId });
|
||||
if (!inserted)
|
||||
return true;
|
||||
@@ -347,6 +364,7 @@ namespace MMAP
|
||||
}
|
||||
|
||||
MMapData* mmap = itr->second.get();
|
||||
std::lock_guard<std::mutex> lock(mmap->loadLock);
|
||||
uint32 packedGridPos = packTileID(x, y);
|
||||
for (auto& [instanceId, meshData] : mmap->meshData)
|
||||
{
|
||||
@@ -382,6 +400,8 @@ namespace MMAP
|
||||
return;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(itr->second->loadLock);
|
||||
|
||||
if (!isRebuildingTilesEnabledOnMap(mapId))
|
||||
{
|
||||
if (MeshDataMap::node_type meshNode = itr->second->RemoveMeshData(mapId, 0))
|
||||
@@ -418,6 +438,7 @@ namespace MMAP
|
||||
}
|
||||
|
||||
MMapData* mmap = itr->second.get();
|
||||
std::lock_guard<std::mutex> lock(mmap->loadLock);
|
||||
std::size_t erased = mmap->navMeshQueries.erase({ instanceMapId, instanceId });
|
||||
if (!erased)
|
||||
TC_LOG_DEBUG("maps", "MMAP:unloadMapInstance: Asked to unload not loaded dtNavMeshQuery mapId {:04} instanceId {}", instanceMapId, instanceId);
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
#include "Define.h"
|
||||
#include "MMapDefines.h"
|
||||
#include <DetourNavMeshQuery.h>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
@@ -80,7 +81,7 @@ namespace MMAP
|
||||
|
||||
MMapDataSet::const_iterator GetMMapData(uint32 mapId) const;
|
||||
MMapDataSet loadedMMaps;
|
||||
uint32 loadedTiles = 0;
|
||||
std::atomic<uint32> loadedTiles = 0; // changed by several map threads (each map has its own load lock)
|
||||
|
||||
std::unordered_map<uint32, uint32> parentMapData;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user