简体   繁体   中英

Algorithm for 3D grid

I'm having a hard time creating an algorithm that calculates the position of a given number of vertices so that they will be spread to match the number of divisions I set a 3D grid (a cube, really) to be.

Here are more details:

I need to create vertices for a 3D Grid (cube) that will have: 3 rows in the X axis, 4 rows in the Y axis and 2 rows in the Z axis.

Given each vertex = (x, y, z), and the total number of vertices 3 * 4 * 2 = 24, what values should I replace (x, y, z) with for each of the 24 vertices?

Initially I was thinking something like:

vertices = [(0,0,0),(0,0,0),...] # fill the list with 24 vertices

and then iterate:

for i in range(vertices.length):
 for x in range(3):
  for y in range(4):
   for z in range(2):
    vertices[i] = (x,y,z)
return vertices

...something along those lines...

I haven't been able to figure this out yet. Would anyone help me, please?

Here is brief code that returns a list of vertices that matches the apparent intent of your code.

from itertools import product
mylist = list(product(range(3), range(4), range(2)))

Printing mylist in iPython results in

[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (0, 2, 0),
 (0, 2, 1),
 (0, 3, 0),
 (0, 3, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1),
 (1, 2, 0),
 (1, 2, 1),
 (1, 3, 0),
 (1, 3, 1),
 (2, 0, 0),
 (2, 0, 1),
 (2, 1, 0),
 (2, 1, 1),
 (2, 2, 0),
 (2, 2, 1),
 (2, 3, 0),
 (2, 3, 1)]

If you don't understand how product works, check the documentation .

your solution seems to be almost correct, you just need to eliminate the outer loop over i and append to the vertices list directly:

def grid():
    vertices = []
    for x in range(3):
        for y in range(4):
            for z in range(2):
                vertices.append((x, y, z))
    return vertices

print(grid())

or preinitialize the list and assign individual elements:

def grid():
    vertices = [None]*3*4*2
    i = 0
    for x in range(3):
        for y in range(4):
            for z in range(2):
                vertices[i] = (x, y, z)
                i += 1

    return vertices

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM