Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way the find the Vertices of a Cube

Nearly every OpenGL tutorial lets you implement drawing a cube. Therefore the vertices of the cube are needed. In the example code I saw a long list defining every vertex. But I would like to compute the vertices of a cube rather that using a overlong list of precomputed coordinates.

A cube is made of eight vertices and twelve triangles. Vertices are defined by x, y, and z. Triangles are defined each by the indexes of three vertices.

Is there an elegant way to compute the vertices and the element indexes of a cube?

like image 462
danijar Avatar asked Dec 19 '12 13:12

danijar


People also ask

How do you find the vertices of a cube?

Use this equation to find the vertices from the number of faces and edges as follows: Add 2 to the number of edges and subtract the number of faces. For example, a cube has 12 edges. Add 2 to get 14, minus the number of faces, 6, to get 8, which is the number of vertices.

How does a cube have 12 edges?

Three edges join at each corner, called a vertex. Among the five platonic geometrical solids, only the cube is a hexahedron. It has 12 edges because all square faces are identical, forming a total number of 12 edges of the same length. A cube has vertices that are eight in number.


1 Answers

I solved this problem with this piece code (C#):

public CubeShape(Coord3 startPos, int size) {
    int l = size / 2;
    verts = new Coord3[8];
    for (int i = 0; i < 8; i++) {
        verts[i] = new Coord3(
            (i & 4) != 0 ? l : -l,
            (i & 2) != 0 ? l : -l,
            (i & 1) != 0 ? l : -l) + startPos;
    }

    tris = new Tris[12];
    int vertCount = 0;
    void AddVert(int one, int two, int three) =>
        tris[vertCount++] = new Tris(verts[one], verts[two], verts[three]);
        
    for (int i = 0; i < 3; i++) {
        int v1 = 1 << i;
        int v2 = v1 == 4 ? 1 : v1 << 1;
        AddVert(0, v1, v2);
        AddVert(v1 + v2, v2, v1);
        AddVert(7, 7 - v2, 7 - v1);
        AddVert(7 - (v1 + v2), 7 - v1, 7 - v2);
    }
}

If you want to understand more of what is going on, you can check out the github page I wrote that explains it.

like image 91
Catonif Avatar answered Oct 31 '22 08:10

Catonif