recast update

Added chunkytrimesh - this class splits up the geometry the navmesh is interested in into kdtree for fast traversal, makes the actual navmesh generation work with smaller chunks.

Now only 1 RecastPolylist per navmesh this can be saved out in a future commit.

This is a history commit, all functionality works same as it did before but it matches recasts recommended setup more closely. Future additions may break backwards compatibility.
This commit is contained in:
marauder2k7 2025-07-22 14:39:36 +01:00
parent 26ebdd093b
commit d4d552e8e0
8 changed files with 800 additions and 215 deletions

View file

@ -704,6 +704,9 @@ inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
{ {
mDeviceStatistics.mDrawCalls++; mDeviceStatistics.mDrawCalls++;
mDeviceStatistics.mPolyCount += primitiveCount; mDeviceStatistics.mPolyCount += primitiveCount;
mVolatileVBs.clear();
mVolatilePBs.clear();
} }
void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ) void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )

View file

@ -0,0 +1,315 @@
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#include "ChunkyTriMesh.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct BoundsItem
{
float bmin[2];
float bmax[2];
int i;
};
static int compareItemX(const void* va, const void* vb)
{
const BoundsItem* a = (const BoundsItem*)va;
const BoundsItem* b = (const BoundsItem*)vb;
if (a->bmin[0] < b->bmin[0])
return -1;
if (a->bmin[0] > b->bmin[0])
return 1;
return 0;
}
static int compareItemY(const void* va, const void* vb)
{
const BoundsItem* a = (const BoundsItem*)va;
const BoundsItem* b = (const BoundsItem*)vb;
if (a->bmin[1] < b->bmin[1])
return -1;
if (a->bmin[1] > b->bmin[1])
return 1;
return 0;
}
static void calcExtends(const BoundsItem* items, const int /*nitems*/,
const int imin, const int imax,
float* bmin, float* bmax)
{
bmin[0] = items[imin].bmin[0];
bmin[1] = items[imin].bmin[1];
bmax[0] = items[imin].bmax[0];
bmax[1] = items[imin].bmax[1];
for (int i = imin+1; i < imax; ++i)
{
const BoundsItem& it = items[i];
if (it.bmin[0] < bmin[0]) bmin[0] = it.bmin[0];
if (it.bmin[1] < bmin[1]) bmin[1] = it.bmin[1];
if (it.bmax[0] > bmax[0]) bmax[0] = it.bmax[0];
if (it.bmax[1] > bmax[1]) bmax[1] = it.bmax[1];
}
}
inline int longestAxis(float x, float y)
{
return y > x ? 1 : 0;
}
static void subdivide(BoundsItem* items, int nitems, int imin, int imax, int trisPerChunk,
int& curNode, rcChunkyTriMeshNode* nodes, const int maxNodes,
int& curTri, int* outTris, const int* inTris)
{
int inum = imax - imin;
int icur = curNode;
if (curNode >= maxNodes)
return;
rcChunkyTriMeshNode& node = nodes[curNode++];
if (inum <= trisPerChunk)
{
// Leaf
calcExtends(items, nitems, imin, imax, node.bmin, node.bmax);
// Copy triangles.
node.i = curTri;
node.n = inum;
for (int i = imin; i < imax; ++i)
{
const int* src = &inTris[items[i].i*3];
int* dst = &outTris[curTri*3];
curTri++;
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
}
}
else
{
// Split
calcExtends(items, nitems, imin, imax, node.bmin, node.bmax);
int axis = longestAxis(node.bmax[0] - node.bmin[0],
node.bmax[1] - node.bmin[1]);
if (axis == 0)
{
// Sort along x-axis
qsort(items+imin, static_cast<size_t>(inum), sizeof(BoundsItem), compareItemX);
}
else if (axis == 1)
{
// Sort along y-axis
qsort(items+imin, static_cast<size_t>(inum), sizeof(BoundsItem), compareItemY);
}
int isplit = imin+inum/2;
// Left
subdivide(items, nitems, imin, isplit, trisPerChunk, curNode, nodes, maxNodes, curTri, outTris, inTris);
// Right
subdivide(items, nitems, isplit, imax, trisPerChunk, curNode, nodes, maxNodes, curTri, outTris, inTris);
int iescape = curNode - icur;
// Negative index means escape.
node.i = -iescape;
}
}
bool rcCreateChunkyTriMesh(const float* verts, const int* tris, int ntris,
int trisPerChunk, rcChunkyTriMesh* cm)
{
int nchunks = (ntris + trisPerChunk-1) / trisPerChunk;
cm->nodes = new rcChunkyTriMeshNode[nchunks*4];
if (!cm->nodes)
return false;
cm->tris = new int[ntris*3];
if (!cm->tris)
return false;
cm->ntris = ntris;
// Build tree
BoundsItem* items = new BoundsItem[ntris];
if (!items)
return false;
for (int i = 0; i < ntris; i++)
{
const int* t = &tris[i*3];
BoundsItem& it = items[i];
it.i = i;
// Calc triangle XZ bounds.
it.bmin[0] = it.bmax[0] = verts[t[0]*3+0];
it.bmin[1] = it.bmax[1] = verts[t[0]*3+2];
for (int j = 1; j < 3; ++j)
{
const float* v = &verts[t[j]*3];
if (v[0] < it.bmin[0]) it.bmin[0] = v[0];
if (v[2] < it.bmin[1]) it.bmin[1] = v[2];
if (v[0] > it.bmax[0]) it.bmax[0] = v[0];
if (v[2] > it.bmax[1]) it.bmax[1] = v[2];
}
}
int curTri = 0;
int curNode = 0;
subdivide(items, ntris, 0, ntris, trisPerChunk, curNode, cm->nodes, nchunks*4, curTri, cm->tris, tris);
delete [] items;
cm->nnodes = curNode;
// Calc max tris per node.
cm->maxTrisPerChunk = 0;
for (int i = 0; i < cm->nnodes; ++i)
{
rcChunkyTriMeshNode& node = cm->nodes[i];
const bool isLeaf = node.i >= 0;
if (!isLeaf) continue;
if (node.n > cm->maxTrisPerChunk)
cm->maxTrisPerChunk = node.n;
}
return true;
}
inline bool checkOverlapRect(const float amin[2], const float amax[2],
const float bmin[2], const float bmax[2])
{
bool overlap = true;
overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap;
overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap;
return overlap;
}
int rcGetChunksOverlappingRect(const rcChunkyTriMesh* cm,
float bmin[2], float bmax[2],
int* ids, const int maxIds)
{
// Traverse tree
int i = 0;
int n = 0;
while (i < cm->nnodes)
{
const rcChunkyTriMeshNode* node = &cm->nodes[i];
const bool overlap = checkOverlapRect(bmin, bmax, node->bmin, node->bmax);
const bool isLeafNode = node->i >= 0;
if (isLeafNode && overlap)
{
if (n < maxIds)
{
ids[n] = i;
n++;
}
}
if (overlap || isLeafNode)
i++;
else
{
const int escapeIndex = -node->i;
i += escapeIndex;
}
}
return n;
}
static bool checkOverlapSegment(const float p[2], const float q[2],
const float bmin[2], const float bmax[2])
{
static const float EPSILON = 1e-6f;
float tmin = 0;
float tmax = 1;
float d[2];
d[0] = q[0] - p[0];
d[1] = q[1] - p[1];
for (int i = 0; i < 2; i++)
{
if (fabsf(d[i]) < EPSILON)
{
// Ray is parallel to slab. No hit if origin not within slab
if (p[i] < bmin[i] || p[i] > bmax[i])
return false;
}
else
{
// Compute intersection t value of ray with near and far plane of slab
float ood = 1.0f / d[i];
float t1 = (bmin[i] - p[i]) * ood;
float t2 = (bmax[i] - p[i]) * ood;
if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; }
if (t1 > tmin) tmin = t1;
if (t2 < tmax) tmax = t2;
if (tmin > tmax) return false;
}
}
return true;
}
int rcGetChunksOverlappingSegment(const rcChunkyTriMesh* cm,
float p[2], float q[2],
int* ids, const int maxIds)
{
// Traverse tree
int i = 0;
int n = 0;
while (i < cm->nnodes)
{
const rcChunkyTriMeshNode* node = &cm->nodes[i];
const bool overlap = checkOverlapSegment(p, q, node->bmin, node->bmax);
const bool isLeafNode = node->i >= 0;
if (isLeafNode && overlap)
{
if (n < maxIds)
{
ids[n] = i;
n++;
}
}
if (overlap || isLeafNode)
i++;
else
{
const int escapeIndex = -node->i;
i += escapeIndex;
}
}
return n;
}

View file

@ -0,0 +1,59 @@
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
#ifndef CHUNKYTRIMESH_H
#define CHUNKYTRIMESH_H
struct rcChunkyTriMeshNode
{
float bmin[2];
float bmax[2];
int i;
int n;
};
struct rcChunkyTriMesh
{
inline rcChunkyTriMesh() : nodes(0), nnodes(0), tris(0), ntris(0), maxTrisPerChunk(0) {}
inline ~rcChunkyTriMesh() { delete [] nodes; delete [] tris; }
rcChunkyTriMeshNode* nodes;
int nnodes;
int* tris;
int ntris;
int maxTrisPerChunk;
private:
// Explicitly disabled copy constructor and copy assignment operator.
rcChunkyTriMesh(const rcChunkyTriMesh&);
rcChunkyTriMesh& operator=(const rcChunkyTriMesh&);
};
/// Creates partitioned triangle mesh (AABB tree),
/// where each node contains at max trisPerChunk triangles.
bool rcCreateChunkyTriMesh(const float* verts, const int* tris, int ntris,
int trisPerChunk, rcChunkyTriMesh* cm);
/// Returns the chunk indices which overlap the input rectable.
int rcGetChunksOverlappingRect(const rcChunkyTriMesh* cm, float bmin[2], float bmax[2], int* ids, const int maxIds);
/// Returns the chunk indices which overlap the input segment.
int rcGetChunksOverlappingSegment(const rcChunkyTriMesh* cm, float p[2], float q[2], int* ids, const int maxIds);
#endif // CHUNKYTRIMESH_H

View file

@ -51,7 +51,7 @@ duDebugDrawTorque::~duDebugDrawTorque()
void duDebugDrawTorque::depthMask(bool state) void duDebugDrawTorque::depthMask(bool state)
{ {
mDesc.setZReadWrite(state, state); mDesc.setZReadWrite(state, false);
} }
void duDebugDrawTorque::texture(bool state) void duDebugDrawTorque::texture(bool state)
@ -94,7 +94,7 @@ void duDebugDrawTorque::begin(duDebugDrawPrimitives prim, float size)
case DU_DRAW_QUADS: mPrimType = GFXTriangleList; mQuadsMode = true; break; case DU_DRAW_QUADS: mPrimType = GFXTriangleList; mQuadsMode = true; break;
} }
mDesc.setCullMode(GFXCullNone); mDesc.setCullMode(GFXCullCW);
mDesc.setBlend(true); mDesc.setBlend(true);
} }

View file

@ -173,6 +173,12 @@ DefineEngineFunction(NavMeshUpdateOne, void, (S32 meshid, S32 objid, bool remove
} }
NavMesh::NavMesh() NavMesh::NavMesh()
: m_triareas(0),
m_solid(0),
m_chf(0),
m_cset(0),
m_pmesh(0),
m_dmesh(0)
{ {
mTypeMask |= StaticShapeObjectType | MarkerObjectType; mTypeMask |= StaticShapeObjectType | MarkerObjectType;
mFileName = StringTable->EmptyString(); mFileName = StringTable->EmptyString();
@ -184,8 +190,7 @@ NavMesh::NavMesh()
mWaterMethod = Ignore; mWaterMethod = Ignore;
dMemset(&cfg, 0, sizeof(cfg)); mCellSize = mCellHeight = 0.01f;
mCellSize = mCellHeight = 0.2f;
mWalkableHeight = 2.0f; mWalkableHeight = 2.0f;
mWalkableClimb = 0.3f; mWalkableClimb = 0.3f;
mWalkableRadius = 0.5f; mWalkableRadius = 0.5f;
@ -599,6 +604,13 @@ DefineEngineMethod(NavMesh, deleteLinks, void, (),,
//object->eraseLinks(); //object->eraseLinks();
} }
static void buildCallback(SceneObject* object, void* key)
{
SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
if (!object->mPathfindingIgnore)
object->buildPolyList(info->context, info->polyList, info->boundingBox, info->boundingSphere);
}
bool NavMesh::build(bool background, bool saveIntermediates) bool NavMesh::build(bool background, bool saveIntermediates)
{ {
if(mBuilding) if(mBuilding)
@ -622,14 +634,53 @@ bool NavMesh::build(bool background, bool saveIntermediates)
return false; return false;
} }
updateConfig(); Box3F worldBox = getWorldBox();
SceneContainer::CallbackInfo info;
info.context = PLC_Navigation;
info.boundingBox = worldBox;
m_geo = new RecastPolyList;
info.polyList = m_geo;
info.key = this;
getContainer()->findObjects(worldBox, StaticObjectType | DynamicShapeObjectType, buildCallback, &info);
// Parse water objects into the same list, but remember how much geometry was /not/ water.
U32 nonWaterVertCount = m_geo->getVertCount();
U32 nonWaterTriCount = m_geo->getTriCount();
if (mWaterMethod != Ignore)
{
getContainer()->findObjects(worldBox, WaterObjectType, buildCallback, &info);
}
// Check for no geometry.
if (!m_geo->getVertCount())
{
m_geo->clear();
return false;
}
m_geo->getChunkyMesh();
// Needed for the recast config and generation params.
Box3F rc_box = DTStoRC(getWorldBox());
S32 gw = 0, gh = 0;
rcCalcGridSize(rc_box.minExtents, rc_box.maxExtents, mCellSize, &gw, &gh);
const S32 ts = (S32)mTileSize;
const S32 tw = (gw + ts - 1) / ts;
const S32 th = (gh + ts - 1) / ts;
Con::printf("NavMesh::Build - Tiles %d x %d", tw, th);
U32 tileBits = mMin(getNextBinLog2(tw * th), 14);
if (tileBits > 14) tileBits = 14;
U32 maxTiles = 1 << tileBits;
U32 polyBits = 22 - tileBits;
mMaxPolysPerTile = 1 << polyBits;
// Build navmesh parameters from console members. // Build navmesh parameters from console members.
dtNavMeshParams params; dtNavMeshParams params;
rcVcopy(params.orig, cfg.bmin); rcVcopy(params.orig, rc_box.minExtents);
params.tileWidth = cfg.tileSize * mCellSize; params.tileWidth = mTileSize * mCellSize;
params.tileHeight = cfg.tileSize * mCellSize; params.tileHeight = mTileSize * mCellSize;
params.maxTiles = mCeil(getWorldBox().len_x() / params.tileWidth) * mCeil(getWorldBox().len_y() / params.tileHeight); params.maxTiles = maxTiles;
params.maxPolys = mMaxPolysPerTile; params.maxPolys = mMaxPolysPerTile;
// Initialise our navmesh. // Initialise our navmesh.
@ -690,29 +741,29 @@ void NavMesh::inspectPostApply()
void NavMesh::updateConfig() void NavMesh::updateConfig()
{ {
// Build rcConfig object from our console members. //// Build rcConfig object from our console members.
dMemset(&cfg, 0, sizeof(cfg)); //dMemset(&cfg, 0, sizeof(cfg));
cfg.cs = mCellSize; //cfg.cs = mCellSize;
cfg.ch = mCellHeight; //cfg.ch = mCellHeight;
Box3F box = DTStoRC(getWorldBox()); //Box3F box = DTStoRC(getWorldBox());
rcVcopy(cfg.bmin, box.minExtents); //rcVcopy(cfg.bmin, box.minExtents);
rcVcopy(cfg.bmax, box.maxExtents); //rcVcopy(cfg.bmax, box.maxExtents);
rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height); //rcCalcGridSize(cfg.bmin, cfg.bmax, cfg.cs, &cfg.width, &cfg.height);
cfg.walkableHeight = mCeil(mWalkableHeight / mCellHeight); //cfg.walkableHeight = mCeil(mWalkableHeight / mCellHeight);
cfg.walkableClimb = mCeil(mWalkableClimb / mCellHeight); //cfg.walkableClimb = mCeil(mWalkableClimb / mCellHeight);
cfg.walkableRadius = mCeil(mWalkableRadius / mCellSize); //cfg.walkableRadius = mCeil(mWalkableRadius / mCellSize);
cfg.walkableSlopeAngle = mWalkableSlope; //cfg.walkableSlopeAngle = mWalkableSlope;
cfg.borderSize = cfg.walkableRadius + 3; //cfg.borderSize = cfg.walkableRadius + 3;
cfg.detailSampleDist = mDetailSampleDist; //cfg.detailSampleDist = mDetailSampleDist;
cfg.detailSampleMaxError = mDetailSampleMaxError; //cfg.detailSampleMaxError = mDetailSampleMaxError;
cfg.maxEdgeLen = mMaxEdgeLen; //cfg.maxEdgeLen = mMaxEdgeLen;
cfg.maxSimplificationError = mMaxSimplificationError; //cfg.maxSimplificationError = mMaxSimplificationError;
cfg.maxVertsPerPoly = mMaxVertsPerPoly; //cfg.maxVertsPerPoly = mMaxVertsPerPoly;
cfg.minRegionArea = mMinRegionArea; //cfg.minRegionArea = mMinRegionArea;
cfg.mergeRegionArea = mMergeRegionArea; //cfg.mergeRegionArea = mMergeRegionArea;
cfg.tileSize = mTileSize / cfg.cs; //cfg.tileSize = mTileSize / cfg.cs;
} }
S32 NavMesh::getTile(const Point3F& pos) S32 NavMesh::getTile(const Point3F& pos)
@ -740,6 +791,36 @@ void NavMesh::updateTiles(bool dirty)
if(!isProperlyAdded()) if(!isProperlyAdded())
return; return;
// this is just here so that load regens the mesh, we should be saving it out.
if (!m_geo)
{
Box3F worldBox = getWorldBox();
SceneContainer::CallbackInfo info;
info.context = PLC_Navigation;
info.boundingBox = worldBox;
m_geo = new RecastPolyList;
info.polyList = m_geo;
info.key = this;
getContainer()->findObjects(worldBox, StaticObjectType | DynamicShapeObjectType, buildCallback, &info);
// Parse water objects into the same list, but remember how much geometry was /not/ water.
U32 nonWaterVertCount = m_geo->getVertCount();
U32 nonWaterTriCount = m_geo->getTriCount();
if (mWaterMethod != Ignore)
{
getContainer()->findObjects(worldBox, WaterObjectType, buildCallback, &info);
}
// Check for no geometry.
if (!m_geo->getVertCount())
{
m_geo->clear();
return;
}
m_geo->getChunkyMesh();
}
mTiles.clear(); mTiles.clear();
mTileData.clear(); mTileData.clear();
mDirtyTiles.clear(); mDirtyTiles.clear();
@ -748,13 +829,15 @@ void NavMesh::updateTiles(bool dirty)
if(box.isEmpty()) if(box.isEmpty())
return; return;
updateConfig();
// Calculate tile dimensions. // Calculate tile dimensions.
const U32 ts = cfg.tileSize; const F32* bmin = box.minExtents;
const U32 tw = (cfg.width + ts-1) / ts; const F32* bmax = box.maxExtents;
const U32 th = (cfg.height + ts-1) / ts; S32 gw = 0, gh = 0;
const F32 tcs = cfg.tileSize * cfg.cs; rcCalcGridSize(bmin, bmax, mCellSize, &gw, &gh);
const S32 ts = (S32)mTileSize;
const S32 tw = (gw + ts - 1) / ts;
const S32 th = (gh + ts - 1) / ts;
const F32 tcs = mTileSize * mCellSize;
// Iterate over tiles. // Iterate over tiles.
F32 tileBmin[3], tileBmax[3]; F32 tileBmin[3], tileBmax[3];
@ -762,13 +845,13 @@ void NavMesh::updateTiles(bool dirty)
{ {
for(U32 x = 0; x < tw; ++x) for(U32 x = 0; x < tw; ++x)
{ {
tileBmin[0] = cfg.bmin[0] + x*tcs; tileBmin[0] = bmin[0] + x*tcs;
tileBmin[1] = cfg.bmin[1]; tileBmin[1] = bmin[1];
tileBmin[2] = cfg.bmin[2] + y*tcs; tileBmin[2] = bmin[2] + y*tcs;
tileBmax[0] = cfg.bmin[0] + (x+1)*tcs; tileBmax[0] = bmin[0] + (x+1)*tcs;
tileBmax[1] = cfg.bmax[1]; tileBmax[1] = bmax[1];
tileBmax[2] = cfg.bmin[2] + (y+1)*tcs; tileBmax[2] = bmin[2] + (y+1)*tcs;
mTiles.push_back( mTiles.push_back(
Tile(RCtoDTS(tileBmin, tileBmax), Tile(RCtoDTS(tileBmin, tileBmax),
@ -846,112 +929,127 @@ void NavMesh::buildNextTile()
} }
} }
static void buildCallback(SceneObject* object,void *key)
{
SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
if (!object->mPathfindingIgnore)
object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
}
unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dataSize) unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dataSize)
{ {
cleanup();
const rcChunkyTriMesh* chunkyMesh = m_geo->getChunkyMesh();
// Push out tile boundaries a bit. // Push out tile boundaries a bit.
F32 tileBmin[3], tileBmax[3]; F32 tileBmin[3], tileBmax[3];
rcVcopy(tileBmin, tile.bmin); rcVcopy(tileBmin, tile.bmin);
rcVcopy(tileBmax, tile.bmax); rcVcopy(tileBmax, tile.bmax);
tileBmin[0] -= cfg.borderSize * cfg.cs; // Setup our rcConfig
tileBmin[2] -= cfg.borderSize * cfg.cs; dMemset(&m_cfg, 0, sizeof(m_cfg));
tileBmax[0] += cfg.borderSize * cfg.cs; m_cfg.cs = mCellSize;
tileBmax[2] += cfg.borderSize * cfg.cs; m_cfg.ch = mCellHeight;
m_cfg.walkableSlopeAngle = mWalkableSlope;
// Parse objects from level into RC-compatible format. m_cfg.walkableHeight = (S32)mCeil(mWalkableHeight / m_cfg.ch);
Box3F box = RCtoDTS(tileBmin, tileBmax); m_cfg.walkableClimb = (S32)mFloor(mWalkableClimb / m_cfg.ch);
SceneContainer::CallbackInfo info; m_cfg.walkableRadius = (S32)mCeil(mWalkableRadius / m_cfg.cs);
info.context = PLC_Navigation; m_cfg.maxEdgeLen = (S32)(mMaxEdgeLen / mCellSize);
info.boundingBox = box; m_cfg.maxSimplificationError = mMaxSimplificationError;
data.geom.clear(); m_cfg.minRegionArea = (S32)mSquared((F32)mMinRegionArea);
info.polyList = &data.geom; m_cfg.mergeRegionArea = (S32)mSquared((F32)mMergeRegionArea);
info.key = this; m_cfg.maxVertsPerPoly = (S32)mMaxVertsPerPoly;
getContainer()->findObjects(box, StaticObjectType | DynamicShapeObjectType, buildCallback, &info); m_cfg.tileSize = (S32)mTileSize;
m_cfg.borderSize = mMax(m_cfg.walkableRadius + 3, mBorderSize); // use the border size if it is bigger.
// Parse water objects into the same list, but remember how much geometry was /not/ water. m_cfg.width = m_cfg.tileSize + m_cfg.borderSize * 2;
U32 nonWaterVertCount = data.geom.getVertCount(); m_cfg.height = m_cfg.tileSize + m_cfg.borderSize * 2;
U32 nonWaterTriCount = data.geom.getTriCount(); m_cfg.detailSampleDist = mDetailSampleDist < 0.9f ? 0 : mCellSize * mDetailSampleDist;
if(mWaterMethod != Ignore) m_cfg.detailSampleMaxError = mCellHeight * mDetailSampleMaxError;
{ rcVcopy(m_cfg.bmin, tileBmin);
getContainer()->findObjects(box, WaterObjectType, buildCallback, &info); rcVcopy(m_cfg.bmax, tileBmax);
} m_cfg.bmin[0] -= m_cfg.borderSize * m_cfg.cs;
m_cfg.bmin[2] -= m_cfg.borderSize * m_cfg.cs;
// Check for no geometry. m_cfg.bmax[0] += m_cfg.borderSize * m_cfg.cs;
if (!data.geom.getVertCount()) m_cfg.bmax[2] += m_cfg.borderSize * m_cfg.cs;
{
data.geom.clear();
return NULL;
}
// Figure out voxel dimensions of this tile.
U32 width = 0, height = 0;
width = cfg.tileSize + cfg.borderSize * 2;
height = cfg.tileSize + cfg.borderSize * 2;
// Create a heightfield to voxelise our input geometry. // Create a heightfield to voxelise our input geometry.
data.hf = rcAllocHeightfield(); m_solid = rcAllocHeightfield();
if(!data.hf) if(!m_solid)
{ {
Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString()); Con::errorf("Out of memory (rcHeightField) for NavMesh %s", getIdString());
return NULL; return NULL;
} }
if(!rcCreateHeightfield(ctx, *data.hf, width, height, tileBmin, tileBmax, cfg.cs, cfg.ch)) if (!rcCreateHeightfield(ctx, *m_solid, m_cfg.width, m_cfg.height, m_cfg.bmin, m_cfg.bmax, m_cfg.cs, m_cfg.ch))
{ {
Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString()); Con::errorf("Could not generate rcHeightField for NavMesh %s", getIdString());
return NULL; return NULL;
} }
unsigned char *areas = new unsigned char[data.geom.getTriCount()]; m_triareas = new unsigned char[chunkyMesh->maxTrisPerChunk];
if (!m_triareas)
dMemset(areas, 0, data.geom.getTriCount() * sizeof(unsigned char));
// Mark walkable triangles with the appropriate area flags, and rasterize.
if(mWaterMethod == Solid)
{ {
// Treat water as solid: i.e. mark areas as walkable based on angle. Con::errorf("NavMesh::buildTileData: Out of memory 'm_triareas' (%d).", chunkyMesh->maxTrisPerChunk);
rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
data.geom.getVerts(), data.geom.getVertCount(),
data.geom.getTris(), data.geom.getTriCount(), areas);
}
else
{
// Treat water as impassable: leave all area flags 0.
rcMarkWalkableTriangles(ctx, cfg.walkableSlopeAngle,
data.geom.getVerts(), nonWaterVertCount,
data.geom.getTris(), nonWaterTriCount, areas);
}
rcRasterizeTriangles(ctx,
data.geom.getVerts(), data.geom.getVertCount(),
data.geom.getTris(), areas, data.geom.getTriCount(),
*data.hf, cfg.walkableClimb);
delete[] areas;
// Filter out areas with low ceilings and other stuff.
rcFilterLowHangingWalkableObstacles(ctx, cfg.walkableClimb, *data.hf);
rcFilterLedgeSpans(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf);
rcFilterWalkableLowHeightSpans(ctx, cfg.walkableHeight, *data.hf);
data.chf = rcAllocCompactHeightfield();
if(!data.chf)
{
Con::errorf("Out of memory (rcCompactHeightField) for NavMesh %s", getIdString());
return NULL; return NULL;
} }
if(!rcBuildCompactHeightfield(ctx, cfg.walkableHeight, cfg.walkableClimb, *data.hf, *data.chf))
F32 tbmin[2], tbmax[2];
tbmin[0] = m_cfg.bmin[0];
tbmin[1] = m_cfg.bmin[2];
tbmax[0] = m_cfg.bmax[0];
tbmax[1] = m_cfg.bmax[2];
int cid[512];
const int ncid = rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512);
if (!ncid)
return 0;
for (int i = 0; i < ncid; ++i)
{ {
Con::errorf("Could not generate rcCompactHeightField for NavMesh %s", getIdString()); const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]];
const int* ctris = &chunkyMesh->tris[node.i * 3];
const int nctris = node.n;
memset(m_triareas, 0, nctris * sizeof(unsigned char));
rcMarkWalkableTriangles(ctx, m_cfg.walkableSlopeAngle,
m_geo->getVerts(), m_geo->getVertCount(), ctris, nctris, m_triareas);
if (!rcRasterizeTriangles(ctx, m_geo->getVerts(), m_geo->getVertCount(), ctris, m_triareas, nctris, *m_solid, m_cfg.walkableClimb))
return NULL;
}
if (!mSaveIntermediates)
{
delete[] m_triareas;
m_triareas = 0;
}
// these should be optional.
//if (m_filterLowHangingObstacles)
rcFilterLowHangingWalkableObstacles(ctx, m_cfg.walkableClimb, *m_solid);
//if (m_filterLedgeSpans)
rcFilterLedgeSpans(ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid);
//if (m_filterWalkableLowHeightSpans)
rcFilterWalkableLowHeightSpans(ctx, m_cfg.walkableHeight, *m_solid);
// Compact the heightfield so that it is faster to handle from now on.
// This will result more cache coherent data as well as the neighbours
// between walkable cells will be calculated.
m_chf = rcAllocCompactHeightfield();
if (!m_chf)
{
Con::errorf("NavMesh::buildTileData: Out of memory 'chf'.");
return NULL; return NULL;
} }
if(!rcErodeWalkableArea(ctx, cfg.walkableRadius, *data.chf)) if (!rcBuildCompactHeightfield(ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid, *m_chf))
{ {
Con::errorf("Could not erode walkable area for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not build compact data.");
return NULL;
}
if (!mSaveIntermediates)
{
rcFreeHeightField(m_solid);
m_solid = NULL;
}
// Erode the walkable area by agent radius.
if (!rcErodeWalkableArea(ctx, m_cfg.walkableRadius, *m_chf))
{
Con::errorf("NavMesh::buildTileData: Could not erode.");
return NULL; return NULL;
} }
@ -962,132 +1060,186 @@ unsigned char *NavMesh::buildTileData(const Tile &tile, TileData &data, U32 &dat
//rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf); //rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
//-------------------------- //--------------------------
if(false) // Partition the heightfield so that we can use simple algorithm later to triangulate the walkable areas.
// There are 3 martitioning methods, each with some pros and cons:
// These should be implemented.
// 1) Watershed partitioning
// - the classic Recast partitioning
// - creates the nicest tessellation
// - usually slowest
// - partitions the heightfield into nice regions without holes or overlaps
// - the are some corner cases where this method creates produces holes and overlaps
// - holes may appear when a small obstacles is close to large open area (triangulation can handle this)
// - overlaps may occur if you have narrow spiral corridors (i.e stairs), this make triangulation to fail
// * generally the best choice if you precompute the nacmesh, use this if you have large open areas
// 2) Monotone partioning
// - fastest
// - partitions the heightfield into regions without holes and overlaps (guaranteed)
// - creates long thin polygons, which sometimes causes paths with detours
// * use this if you want fast navmesh generation
// 3) Layer partitoining
// - quite fast
// - partitions the heighfield into non-overlapping regions
// - relies on the triangulation code to cope with holes (thus slower than monotone partitioning)
// - produces better triangles than monotone partitioning
// - does not have the corner cases of watershed partitioning
// - can be slow and create a bit ugly tessellation (still better than monotone)
// if you have large open areas with small obstacles (not a problem if you use tiles)
// * good choice to use for tiled navmesh with medium and small sized tiles
if (/*m_partitionType == SAMPLE_PARTITION_WATERSHED*/ true)
{ {
if(!rcBuildRegionsMonotone(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) // Prepare for region partitioning, by calculating distance field along the walkable surface.
if (!rcBuildDistanceField(ctx, *m_chf))
{ {
Con::errorf("Could not build regions for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not build distance field.");
return 0;
}
// Partition the walkable surface into simple regions without holes.
if (!rcBuildRegions(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
{
Con::errorf("NavMesh::buildTileData: Could not build watershed regions.");
return NULL; return NULL;
} }
} }
else else if (/*m_partitionType == SAMPLE_PARTITION_MONOTONE*/ false)
{ {
if(!rcBuildDistanceField(ctx, *data.chf)) // Partition the walkable surface into simple regions without holes.
// Monotone partitioning does not need distancefield.
if (!rcBuildRegionsMonotone(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
{ {
Con::errorf("Could not build distance field for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not build monotone regions.");
return NULL; return NULL;
} }
if(!rcBuildRegions(ctx, *data.chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) }
else // SAMPLE_PARTITION_LAYERS
{
// Partition the walkable surface into simple regions without holes.
if (!rcBuildLayerRegions(ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea))
{ {
Con::errorf("Could not build regions for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not build layer regions.");
return NULL; return NULL;
} }
} }
data.cs = rcAllocContourSet(); m_cset = rcAllocContourSet();
if(!data.cs) if (!m_cset)
{ {
Con::errorf("Out of memory (rcContourSet) for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Out of memory 'cset'");
return NULL;
}
if(!rcBuildContours(ctx, *data.chf, cfg.maxSimplificationError, cfg.maxEdgeLen, *data.cs))
{
Con::errorf("Could not construct rcContourSet for NavMesh %s", getIdString());
return NULL;
}
if(data.cs->nconts <= 0)
{
Con::errorf("No contours in rcContourSet for NavMesh %s", getIdString());
return NULL; return NULL;
} }
data.pm = rcAllocPolyMesh(); if (!rcBuildContours(ctx, *m_chf, m_cfg.maxSimplificationError, m_cfg.maxEdgeLen, *m_cset))
if(!data.pm)
{ {
Con::errorf("Out of memory (rcPolyMesh) for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not create contours");
return NULL;
}
if(!rcBuildPolyMesh(ctx, *data.cs, cfg.maxVertsPerPoly, *data.pm))
{
Con::errorf("Could not construct rcPolyMesh for NavMesh %s", getIdString());
return NULL; return NULL;
} }
data.pmd = rcAllocPolyMeshDetail(); if (m_cset->nconts == 0)
if(!data.pmd) return NULL;
// Build polygon navmesh from the contours.
m_pmesh = rcAllocPolyMesh();
if (!m_pmesh)
{ {
Con::errorf("Out of memory (rcPolyMeshDetail) for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Out of memory 'pmesh'.");
return NULL; return NULL;
} }
if(!rcBuildPolyMeshDetail(ctx, *data.pm, *data.chf, cfg.detailSampleDist, cfg.detailSampleMaxError, *data.pmd)) if (!rcBuildPolyMesh(ctx, *m_cset, m_cfg.maxVertsPerPoly, *m_pmesh))
{ {
Con::errorf("Could not construct rcPolyMeshDetail for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Could not triangulate contours.");
return NULL; return NULL;
} }
if(data.pm->nverts >= 0xffff) // Build detail mesh.
m_dmesh = rcAllocPolyMeshDetail();
if (!m_dmesh)
{ {
Con::errorf("Too many vertices in rcPolyMesh for NavMesh %s", getIdString()); Con::errorf("NavMesh::buildTileData: Out of memory 'dmesh'.");
return NULL; return NULL;
} }
for(U32 i = 0; i < data.pm->npolys; i++)
{
if(data.pm->areas[i] == RC_WALKABLE_AREA)
data.pm->areas[i] = GroundArea;
if(data.pm->areas[i] == GroundArea) if (!rcBuildPolyMeshDetail(ctx, *m_pmesh, *m_chf, m_cfg.detailSampleDist, m_cfg.detailSampleMaxError, *m_dmesh))
data.pm->flags[i] |= WalkFlag; {
if(data.pm->areas[i] == WaterArea) Con::errorf("NavMesh::buildTileData: Could build polymesh detail.");
data.pm->flags[i] |= SwimFlag; return NULL;
}
if (!mSaveIntermediates)
{
rcFreeCompactHeightfield(m_chf);
m_chf = 0;
rcFreeContourSet(m_cset);
m_cset = 0;
} }
unsigned char* navData = 0; unsigned char* navData = 0;
int navDataSize = 0; int navDataSize = 0;
if (m_cfg.maxVertsPerPoly <= DT_VERTS_PER_POLYGON)
dtNavMeshCreateParams params;
dMemset(&params, 0, sizeof(params));
params.verts = data.pm->verts;
params.vertCount = data.pm->nverts;
params.polys = data.pm->polys;
params.polyAreas = data.pm->areas;
params.polyFlags = data.pm->flags;
params.polyCount = data.pm->npolys;
params.nvp = data.pm->nvp;
params.detailMeshes = data.pmd->meshes;
params.detailVerts = data.pmd->verts;
params.detailVertsCount = data.pmd->nverts;
params.detailTris = data.pmd->tris;
params.detailTriCount = data.pmd->ntris;
params.offMeshConVerts = mLinkVerts.address();
params.offMeshConRad = mLinkRads.address();
params.offMeshConDir = mLinkDirs.address();
params.offMeshConAreas = mLinkAreas.address();
params.offMeshConFlags = mLinkFlags.address();
params.offMeshConUserID = mLinkIDs.address();
params.offMeshConCount = mLinkIDs.size();
params.walkableHeight = mWalkableHeight;
params.walkableRadius = mWalkableRadius;
params.walkableClimb = mWalkableClimb;
params.tileX = tile.x;
params.tileY = tile.y;
params.tileLayer = 0;
rcVcopy(params.bmin, data.pm->bmin);
rcVcopy(params.bmax, data.pm->bmax);
params.cs = cfg.cs;
params.ch = cfg.ch;
params.buildBvTree = true;
if(!dtCreateNavMeshData(&params, &navData, &navDataSize))
{ {
Con::errorf("Could not create dtNavMeshData for tile (%d, %d) of NavMesh %s", if (m_pmesh->nverts >= 0xffff)
tile.x, tile.y, getIdString()); {
return NULL; // The vertex indices are ushorts, and cannot point to more than 0xffff vertices.
} Con::errorf("NavMesh::buildTileData: Too many vertices per tile %d (max: %d).", m_pmesh->nverts, 0xffff);
return NULL;
}
for (U32 i = 0; i < m_pmesh->npolys; i++)
{
if (m_pmesh->areas[i] == RC_WALKABLE_AREA)
m_pmesh->areas[i] = GroundArea;
if (m_pmesh->areas[i] == GroundArea)
m_pmesh->flags[i] |= WalkFlag;
if (m_pmesh->areas[i] == WaterArea)
m_pmesh->flags[i] |= SwimFlag;
}
dtNavMeshCreateParams params;
dMemset(&params, 0, sizeof(params));
params.verts = m_pmesh->verts;
params.vertCount = m_pmesh->nverts;
params.polys = m_pmesh->polys;
params.polyAreas = m_pmesh->areas;
params.polyFlags = m_pmesh->flags;
params.polyCount = m_pmesh->npolys;
params.nvp = m_pmesh->nvp;
params.detailMeshes = m_dmesh->meshes;
params.detailVerts = m_dmesh->verts;
params.detailVertsCount = m_dmesh->nverts;
params.detailTris = m_dmesh->tris;
params.detailTriCount = m_dmesh->ntris;
params.offMeshConVerts = mLinkVerts.address();
params.offMeshConRad = mLinkRads.address();
params.offMeshConDir = mLinkDirs.address();
params.offMeshConAreas = mLinkAreas.address();
params.offMeshConFlags = mLinkFlags.address();
params.offMeshConUserID = mLinkIDs.address();
params.offMeshConCount = mLinkIDs.size();
params.walkableHeight = mWalkableHeight;
params.walkableRadius = mWalkableRadius;
params.walkableClimb = mWalkableClimb;
params.tileX = tile.x;
params.tileY = tile.y;
params.tileLayer = 0;
rcVcopy(params.bmin, m_pmesh->bmin);
rcVcopy(params.bmax, m_pmesh->bmax);
params.cs = m_cfg.cs;
params.ch = m_cfg.ch;
params.buildBvTree = true;
if (!dtCreateNavMeshData(&params, &navData, &navDataSize))
{
Con::errorf("NavMesh::buildTileData: Could not build Detour navmesh.");
return NULL;
}
}
dataSize = navDataSize; dataSize = navDataSize;
return navData; return navData;
@ -1331,6 +1483,22 @@ void NavMesh::renderToDrawer()
{ {
} }
void NavMesh::cleanup()
{
delete[] m_triareas;
m_triareas = 0;
rcFreeHeightField(m_solid);
m_solid = 0;
rcFreeCompactHeightfield(m_chf);
m_chf = 0;
rcFreeContourSet(m_cset);
m_cset = 0;
rcFreePolyMesh(m_pmesh);
m_pmesh = 0;
rcFreePolyMeshDetail(m_dmesh);
m_dmesh = 0;
}
void NavMesh::prepRenderImage(SceneRenderState *state) void NavMesh::prepRenderImage(SceneRenderState *state)
{ {
ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();

View file

@ -366,9 +366,6 @@ private:
/// @name Intermediate data /// @name Intermediate data
/// @{ /// @{
/// Config struct.
rcConfig cfg;
/// Updates our config from console members. /// Updates our config from console members.
void updateConfig(); void updateConfig();
@ -419,6 +416,18 @@ private:
/// Use this object to manage update events. /// Use this object to manage update events.
static SimObjectPtr<EventManager> smEventManager; static SimObjectPtr<EventManager> smEventManager;
protected:
RecastPolyList* m_geo;
unsigned char* m_triareas;
rcHeightfield* m_solid;
rcCompactHeightfield* m_chf;
rcContourSet* m_cset;
rcPolyMesh* m_pmesh;
rcPolyMeshDetail* m_dmesh;
rcConfig m_cfg;
void cleanup();
}; };
typedef NavMesh::WaterMethod NavMeshWaterMethod; typedef NavMesh::WaterMethod NavMeshWaterMethod;

View file

@ -27,7 +27,7 @@
#include "gfx/primBuilder.h" #include "gfx/primBuilder.h"
#include "gfx/gfxStateBlock.h" #include "gfx/gfxStateBlock.h"
RecastPolyList::RecastPolyList() RecastPolyList::RecastPolyList() : mChunkyMesh(0)
{ {
nverts = 0; nverts = 0;
verts = NULL; verts = NULL;
@ -44,6 +44,28 @@ RecastPolyList::~RecastPolyList()
clear(); clear();
} }
rcChunkyTriMesh* RecastPolyList::getChunkyMesh()
{
if (!mChunkyMesh)
{
mChunkyMesh = new rcChunkyTriMesh;
if (!mChunkyMesh)
{
Con::errorf("Build tile navigation: out of memory");
return NULL;
}
if (!rcCreateChunkyTriMesh(getVerts(), getTris(), getTriCount(), 256, mChunkyMesh))
{
Con::errorf("Build tile navigation: out of memory");
return NULL;
}
}
return mChunkyMesh;
}
void RecastPolyList::clear() void RecastPolyList::clear()
{ {
nverts = 0; nverts = 0;

View file

@ -26,6 +26,10 @@
#include "collision/abstractPolyList.h" #include "collision/abstractPolyList.h"
#include "core/util/tVector.h" #include "core/util/tVector.h"
#ifndef CHUNKYTRIMESH_H
#include "ChunkyTriMesh.h"
#endif
/// Represents polygons in the same manner as the .obj file format. Handy for /// Represents polygons in the same manner as the .obj file format. Handy for
/// padding data to Recast, since it expects this data format. At the moment, /// padding data to Recast, since it expects this data format. At the moment,
/// this class only accepts triangles. /// this class only accepts triangles.
@ -70,6 +74,9 @@ public:
/// Default destructor. /// Default destructor.
~RecastPolyList(); ~RecastPolyList();
rcChunkyTriMesh* getChunkyMesh();
protected: protected:
/// Number of vertices defined. /// Number of vertices defined.
U32 nverts; U32 nverts;
@ -93,6 +100,8 @@ protected:
/// Another inherited utility function. /// Another inherited utility function.
const PlaneF& getIndexedPlane(const U32 index) override { return planes[index]; } const PlaneF& getIndexedPlane(const U32 index) override { return planes[index]; }
rcChunkyTriMesh* mChunkyMesh;
private: private:
}; };