I have 8 vertices of a cube that are simply indexes. I want to get every vertex's respective point of where it would be in a normalized cube. In the following diagram, assume that +x is to the right, +y is up, and +z is coming out of the screen. (vertices 2, 3, 6, and 7 are in front, if it's hard to see).

Polygonise

(ignore the edge indexes)

Here's what I have:

for (int v = 0; v < 8; v++) {
    float x, y, z;

    if(v < 4)                                    y = -1;
    else                                         y = +1;
    if(v == 1 || v == 2 || v == 5 || v == 6)     x = +1;
    else                                         x = -1;
    if(v == 2 || v == 3 || v == 6 || v == 7)     z = +1;
    else                                         z = -1;
}

Is there a more logical way to do this, without so many logical ORs?

有帮助吗?

解决方案

You could use lookup tables. LUTs tend to be quite efficient, but some people find them counter-intuitive.

for (int v = 0; v < 8; v++) {
    int[] lutX = new int[] {-1, -1, -1, -1, 1, 1, 1, 1};
    int[] lutY = new int[] {-1, -1, -1, -1, 1, 1, 1, 1};
    int[] lutZ = new int[] {-1, -1, 1, 1, -1, -1, 1, 1};
    float x = lutX[v];
    float y = lutY[v];
    float z = lutZ[v];
}

Usually you should declare them statically outside your function.

You can deduce the LUTs from your OR-based logic by a logic like this:

If for v==0, the OR-logic adds 1 to X, set lutX[0] to 1.
Else set lutX[0] to -1

其他提示

How about this one liner:

float x = 2*((v/2)%2)-1, y = 2*(v/4)-1, z = 2*(v%2)-1;

Test code:

static void Main(string[] args)
{
    Debug.Print("{0,3} {1,3},{2,3},{3,3}", "v", "x", "y", "z");
    for(int v=0; v<8; v++)
    {
        float x=2*((v/2)%2)-1, y=2*(v/4)-1, z=2*(v%2)-1;

        Debug.Print("{0,3} {1,3},{2,3},{3,3}", v, x, y, z);
    }
}

result:

v   x,  y,  z
0  -1, -1, -1
1  -1, -1,  1
2   1, -1, -1
3   1, -1,  1
4  -1,  1, -1
5  -1,  1,  1
6   1,  1, -1
7   1,  1,  1
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top