Skip to content

Instantly share code, notes, and snippets.

@johnfredcee
Created January 2, 2019 16:13
Show Gist options
  • Select an option

  • Save johnfredcee/c5592bf4d6c2a7d35b56463c4639e1aa to your computer and use it in GitHub Desktop.

Select an option

Save johnfredcee/c5592bf4d6c2a7d35b56463c4639e1aa to your computer and use it in GitHub Desktop.
Mesh representation - with edges.
# if you can't rely on euclid, what can you rely on?
import euclid
from euclid import Vector3
class Mesh:
def __init__(self, vertices=[], faces=[]):
"""Initialises a vertex with a list of faces. Vertex array is a list of Vector3. Face array is a list of 3 tuple indexes into vertex array."""
self.vertex_list = vertices
self.face_list = faces
def __len__(self):
"""Returns number of vertices in a mesh"""
return len(self.face_list) * 3
def vertices(self):
"""Iterate over the vertices in the mesh"""
for v in self.vertex_list:
yield v
def faces(self):
"""Iterate over the faces in the mesh"""
for face in self.face_list:
a, b, c = face
yield (self.vertex_list[a], self.vertex_list[b], self.vertex_list[c])
def edges(self):
"""Iterate over the edges in the faces of the mesh"""
for face in self.face_list:
e0 = [self.vertex_list[face[0]], self.vertex_list[face[1]]]
yield(tuple(e0))
e1 = [self.vertex_list[face[1]], self.vertex_list[face[2]]]
yield(tuple(e1))
e2 = [self.vertex_list[face[2]], self.vertex_list[face[0]]]
yield(tuple(e2))
def __str__(self):
"""Print a readable description of the mesh"""
result = "Mesh with {0} vertices and {1} faces\n".format(
len(self), len(self.face_list))
for face_index, face in enumerate(self.faces()):
result += "Face {0} :({1}, {2}, {3})\n".format(face_index,
face[0], face[1], face[2])
for edge_index, edge in enumerate(self.edges()):
a, b = edge[0], edge[1]
result += "Edge {0} of Face {1} :({2}, {3})\n".format(edge_index %
3, edge_index // 3, a, b)
return result
if __name__ == "__main__":
cube_mesh=Mesh(vertices=[
# face vertices
Vector3(-1.0, -1.0, -1.0),
Vector3(-1.0, 1.0, -1.0),
Vector3(1.0, 1.0, -1.0),
Vector3(1.0, -1.0, -1.0),
Vector3(-1.0, -1.0, 1.0),
Vector3(-1.0, 1.0, 1.0),
Vector3(1.0, 1.0, 1.0),
Vector3(1.0, -1.0, 1.0),
# edge vertices
Vector3(-1.0, -1.0, -1.0),
Vector3(-1.0, 1.0, -1.0),
Vector3(1.0, 1.0, -1.0),
Vector3(1.0, -1.0, -1.0),
Vector3(-1.0, -1.0, 1.0),
Vector3(-1.0, 1.0, 1.0),
Vector3(1.0, 1.0, 1.0),
Vector3(1.0, -1.0, 1.0)
],
faces=[
# Front face
(0, 1, 2),
(0, 2, 3),
# Back face
(4, 6, 5),
(4, 7, 6),
# Left face
(4, 5, 1),
(4, 1, 0),
# Right face
(3, 2, 6),
(3, 6, 7),
# Top face
(1, 5, 6),
(1, 6, 2),
# Bottom face
(4, 0, 3),
(4, 3, 7)
])
print(cube_mesh)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment