【发布时间】:2020-04-22 13:59:25
【问题描述】:
我正在尝试检查数组中的邻居并且没有边缘情况检查限制,程序将导致异常。我至少需要检查bottomLeft、bottomRight、topLeft topRight 角。我在 DirectXTDK 工作,该功能用于平滑景观。
bool Terrain::SmoothenHeightMap(ID3D11Device* device)
{
bool result;
int index, nx, nz;
float height = 0.0;
int neighbours[8] = {}; // array starts at 0, inclusive
int n = 8;
/* Initialise corner of height map */ // 1.
int bottomLeftCorner = 0;
int bottomRightCorner = (m_terrainHeight * (m_terrainHeight - 1));
int topLeftCorner = (m_terrainWidth - 1);
int topRightCorner = m_terrainHeight * (m_terrainHeight - 1) + (m_terrainWidth - 1);
m_frequency = (6.283 / m_terrainHeight) / m_wavelength; //we want a wavelength of 1 to be a single wave over the whole terrain. A single wave is 2 pi which is about 6.283
// m_terrainHeight is actually the z axis
for (int j = 0; j < m_terrainHeight; j++)
{
for (int i = 0; i < m_terrainWidth; i++)
{
index = (m_terrainHeight * j) + i;
float sum = m_heightMap[index].y;
// with more than 128 square dimensions, initial neighbours on bottom row might not exist
// can refractor this better if it works
if (m_heightMap[(m_terrainHeight * (j - 1)) + (i - 1)].x != NULL) {
neighbours[0] = m_heightMap[(m_terrainHeight * (j + 1)) + (i - 1)].y; // top left
neighbours[1] = m_heightMap[(m_terrainHeight * (j + 1)) + (i)].y; // top middle
neighbours[2] = m_heightMap[(m_terrainHeight * (j + 1)) + (i + 1)].y; // top right
neighbours[3] = m_heightMap[(m_terrainHeight * (j)) + (i - 1)].y; // middle left
neighbours[4] = m_heightMap[(m_terrainHeight * (j)) + (i + 1)].y; // middle right
neighbours[5] = m_heightMap[(m_terrainHeight * (j - 1)) + (i - 1)].y; // bottom left
neighbours[6] = m_heightMap[(m_terrainHeight * (j - 1)) + (i)].y; // bottom middle
neighbours[7] = m_heightMap[(m_terrainHeight * (j - 1)) + (i + 1)].y; // bottom right
}
for (int z = 0; z < n; z++)
{
if (neighbours[z] < 0 || neighbours[z] >= m_terrainHeight * m_terrainWidth) // if out of map, take y of current index for sum
{
sum += m_heightMap[index].y;
}
else
{
sum += neighbours[z]; // if exists, include in sum
}
}
// smoothen based on neighbours
m_heightMap[index].y = sum / 9.0f; // current point n is no. of neighbours +1 for current vertex point// total of 9 points in a 3*3 grid
}
}
result = CalculateNormals();
if (!result)
{
return false;
}
result = InitializeBuffers(device);
if (!result)
{
return false;
}
}
上述代码用于平滑地形,使用高度图通过存储在结构中的点。以下是结构体:
struct HeightMapType
{
float x, y, z;
float nx, ny, nz;
float u, v;
};
通过创建一个名为m_heightmap的指针来使用它。
HeightMapType* m_heightMap;
【问题讨论】:
-
你是正确的按照指南修改
-
(m_terrainHeight * (j - 1)) + (i - 1))此值超出范围,当您发生错误时。 -
什么是
m_heightMap?使用 std::vector 或 std::array,使用.at(index)访问它并将其包装在 try catch 中,那么您就不会有这个问题。还建议使用nullptr而不是NULL -
是的,因为我在数组的开头,并且正在检查前几次迭代行和其余角落不存在的邻居
-
@firepro20 当然你可以有结构的std::vectors!它是 C++!
标签: c++ arrays nearest-neighbor neighbours