Certainly! To integrate water into your tile cache build and ensure that pathfinding avoids rivers by preferring bridges, you'll need to perform several steps:
-
Rasterize the Water Mesh: Process the water geometry similarly to the main mesh but mark these areas distinctly (e.g., as water) so the navigation system can recognize and avoid them.
-
Mark Water Areas Appropriately: Assign a specific area type (like SAMPLE_POLYAREA_WATER) to water regions. This allows the pathfinding system to identify these areas and avoid them unless there's a bridge.
-
Handle Bridges Separately: If bridges are present, ensure they are marked as walkable areas, enabling agents to prefer traversing bridges over swimming or going around the water.
-
Adjust Pathfinding Filters: Since you're excluding the swim flag in the path filter, ensure that water areas are treated as non-walkable or high-cost regions.
Below is the modified version of your rasterizeTileLayers function with water handling implemented. I'll include detailed comments to guide you through the changes.
int NavMeshBuilder::rasterizeTileLayers(const int tx, const int ty, const rcConfig& cfg, TileCacheData* tiles, const int maxTiles) {
FastLZCompressor comp;
RasterizationContext rc;
const float* verts;
int nverts = 0;
const rcChunkyTriMesh* chunkyMesh;
const rcChunkyTriMesh* chunkyWaterMesh;
int waternverts;
const float* waterverts;
{
// Retrieve main mesh data
verts = m_World->GetStaticWorldMesh().getVerts();
nverts = m_World->GetStaticWorldMesh().getVertCount();
chunkyMesh = m_World->GetChunkyMesh();
// Retrieve water mesh data
chunkyWaterMesh = m_World->GetWaterChunkyMesh();
waternverts = m_World->GetWaterWorldMesh().getVertCount();
waterverts = m_World->GetWaterWorldMesh().getVerts();
}
float tcs = cfg.tileSize * cfg.cs;
rcConfig tcfg;
memcpy(&tcfg, &cfg, sizeof(tcfg));
// Calculate tile bounds
tcfg.bmin[0] = cfg.bmin[0] + tx * tcs;
tcfg.bmin[1] = cfg.bmin[1];
tcfg.bmin[2] = cfg.bmin[2] + ty * tcs;
tcfg.bmax[0] = cfg.bmin[0] + (tx + 1) * tcs;
tcfg.bmax[1] = cfg.bmax[1];
tcfg.bmax[2] = cfg.bmin[2] + (ty + 1) * tcs;
// Expand bounds by border size
tcfg.bmin[0] -= tcfg.borderSize * tcfg.cs;
tcfg.bmin[2] -= tcfg.borderSize * tcfg.cs;
tcfg.bmax[0] += tcfg.borderSize * tcfg.cs;
tcfg.bmax[2] += tcfg.borderSize * tcfg.cs;
// Allocate voxel heightfield
rc.solid = rcAllocHeightfield();
if (!rc.solid) {
printf("buildNavigation: Out of memory 'solid'.\n");
return 0;
}
std::unique_ptr<rcContext> m_ctx = std::make_unique<rcContext>();
if (!rcCreateHeightfield(m_ctx.get(), *rc.solid, tcfg.width, tcfg.height, tcfg.bmin, tcfg.bmax, tcfg.cs, tcfg.ch)) {
printf("buildNavigation: Could not create solid heightfield.\n");
return 0;
}
// Allocate triangle areas
rc.triareas = new unsigned char[chunkyMesh->maxTrisPerChunk];
if (!rc.triareas) {
printf("buildNavigation: Out of memory 'm_triareas' (%d).\n", chunkyMesh->maxTrisPerChunk);
return 0;
}
// Define tile bounds for main mesh
float tbmin[2] = { tcfg.bmin[0], tcfg.bmin[2] };
float tbmax[2] = { tcfg.bmax[0], tcfg.bmax[2] };
int cid[512];
const int ncid = rcChunkyTriMesh::rcGetChunksOverlappingRect(chunkyMesh, tbmin, tbmax, cid, 512);
if (!ncid) {
return 0;
}
// Rasterize main mesh triangles
for (int i = 0; i < ncid; ++i) {
const rcChunkyTriMeshNode& node = chunkyMesh->nodes[cid[i]];
const int* tris = &chunkyMesh->tris[node.i * 3];
const int ntris = node.n;
memset(rc.triareas, 0, ntris * sizeof(unsigned char));
rcMarkWalkableTriangles(m_ctx.get(), tcfg.walkableSlopeAngle, verts, nverts, tris, ntris, rc.triareas);
if (!rcRasterizeTriangles(m_ctx.get(), verts, nverts, tris, rc.triareas, ntris, *rc.solid, tcfg.walkableClimb))
return 0;
}
// **Rasterize Water Mesh**
if (chunkyWaterMesh) {
// Define water tile bounds (assuming water mesh uses the same horizontal dimensions)
float waterTbmin[2] = { tcfg.bmin[0], tcfg.bmin[2] };
float waterTbmax[2] = { tcfg.bmax[0], tcfg.bmax[2] };
int waterCid[512];
const int waterNcid = rcChunkyTriMesh::rcGetChunksOverlappingRect(chunkyWaterMesh, waterTbmin, waterTbmax, waterCid, 512);
if (waterNcid > 0) {
for (int i = 0; i < waterNcid; ++i) {
const rcChunkyTriMeshNode& waterNode = chunkyWaterMesh->nodes[waterCid[i]];
const int* waterTris = &chunkyWaterMesh->tris[waterNode.i * 3];
const int nWaterTris = waterNode.n;
// Mark all water triangles with SAMPLE_POLYAREA_WATER
memset(rc.triareas, 0, nWaterTris * sizeof(unsigned char));
for (int t = 0; t < nWaterTris; ++t) {
rc.triareas[t] = SAMPLE_POLYAREA_WATER;
}
// Rasterize water triangles
if (!rcRasterizeTriangles(m_ctx.get(), waterverts, waternverts, waterTris, rc.triareas, nWaterTris, *rc.solid, tcfg.walkableClimb))
return 0;
}
}
}
// Apply filters to the heightfield
rcFilterLowHangingWalkableObstacles(m_ctx.get(), tcfg.walkableClimb, *rc.solid);
rcFilterLedgeSpans(m_ctx.get(), tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid);
rcFilterWalkableLowHeightSpans(m_ctx.get(), tcfg.walkableHeight, *rc.solid);
// Allocate and build compact heightfield
rc.chf = rcAllocCompactHeightfield();
if (!rc.chf) {
printf("buildNavigation: Out of memory 'chf'.\n");
return 0;
}
if (!rcBuildCompactHeightfield(m_ctx.get(), tcfg.walkableHeight, tcfg.walkableClimb, *rc.solid, *rc.chf)) {
printf("buildNavigation: Could not build compact data.\n");
return 0;
}
// Identify and mark water areas in compact heightfield
for (int i = 0; i < rc.chf->spanCount; ++i) {
if (rc.chf->areas[i] == SAMPLE_POLYAREA_WATER) {
// Optionally, you can mark water areas differently or leave them as is
rc.chf->areas[i] = SAMPLE_POLYAREA_WATER;
}
}
// Erode walkable areas to account for agent radius
if (!rcErodeWalkableArea(m_ctx.get(), tcfg.walkableRadius, *rc.chf)) {
printf("buildNavigation: Could not erode.\n");
return 0;
}
// Optionally, re-mark water areas after erosion if necessary
for (int i = 0; i < rc.chf->spanCount; ++i) {
if (rc.chf->areas[i] == SAMPLE_POLYAREA_WATER) {
rc.chf->areas[i] = SAMPLE_POLYAREA_WATER;
}
}
// Allocate and build heightfield layers
rc.lset = rcAllocHeightfieldLayerSet();
if (!rc.lset) {
printf("buildNavigation: Out of memory 'lset'.\n");
return 0;
}
if (!rcBuildHeightfieldLayers(m_ctx.get(), *rc.chf, tcfg.borderSize, tcfg.walkableHeight, *rc.lset)) {
// Optionally log or handle the error
return 0;
}
// Mark water areas in each layer
for (int i = 0; i < rc.lset->nlayers; ++i) {
rcHeightfieldLayer* layer = &rc.lset->layers[i];
for (int j = 0; j < layer->width * layer->height; ++j) {
if (layer->areas[j] == SAMPLE_POLYAREA_WATER) {
layer->areas[j] = SAMPLE_POLYAREA_WATER;
}
}
}
// Initialize tile count
rc.ntiles = 0;
// Iterate through layers and build tile cache layers
for (int i = 0; i < rcMin(rc.lset->nlayers, MAX_LAYERS); ++i) {
TileCacheData* tile = &rc.tiles[rc.ntiles++];
const rcHeightfieldLayer* layer = &rc.lset->layers[i];
dtTileCacheLayerHeader header;
// Populate header
header.magic = DT_TILECACHE_MAGIC;
header.version = DT_TILECACHE_VERSION;
header.tx = tx;
header.ty = ty;
header.tlayer = i;
dtVcopy(header.bmin, layer->bmin);
dtVcopy(header.bmax, layer->bmax);
header.width = (unsigned char)layer->width;
header.height = (unsigned char)layer->height;
header.minx = (unsigned char)layer->minx;
header.maxx = (unsigned char)layer->maxx;
header.miny = (unsigned char)layer->miny;
header.maxy = (unsigned char)layer->maxy;
header.hmin = (unsigned short)layer->hmin;
header.hmax = (unsigned short)layer->hmax;
// Build tile cache layer
dtStatus status = dtBuildTileCacheLayer(&comp, &header, layer->heights, layer->areas, layer->cons, &tile->data, &tile->dataSize);
if (dtStatusFailed(status)) {
return 0;
}
}
// Transfer ownership of tile data to the caller
int n = 0;
for (int i = 0; i < rcMin(rc.ntiles, maxTiles); ++i) {
tiles[n++] = rc.tiles[i];
rc.tiles[i].data = 0;
rc.tiles[i].dataSize = 0;
}
// Clean up allocated memory
delete[] rc.triareas;
rcFreeHeightfield(*rc.solid);
rcFreeCompactHeightfield(*rc.chf);
rcFreeHeightfieldLayerSet(*rc.lset);
return n;
}
Detailed Explanation of Changes
-
Processing the Water Mesh:
- After rasterizing the main mesh, the function checks if a
chunkyWaterMesh exists. If it does, it retrieves the overlapping chunks for the current tile.
- For each water chunk, it marks all triangles as
SAMPLE_POLYAREA_WATER before rasterization. This ensures that water areas are distinctly identified in the heightfield.
-
Marking Water Areas:
- By setting
rc.triareas[t] = SAMPLE_POLYAREA_WATER;, the rasterization process marks these areas as water.
- After building the compact heightfield, there's an optional loop that reaffirms the water area assignments. This is useful if erosion or other filtering steps might have altered these areas.
-
Handling Bridges:
- Ensure that bridges are included in the main mesh (
chunkyMesh) and not in the water mesh (chunkyWaterMesh). Bridges should be marked with standard walkable area types (e.g., SAMPLE_POLYAREA_GROUND).
- Since bridges are part of the main mesh, agents will prefer traversing them over navigating through water areas, especially when the swim flag is excluded in pathfinding filters.
-
Adjusting Pathfinding Filters:
- Ensure that your pathfinding logic excludes the swim flag or treats
SAMPLE_POLYAREA_WATER as non-walkable. This will make agents avoid water areas unless a bridge is available.
-
Memory Management:
- Added a cleanup section at the end of the function to free allocated memory. This is crucial to prevent memory leaks, especially if the function is called repeatedly during tile generation.
Additional Recommendations
By implementing these changes, your tile cache build process will account for water areas, allowing pathfinding to intelligently navigate around rivers by preferring bridges, thereby enhancing the navigation behavior in your application.