我有一些值是多维数组的偏移量,看起来像这样:
static const int TILE_SIZE = 32;
int Offset2D = (y * TILE_SIZE) + (x * TILE_SIZE);
int Offset3D = (y * TILE_SIZE) + (x * TILE_SIZE) + (z * TILE_SIZE);
Run Code Online (Sandbox Code Playgroud)
现在我想要做的是将偏移量转换为x,y,z对,如下所示:
void ConvertBack(int offset,int size,int& x,int& y,int& z)
{
//What's wrong with this code ?
x = offset / size;
y = offset % size;
z = ??; //How to get Z?
}
Run Code Online (Sandbox Code Playgroud)
要么
//Get back offsets from any dimension ?
void ConvertBackComplex(unsigned int offset,int size,int* vector,int len)
{
for (int i = 0;i < len;i++)
{
vector[i] = offset ?... ?
}
}
Run Code Online (Sandbox Code Playgroud)
......到目前为止,我的所有尝试都失败了......所以我真的很欢迎任何帮助!...
首先,我认为你的索引系统有点偏.你有不同的x,y和z值排列方式可以给出相同的偏移量.所以,首先,假设TILE_SIZE是数组的多少个单元存储给定点的数据:
myArray = new arr[xSize*ySize*zSize*TILESIZE]
int offset2D = (x*ySize*zSize + y*zSize)*TILE_SIZE;
int offset3D = (x*ySize*zSize + y*zSize + z)*TILE_SIZE;
Run Code Online (Sandbox Code Playgroud)
要从偏移量中获取x,y,z,只需执行以下操作:
temp = offset/TILE_SIZE;
x = temp/(ySize*zSize);
y = (temp%(ySize*zSize))/zSize;
z = (temp%(ySize*zSize))%zSize;
Run Code Online (Sandbox Code Playgroud)
对于多个维度:
temp = offset/TILE_SIZE;
sizeProduct = 1;
for(int k=1; k<numDims; ++k)
{
sizeProduct*=size[k];
}
for(int i=0; i<numDims; ++i)
{
vector[i]=temp/sizeProduct;
temp = temp % sizeProduct;
if((i+1)<numDims)
{
sizeProduct/=sizes[i+1];
}
}
Run Code Online (Sandbox Code Playgroud)
要计算多维的数组大小:
int arraySize = TILE_SIZE;
for(int i=0; i<numDims; ++i)
{
arraySize*=sizes[i];
}
Run Code Online (Sandbox Code Playgroud)
要计算多维度的数组索引(假设向量是您的坐标数组):
int index =0;
sizeProduct = 1;
for(int k=1; k<numDims; ++k)
{
sizeProduct*=size[k];
}
for(int i=0; i<numDims; ++i)
{
index+=sizeProduct*vector[i];
if((i+1)<numDims)
{
sizeProduct/=sizes[i+1];
}
}
index*=TILE_SIZE;
Run Code Online (Sandbox Code Playgroud)