Transform a mesh of quads and triangles into a mesh composed of only triangles

Viewed 795

I do not know how to explain my problem well comprehensively. So I'll show you an example ...

I have this array indicating the vertices indices for each quad or triangle:

>>> faces
array([[0, 1, 2, 3],
       [4, 7, 6, 5],
       [0, 4, 1, 0],
       [1, 5, 6, 2],
       [2, 6, 7, 3],
       [4, 0, 3, 7],
       [1, 4, 5, 0]])

Triangles are the elements that end with 0

I want to make a transformation like this:

>>> faces
array([[0, 1, 2, 3],  #->[[0, 1, 2], [0, 2, 3],
       [4, 7, 6, 5],  #-> [4, 7, 6], [4, 6, 5],
       [0, 4, 1, 0],  #-> [0, 4, 1],
       [1, 5, 6, 2],  #-> [1, 5, 6], [1, 6, 2],
       [2, 6, 7, 3],  #-> [2, 6, 7], [2, 7, 3],
       [4, 0, 3, 7],  #-> [4, 0, 3], [4, 3, 7],
       [1, 4, 5, 0]]) #-> [1, 4, 5]]

So how can I make this transformation efficiently?

I did a function that solves it differently. Place the tirangles obtained by the quads at the end of the array.

def v_raw_to_tris(tessfaces):
    len_tessfaces = len(tessfaces)
    quad_indices = tessfaces[:, 3].nonzero()[0]
    t3 = np.empty(((len_tessfaces + len(quad_indices)), 3), 'i4')

    t3[:len_tessfaces] = tessfaces[:, :3]
    t3[len_tessfaces:] = tessfaces[quad_indices][:, (0, 2, 3)]

    return t3

But I don't want the resulting triangles to be at the end of the array. And yes in front of the original quads

3 Answers

Another simpler alternative is

import numpy as np

def quad2tri(mesh):
    if mesh.shape[1] != 4:
        raise ValueError("mesh is not quadrilateral.")
    reduced_mesh = np.zeros([2*mesh.shape[0], 3])
    reduced_mesh[::2] = mesh[:,[0,1,2]]
    reduced_mesh[1::2] = mesh[:,[0,2,3]]
    return reduced_mesh

mesh = np.array([[0, 1, 2, 3],
              [4, 7, 6, 5],
              [0, 4, 1, 0],
              [1, 5, 6, 2],
              [2, 6, 7, 3],
              [4, 0, 3, 7],
              [1, 4, 5, 0]])

print(quad2tri(mesh))

Outputs

[[0. 1. 2.]
 [0. 2. 3.]
 [4. 7. 6.]
 [4. 6. 5.]
 [0. 4. 1.]
 [0. 1. 0.]
 [1. 5. 6.]
 [1. 6. 2.]
 [2. 6. 7.]
 [2. 7. 3.]
 [4. 0. 3.]
 [4. 3. 7.]
 [1. 4. 5.]
 [1. 5. 0.]]
Related