Path: blob/master/thirdparty/recastnavigation/Recast/Source/RecastLayers.cpp
9913 views
//1// Copyright (c) 2009-2010 Mikko Mononen [email protected]2//3// This software is provided 'as-is', without any express or implied4// warranty. In no event will the authors be held liable for any damages5// arising from the use of this software.6// Permission is granted to anyone to use this software for any purpose,7// including commercial applications, and to alter it and redistribute it8// freely, subject to the following restrictions:9// 1. The origin of this software must not be misrepresented; you must not10// claim that you wrote the original software. If you use this software11// in a product, an acknowledgment in the product documentation would be12// appreciated but is not required.13// 2. Altered source versions must be plainly marked as such, and must not be14// misrepresented as being the original software.15// 3. This notice may not be removed or altered from any source distribution.16//1718#include <float.h>19#include <math.h>20#include <string.h>21#include <stdlib.h>22#include <stdio.h>23#include "Recast.h"24#include "RecastAlloc.h"25#include "RecastAssert.h"262728// Must be 255 or smaller (not 256) because layer IDs are stored as29// a byte where 255 is a special value.30#ifndef RC_MAX_LAYERS_DEF31#define RC_MAX_LAYERS_DEF 6332#endif3334#if RC_MAX_LAYERS_DEF > 25535#error RC_MAX_LAYERS_DEF must be 255 or smaller36#endif3738#ifndef RC_MAX_NEIS_DEF39#define RC_MAX_NEIS_DEF 1640#endif4142// Keep type checking.43static const int RC_MAX_LAYERS = RC_MAX_LAYERS_DEF;44static const int RC_MAX_NEIS = RC_MAX_NEIS_DEF;4546struct rcLayerRegion47{48unsigned char layers[RC_MAX_LAYERS];49unsigned char neis[RC_MAX_NEIS];50unsigned short ymin, ymax;51unsigned char layerId; // Layer ID52unsigned char nlayers; // Layer count53unsigned char nneis; // Neighbour count54unsigned char base; // Flag indicating if the region is the base of merged regions.55};565758static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v)59{60const int n = (int)an;61for (int i = 0; i < n; ++i)62{63if (a[i] == v)64return true;65}66return false;67}6869static bool addUnique(unsigned char* a, unsigned char& an, int anMax, unsigned char v)70{71if (contains(a, an, v))72return true;7374if ((int)an >= anMax)75return false;7677a[an] = v;78an++;79return true;80}818283inline bool overlapRange(const unsigned short amin, const unsigned short amax,84const unsigned short bmin, const unsigned short bmax)85{86return (amin > bmax || amax < bmin) ? false : true;87}88899091struct rcLayerSweepSpan92{93unsigned short ns; // number samples94unsigned char id; // region id95unsigned char nei; // neighbour id96};9798/// @par99///100/// See the #rcConfig documentation for more information on the configuration parameters.101///102/// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig103bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf,104const int borderSize, const int walkableHeight,105rcHeightfieldLayerSet& lset)106{107rcAssert(ctx);108109rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS);110111const int w = chf.width;112const int h = chf.height;113114rcScopedDelete<unsigned char> srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));115if (!srcReg)116{117ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);118return false;119}120memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);121122const int nsweeps = chf.width;123rcScopedDelete<rcLayerSweepSpan> sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));124if (!sweeps)125{126ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);127return false;128}129130131// Partition walkable area into monotone regions.132int prevCount[256];133unsigned char regId = 0;134135for (int y = borderSize; y < h-borderSize; ++y)136{137memset(prevCount,0,sizeof(int)*regId);138unsigned char sweepId = 0;139140for (int x = borderSize; x < w-borderSize; ++x)141{142const rcCompactCell& c = chf.cells[x+y*w];143144for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)145{146const rcCompactSpan& s = chf.spans[i];147if (chf.areas[i] == RC_NULL_AREA) continue;148149unsigned char sid = 0xff;150151// -x152if (rcGetCon(s, 0) != RC_NOT_CONNECTED)153{154const int ax = x + rcGetDirOffsetX(0);155const int ay = y + rcGetDirOffsetY(0);156const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);157if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)158sid = srcReg[ai];159}160161if (sid == 0xff)162{163sid = sweepId++;164sweeps[sid].nei = 0xff;165sweeps[sid].ns = 0;166}167168// -y169if (rcGetCon(s,3) != RC_NOT_CONNECTED)170{171const int ax = x + rcGetDirOffsetX(3);172const int ay = y + rcGetDirOffsetY(3);173const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);174const unsigned char nr = srcReg[ai];175if (nr != 0xff)176{177// Set neighbour when first valid neighbour is encoutered.178if (sweeps[sid].ns == 0)179sweeps[sid].nei = nr;180181if (sweeps[sid].nei == nr)182{183// Update existing neighbour184sweeps[sid].ns++;185prevCount[nr]++;186}187else188{189// This is hit if there is nore than one neighbour.190// Invalidate the neighbour.191sweeps[sid].nei = 0xff;192}193}194}195196srcReg[i] = sid;197}198}199200// Create unique ID.201for (int i = 0; i < sweepId; ++i)202{203// If the neighbour is set and there is only one continuous connection to it,204// the sweep will be merged with the previous one, else new region is created.205if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns)206{207sweeps[i].id = sweeps[i].nei;208}209else210{211if (regId == 255)212{213ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow.");214return false;215}216sweeps[i].id = regId++;217}218}219220// Remap local sweep ids to region ids.221for (int x = borderSize; x < w-borderSize; ++x)222{223const rcCompactCell& c = chf.cells[x+y*w];224for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)225{226if (srcReg[i] != 0xff)227srcReg[i] = sweeps[srcReg[i]].id;228}229}230}231232// Allocate and init layer regions.233const int nregs = (int)regId;234rcScopedDelete<rcLayerRegion> regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP));235if (!regs)236{237ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);238return false;239}240memset(regs, 0, sizeof(rcLayerRegion)*nregs);241for (int i = 0; i < nregs; ++i)242{243regs[i].layerId = 0xff;244regs[i].ymin = 0xffff;245regs[i].ymax = 0;246}247248// Find region neighbours and overlapping regions.249for (int y = 0; y < h; ++y)250{251for (int x = 0; x < w; ++x)252{253const rcCompactCell& c = chf.cells[x+y*w];254255unsigned char lregs[RC_MAX_LAYERS];256int nlregs = 0;257258for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)259{260const rcCompactSpan& s = chf.spans[i];261const unsigned char ri = srcReg[i];262if (ri == 0xff) continue;263264regs[ri].ymin = rcMin(regs[ri].ymin, s.y);265regs[ri].ymax = rcMax(regs[ri].ymax, s.y);266267// Collect all region layers.268if (nlregs < RC_MAX_LAYERS)269lregs[nlregs++] = ri;270271// Update neighbours272for (int dir = 0; dir < 4; ++dir)273{274if (rcGetCon(s, dir) != RC_NOT_CONNECTED)275{276const int ax = x + rcGetDirOffsetX(dir);277const int ay = y + rcGetDirOffsetY(dir);278const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);279const unsigned char rai = srcReg[ai];280if (rai != 0xff && rai != ri)281{282// Don't check return value -- if we cannot add the neighbor283// it will just cause a few more regions to be created, which284// is fine.285addUnique(regs[ri].neis, regs[ri].nneis, RC_MAX_NEIS, rai);286}287}288}289290}291292// Update overlapping regions.293for (int i = 0; i < nlregs-1; ++i)294{295for (int j = i+1; j < nlregs; ++j)296{297if (lregs[i] != lregs[j])298{299rcLayerRegion& ri = regs[lregs[i]];300rcLayerRegion& rj = regs[lregs[j]];301302if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, lregs[j]) ||303!addUnique(rj.layers, rj.nlayers, RC_MAX_LAYERS, lregs[i]))304{305ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");306return false;307}308}309}310}311312}313}314315// Create 2D layers from regions.316unsigned char layerId = 0;317318static const int MAX_STACK = 64;319unsigned char stack[MAX_STACK];320int nstack = 0;321322for (int i = 0; i < nregs; ++i)323{324rcLayerRegion& root = regs[i];325// Skip already visited.326if (root.layerId != 0xff)327continue;328329// Start search.330root.layerId = layerId;331root.base = 1;332333nstack = 0;334stack[nstack++] = (unsigned char)i;335336while (nstack)337{338// Pop front339rcLayerRegion& reg = regs[stack[0]];340nstack--;341for (int j = 0; j < nstack; ++j)342stack[j] = stack[j+1];343344const int nneis = (int)reg.nneis;345for (int j = 0; j < nneis; ++j)346{347const unsigned char nei = reg.neis[j];348rcLayerRegion& regn = regs[nei];349// Skip already visited.350if (regn.layerId != 0xff)351continue;352// Skip if the neighbour is overlapping root region.353if (contains(root.layers, root.nlayers, nei))354continue;355// Skip if the height range would become too large.356const int ymin = rcMin(root.ymin, regn.ymin);357const int ymax = rcMax(root.ymax, regn.ymax);358if ((ymax - ymin) >= 255)359continue;360361if (nstack < MAX_STACK)362{363// Deepen364stack[nstack++] = (unsigned char)nei;365366// Mark layer id367regn.layerId = layerId;368// Merge current layers to root.369for (int k = 0; k < regn.nlayers; ++k)370{371if (!addUnique(root.layers, root.nlayers, RC_MAX_LAYERS, regn.layers[k]))372{373ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");374return false;375}376}377root.ymin = rcMin(root.ymin, regn.ymin);378root.ymax = rcMax(root.ymax, regn.ymax);379}380}381}382383layerId++;384}385386// Merge non-overlapping regions that are close in height.387const unsigned short mergeHeight = (unsigned short)walkableHeight * 4;388389for (int i = 0; i < nregs; ++i)390{391rcLayerRegion& ri = regs[i];392if (!ri.base) continue;393394unsigned char newId = ri.layerId;395396for (;;)397{398unsigned char oldId = 0xff;399400for (int j = 0; j < nregs; ++j)401{402if (i == j) continue;403rcLayerRegion& rj = regs[j];404if (!rj.base) continue;405406// Skip if the regions are not close to each other.407if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight))408continue;409// Skip if the height range would become too large.410const int ymin = rcMin(ri.ymin, rj.ymin);411const int ymax = rcMax(ri.ymax, rj.ymax);412if ((ymax - ymin) >= 255)413continue;414415// Make sure that there is no overlap when merging 'ri' and 'rj'.416bool overlap = false;417// Iterate over all regions which have the same layerId as 'rj'418for (int k = 0; k < nregs; ++k)419{420if (regs[k].layerId != rj.layerId)421continue;422// Check if region 'k' is overlapping region 'ri'423// Index to 'regs' is the same as region id.424if (contains(ri.layers,ri.nlayers, (unsigned char)k))425{426overlap = true;427break;428}429}430// Cannot merge of regions overlap.431if (overlap)432continue;433434// Can merge i and j.435oldId = rj.layerId;436break;437}438439// Could not find anything to merge with, stop.440if (oldId == 0xff)441break;442443// Merge444for (int j = 0; j < nregs; ++j)445{446rcLayerRegion& rj = regs[j];447if (rj.layerId == oldId)448{449rj.base = 0;450// Remap layerIds.451rj.layerId = newId;452// Add overlaid layers from 'rj' to 'ri'.453for (int k = 0; k < rj.nlayers; ++k)454{455if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, rj.layers[k]))456{457ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");458return false;459}460}461462// Update height bounds.463ri.ymin = rcMin(ri.ymin, rj.ymin);464ri.ymax = rcMax(ri.ymax, rj.ymax);465}466}467}468}469470// Compact layerIds471unsigned char remap[256];472memset(remap, 0, 256);473474// Find number of unique layers.475layerId = 0;476for (int i = 0; i < nregs; ++i)477remap[regs[i].layerId] = 1;478for (int i = 0; i < 256; ++i)479{480if (remap[i])481remap[i] = layerId++;482else483remap[i] = 0xff;484}485// Remap ids.486for (int i = 0; i < nregs; ++i)487regs[i].layerId = remap[regs[i].layerId];488489// No layers, return empty.490if (layerId == 0)491return true;492493// Create layers.494rcAssert(lset.layers == 0);495496const int lw = w - borderSize*2;497const int lh = h - borderSize*2;498499// Build contracted bbox for layers.500float bmin[3], bmax[3];501rcVcopy(bmin, chf.bmin);502rcVcopy(bmax, chf.bmax);503bmin[0] += borderSize*chf.cs;504bmin[2] += borderSize*chf.cs;505bmax[0] -= borderSize*chf.cs;506bmax[2] -= borderSize*chf.cs;507508lset.nlayers = (int)layerId;509510lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM);511if (!lset.layers)512{513ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers);514return false;515}516memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers);517518519// Store layers.520for (int i = 0; i < lset.nlayers; ++i)521{522unsigned char curId = (unsigned char)i;523524rcHeightfieldLayer* layer = &lset.layers[i];525526const int gridSize = sizeof(unsigned char)*lw*lh;527528layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);529if (!layer->heights)530{531ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize);532return false;533}534memset(layer->heights, 0xff, gridSize);535536layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);537if (!layer->areas)538{539ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize);540return false;541}542memset(layer->areas, 0, gridSize);543544layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);545if (!layer->cons)546{547ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize);548return false;549}550memset(layer->cons, 0, gridSize);551552// Find layer height bounds.553int hmin = 0, hmax = 0;554for (int j = 0; j < nregs; ++j)555{556if (regs[j].base && regs[j].layerId == curId)557{558hmin = (int)regs[j].ymin;559hmax = (int)regs[j].ymax;560}561}562563layer->width = lw;564layer->height = lh;565layer->cs = chf.cs;566layer->ch = chf.ch;567568// Adjust the bbox to fit the heightfield.569rcVcopy(layer->bmin, bmin);570rcVcopy(layer->bmax, bmax);571layer->bmin[1] = bmin[1] + hmin*chf.ch;572layer->bmax[1] = bmin[1] + hmax*chf.ch;573layer->hmin = hmin;574layer->hmax = hmax;575576// Update usable data region.577layer->minx = layer->width;578layer->maxx = 0;579layer->miny = layer->height;580layer->maxy = 0;581582// Copy height and area from compact heightfield.583for (int y = 0; y < lh; ++y)584{585for (int x = 0; x < lw; ++x)586{587const int cx = borderSize+x;588const int cy = borderSize+y;589const rcCompactCell& c = chf.cells[cx+cy*w];590for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)591{592const rcCompactSpan& s = chf.spans[j];593// Skip unassigned regions.594if (srcReg[j] == 0xff)595continue;596// Skip of does nto belong to current layer.597unsigned char lid = regs[srcReg[j]].layerId;598if (lid != curId)599continue;600601// Update data bounds.602layer->minx = rcMin(layer->minx, x);603layer->maxx = rcMax(layer->maxx, x);604layer->miny = rcMin(layer->miny, y);605layer->maxy = rcMax(layer->maxy, y);606607// Store height and area type.608const int idx = x+y*lw;609layer->heights[idx] = (unsigned char)(s.y - hmin);610layer->areas[idx] = chf.areas[j];611612// Check connection.613unsigned char portal = 0;614unsigned char con = 0;615for (int dir = 0; dir < 4; ++dir)616{617if (rcGetCon(s, dir) != RC_NOT_CONNECTED)618{619const int ax = cx + rcGetDirOffsetX(dir);620const int ay = cy + rcGetDirOffsetY(dir);621const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);622unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;623// Portal mask624if (chf.areas[ai] != RC_NULL_AREA && lid != alid)625{626portal |= (unsigned char)(1<<dir);627// Update height so that it matches on both sides of the portal.628const rcCompactSpan& as = chf.spans[ai];629if (as.y > hmin)630layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin));631}632// Valid connection mask633if (chf.areas[ai] != RC_NULL_AREA && lid == alid)634{635const int nx = ax - borderSize;636const int ny = ay - borderSize;637if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)638con |= (unsigned char)(1<<dir);639}640}641}642643layer->cons[idx] = (portal << 4) | con;644}645}646}647648if (layer->minx > layer->maxx)649layer->minx = layer->maxx = 0;650if (layer->miny > layer->maxy)651layer->miny = layer->maxy = 0;652}653654return true;655}656657658