-
Notifications
You must be signed in to change notification settings - Fork 9
/
objloader.py
executable file
·104 lines (91 loc) · 3.22 KB
/
objloader.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
class MeshData(object):
def __init__(self, **kwargs):
self.name = kwargs.get("name")
self.vertex_format = [
(b'v_pos', 3, 'float'),
(b'v_normal', 3, 'float'),
(b'v_tc0', 2, 'float')]
self.vertices = []
self.indices = []
class ObjFile:
def finish_object(self):
if self._current_object is None:
return
mesh = MeshData()
idx = 0
for f in self.faces:
verts = f[0]
norms = f[1]
tcs = f[2]
n_verts = len(verts)
for i in range(n_verts):
# get normal components
n = (0.0, 0.0, 0.0)
if norms[i] != -1:
n = self.normals[norms[i] - 1]
# get texture coordinate components
t = (0.0, 0.0)
if tcs[i] != -1:
t = self.texcoords[tcs[i] - 1]
# get vertex components
v = self.vertices[verts[i] - 1]
data = [v[0], v[1], v[2], n[0], n[1], n[2], t[0], t[1]]
mesh.vertices.extend(data)
if n_verts == 3:
conn = [idx, idx + 1, idx + 2]
elif n_verts == 4:
conn = [idx, idx + 1, idx + 2, idx, idx + 2, idx + 3]
else:
raise ValueError
mesh.indices.extend(conn)
idx += n_verts
self.objects[self._current_object] = mesh
self.faces = []
def __init__(self, filename, swapyz=False):
self.objects = {}
self.vertices = []
self.normals = []
self.texcoords = []
self.faces = []
self._current_object = None
material = None
for line in open(filename, "r"):
if line.startswith('#'):
continue
if line.startswith('s'):
continue
values = line.split()
if not values:
continue
if values[0] == 'o':
self.finish_object()
self._current_object = values[1]
if values[0] == 'v':
v = list(map(float, values[1:4]))
if swapyz:
v = v[0], v[2], v[1]
self.vertices.append(v)
elif values[0] == 'vn':
v = list(map(float, values[1:4]))
if swapyz:
v = v[0], v[2], v[1]
self.normals.append(v)
elif values[0] == 'vt':
self.texcoords.append(map(float, values[1:3]))
elif values[0] == 'f':
face = []
texcoords = []
norms = []
for v in values[1:]:
w = v.split('/')
face.append(int(w[0]))
if len(w) >= 2 and len(w[1]) > 0:
texcoords.append(int(w[1]))
else:
texcoords.append(-1)
if len(w) >= 3 and len(w[2]) > 0:
norms.append(int(w[2]))
else:
norms.append(-1)
self.faces.append((face, norms, texcoords, material))
self.finish_object()