[英]In a hexagon graph, how do I store 3D coordinates as an index for a 1D container / retrieve an element from a 1D container using 3D coordinates?
我正在尝试使用立方坐标存储六边形图,详见https://www.redblobgames.com/grids/hexagons/#coordinates
我想使用一个向量或一些易于迭代的容器来存储 Hex 对象,基本上是 3D 整数坐标的集合加上一个包含相邻 Hex 索引的向量。
我的问题是我在想出将立方 X/Y/Z 坐标(允许负整数值)转换为相应的一维容器索引的函数时遇到了麻烦。 给定任何有效的坐标集,我希望能够获得十六进制的特定索引号。
我知道一个功能像
1D_index = f(x,y,z) = x + (max_width)*y + (max_width)(max_height)*z,
对于笛卡尔网格,但我无法在六边形空间中生成类似的函数:
我的十六进制类和容器是这样的:
class Hex
{
private:
int xCell, yCell, zCell;
std::vector<int>neighbours;
public:
Hex();
Hex(int x, int y, int z) : _x(x), _y(y), _z(z);
~Hex();
};
std::vector<Hex*>hexGraph;
为了用未连接的节点填充图形,我仅使用列出所有可能存在的坐标,给定图形的正负 x/y/z 维度:
for(int x = effectiveWorldNegX; x < effectiveWorldPosX; x++)
for(int y = effectiveWorldPosY; y > effectiveWorldNegY; y--)
hexGraph.push_back(new Hex(x,y,(x*-1)-y)); // x+y+z=0, so z=(-x-y)
现在这是我难倒的地方。 我想使用这样的循环连接节点:
for(std::vector<Hex*>iterator it = hexGraph.begin(); it != hexGraph.end(); ++it)
{
(*it)->neighbours.push_back( /* Index of upper left hex node */ )
(*it)->neighbours.push_back( /* Index of upper center hex node */ )
(*it)->neighbours.push_back( /* Index of upper right hex node */ )
...
}
依此类推,但为了做到这一点,我需要一种方法来找到任何单元格的索引,例如 +1x、-1y、+0z。
从上面的循环中,我确定的是 1) 给定循环的开始/结束,将 Hex 推回 hexGraph 向量的确切顺序
2)我可能需要也可能不需要将所有坐标值偏移从 0 的负 X/Y/Z 距离以去除负数
但我可以从这里去哪里?
非常感谢帮助。
解决该问题的一种方法是为图中的每个顶点指定一个id
,然后通过 id 引用相邻顶点。
例子
using VertexId = size_t;
class Hex {
std::vector<VertexId>neighbours;
public:
Hex(int x, int y, int z);
};
class VertexStorage {
std::unordered_map<VertexId, Hex> _id_to_hex;
std::unordered_map<Hex, VertexId> _hex_to_id;
public:
// check if hex is in storage, return id
// if not, assign new id an push tostorage
// id could be increasing counter
VertexId getId(const Hex &hex);
Hex getHex(VertexId id);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.