Warm tip: This article is reproduced from stackoverflow.com, please click
python python-3.x

I have 8 vertices of a box on a 3D terrain, and i need to seperate the box to a few smaller ones

发布于 2020-03-27 10:27:56

For this problem, I got the 8 vertices of a box that i need to shrink, with a given size that is an integer which I need to shrink every side with. For example, if the size of the box I need to shrink is 8*8*8 and the shrinking size is 2, I need to return a list of all the vertices of the 4*4*4 boxes that fill the big box in a 3D coordinate system.

I thought about having a for loop that runs in range of the size of the box, but than I thought if I want to eventually seperate the box into a lot more boxes that are smaller and I want to fill the big box i would have to write an amount of code that I wouldn't be able to write. How to get this list of vertices without writing this much code?

Questioner
Jhonathan Mizrahi
Viewed
14
B. M. 2019-07-03 23:13

A solution using numpy, which allows easy bloc manipulation.

First I choose to represent a cube with an origin and three vectors : the unit cube is represented with orig=np.array([0,0,0]) and vects=np.array([[1,0,0],[0,1,0],[0,0,1]]).

Now a numpy function to generate the eight vertices:

import numpy as np

def cube(origin,edges):
    for e in edges:
        origin = np.vstack((origin,origin+e))
    return origin


cube(orig,vects)

array([[0, 0, 0],
       [1, 0, 0],
       [0, 1, 0],
       [1, 1, 0],
       [0, 0, 1],
       [1, 0, 1],
       [0, 1, 1],
       [1, 1, 1]])

Then an other to span minicubes in 3D :

def split(origin,edges,k):
    minicube=cube(origin,edges/k)
    for e in edges/k:
        minicube =np.vstack([minicube + i*e for i in range(k) ])
    return minicube.reshape(k**3,8,3) 


split (orig,vects,2)

array([[[ 0. ,  0. ,  0. ],
        [ 0.5,  0. ,  0. ],
        [ 0. ,  0.5,  0. ],
        [ 0.5,  0.5,  0. ],
        [ 0. ,  0. ,  0.5],
        [ 0.5,  0. ,  0.5],
        [ 0. ,  0.5,  0.5],
        [ 0.5,  0.5,  0.5]],
   ...

       [[ 0.5,  0.5,  0.5],
        [ 1. ,  0.5,  0.5],
        [ 0.5,  1. ,  0.5],
        [ 1. ,  1. ,  0.5],
        [ 0.5,  0.5,  1. ],
        [ 1. ,  0.5,  1. ],
        [ 0.5,  1. ,  1. ],
        [ 1. ,  1. ,  1. ]]])