-
Notifications
You must be signed in to change notification settings - Fork 43
/
utils_3d.py
76 lines (60 loc) · 2.05 KB
/
utils_3d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Contains utilities common to 3d meshing methods"""
import math
class V3:
"""A vector in 3D space"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def normalize(self):
d = math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z)
return V3(self.x / d, self.y / d, self.z / d)
class Tri:
"""A 3d triangle"""
def __init__(self, v1, v2, v3):
self.v1 = v1
self.v2 = v2
self.v3 = v3
def map(self, f):
return Tri(f(self.v1), f(self.v2), f(self.v3))
class Quad:
"""A 3d quadrilateral (polygon with 4 vertices)"""
def __init__(self, v1, v2, v3, v4):
self.v1 = v1
self.v2 = v2
self.v3 = v3
self.v4 = v4
def map(self, f):
return Quad(f(self.v1), f(self.v2), f(self.v3), f(self.v4))
def swap(self, swap=True):
if swap:
return Quad(self.v4, self.v3, self.v2, self.v1)
else:
return Quad(self.v1, self.v2, self.v3, self.v4)
class Mesh:
"""A collection of vertices, and faces between those vertices."""
def __init__(self, verts=None, faces=None):
self.verts = verts or []
self.faces = faces or []
def extend(self, other):
l = len(self.verts)
f = lambda v: v + l
self.verts.extend(other.verts)
self.faces.extend(face.map(f) for face in other.faces)
def __add__(self, other):
r = Mesh()
r.extend(self)
r.extend(other)
return r
def translate(self, offset):
new_verts = [V3(v.x + offset.x, v.y + offset.y, v.z + offset.z) for v in self.verts]
return Mesh(new_verts, self.faces)
def make_obj(f, mesh):
"""Crude export to Wavefront mesh format"""
for v in mesh.verts:
f.write("v {} {} {}\n".format(v.x, v.y, v.z))
for face in mesh.faces:
if isinstance(face, Quad):
f.write("f {} {} {} {}\n".format(face.v1, face.v2, face.v3, face.v4))
if isinstance(face, Tri):
f.write("f {} {} {}\n".format(face.v1, face.v2, face.v3))