-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobj_parser3.py
263 lines (212 loc) · 10 KB
/
obj_parser3.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import sys,os,string,traceback,pprint
from threading import Thread
'''
obj_parser.py has two arguments: the obj file containing the geometry and the mtl file containing the materials (optional)
In the Wavefront OBJ format, the indices are shared among objects.
'''
MATERIALS = {} #dictionary for materials
OBJECTS = {}
FILE = ''
def createWebGLFile():
mf = open('manifest.txt','w')
mf.write('original OBJ file: ' + FILE +'\n')
print('\n=== WebGL Output ===')
partNumber = 1
nor = OBJECTS['normals']
for obj in OBJECTS:
if obj == 'normals':
continue
ver = OBJECTS[obj]['vertices']
allIndicesForObject = []
for grp in OBJECTS[obj]['group']: # The idea here is to get the minimum index per object
allIndicesForObject += OBJECTS[obj]['group'][grp]['indices'] # so the indices of every group belonging to the same object
if len(allIndicesForObject) == 0:
print('Warning: the object ' + obj + ' will not generate a JSON file as it has no groups')
continue
minIndex = min(allIndicesForObject) # can be reindexed (starting on zero per group) for WebGL
for grp in OBJECTS[obj]['group']:
ind = OBJECTS[obj]['group'][grp]['indices']
normals_idx = OBJECTS[obj]['group'][grp]['normals_idx']
numIndices = len(ind)
numVertices = len(ver)
numIndNormals = len(normals_idx)
print('Writing file part'+ str(partNumber)+'.json > [ alias: '+grp+' vertices:' + str(numVertices/3) + ', indices: ' + str(numIndices) +']')
mf.write('part'+ str(partNumber)+'.json > alias: '+grp+'\n')
f = open('part'+str(partNumber)+'.json','w')
partNumber +=1
f.write('{\n')
f.write(' "alias" : "'+grp+'",\n') # ALIAS
f.write(' "vertices" : [') # VERTICES
for v in ver[0:numVertices-1]:
f.write(str(v)+',')
f.write(str(ver[numVertices-1])+'],\n')
f.write(' "indices" : [') # INDICES
for i in ind[0:numIndices-1]:
f.write(str(i-minIndex)+',')
f.write(str(ind[numIndices-1]-minIndex)+'],\n')
#f.write(' "normals" : [')
#for j in normals_idx[0:numIndNormals-1]:
# jk = 3 * (j-1)
# f.write(str(nor[jk])+','+str(nor[jk+1])+','+str(nor[jk+2])+',')
#jk = 3 * (normals_idx[numIndNormals-1]-1)
#f.write(str(nor[jk])+','+str(nor[jk+1])+','+str(nor[jk+2])+'],\n')
useMat = OBJECTS[obj]['group'][grp]['material'] # MATERIALS
#print ' group ' +grp+' uses mat = ' + useMat
if useMat == '(null)' or len(useMat) == 0:
print('warning: the group '+grp+' does not have materials')
continue
mat = MATERIALS[useMat]
numKeys = len(mat)
currKey = 1;
for key in mat:
f.write(' "'+key+'" : ')
if type(mat[key]) is float:
f.write("%.5f" % mat[key])
elif type(mat[key]) is int:
f.write(str(mat[key]))
else:
numNum = len(mat[key])
currNum = 1;
f.write('[')
for num in mat[key]:
s = "%.5f" % num
f.write(s)
if currNum < numNum:
f.write(',')
currNum +=1
f.write(']')
if (currKey < numKeys):
f.write(',\n')
else:
f.write('\n')
currKey+=1
f.write('}')
f.close()
mf.close();
def parseGeometry(file, hasMaterials):
print('\n=== Geometry ===' )
LOC_NOWHERE = 0
LOC_OBJECT = 1
LOC_GROUP = 2
location = LOC_NOWHERE
vertices = []
indices = []
normals = []
normals_idx = []
scalars = []
material = {}
nLine = 0
OBJECT_NAME = ''
GROUP_NAME = ''
MATERIAL_NAME = ''
OBJECTS['normals'] = []
for line in open(file, 'r').readlines():
nLine = nLine + 1
try:
if line.startswith('usemtl') and hasMaterials: #there is a material definition file associated .mtl (second argument on cmd line)
words = line.split()
if (len(words) == 2):
MATERIAL_NAME = words[1]
else:
MATERIAL_NAME = 'undefined'
OBJECTS[OBJECT_NAME]['group'][GROUP_NAME]['material'] = MATERIAL_NAME
print('\tMaterial: '+MATERIAL_NAME)
elif line.startswith('o '): #Processing an new object
OBJECT_NAME = line.split()[1]
location = LOC_OBJECT
OBJECTS[OBJECT_NAME] = {}
OBJECTS[OBJECT_NAME]['vertices'] = []
OBJECTS[OBJECT_NAME]['group'] = {}
vertices = OBJECTS[OBJECT_NAME]['vertices'] #aliasing
normals = OBJECTS['normals'] #aliasing
print('\nObject: ' + OBJECT_NAME)
elif line.startswith('g '): #Processing a new group
GROUP_NAME = line.split()[1]
location = LOC_GROUP
OBJECTS[OBJECT_NAME]['group'][GROUP_NAME] = {}
OBJECTS[OBJECT_NAME]['group'][GROUP_NAME]['indices'] = []
OBJECTS[OBJECT_NAME]['group'][GROUP_NAME]['normals_idx'] = []
indices = OBJECTS[OBJECT_NAME]['group'][GROUP_NAME]['indices'] #aliasing so we can store here
normals_idx = OBJECTS[OBJECT_NAME]['group'][GROUP_NAME]['normals_idx'] #aliasing so we can store here
print('\tGroup: ' + GROUP_NAME)
elif location == LOC_OBJECT: #Add vertices to current object
if line.startswith('v '):
for v in line[1:len(line)].split():
vertices.append(float(v))
if line.startswith('vn '):
for vn in line[3:len(line)].split():
normals.append(float(vn))
elif location == LOC_GROUP: #Add indices to current group
if line.startswith('f '):
f = line[1:len(line)].split()
pl = len(f)
print("########")
print(f[0],f[1],f[2])
print(f[0][0:f[0].find('/')])
print(f[1][0:f[1].find('/')])
print(f[2][0:f[2].find('/')])
print("########")
if (pl == 3): #ideal case for WebGL: all faces are triangles
fa = int(f[0]); #[0:f[0].find('/')]);
fb = int(f[1]);#[0:f[1].find('/')]);
fc = int(f[2]);#[0:f[2].find('/')]);
indices.append(fa)
indices.append(fb)
indices.append(fc)
na = int(f[0][f[0].rfind('/')+1:len(f[0])]);
nb = int(f[1][f[1].rfind('/')+1:len(f[1])]);
nc = int(f[2][f[2].rfind('/')+1:len(f[2])]);
normals_idx.append(na)
normals_idx.append(nb)
normals_idx.append(nc)
else:
print('faces need to be triangular')
raise
except:
print('ERROR while processing line: '+str(nLine))
print(line)
raise
#pp = pprint.PrettyPrinter(indent=2, width=300)
#pp.pprint(OBJECTS)
def parseMaterials(file):
if (len(file) == 0):
return False
print('\n=== Materials ===')
linenumber = 0;
currentMaterial = ''
for line in open(file, 'r').readlines():
linenumber = linenumber + 1
try:
if line.startswith('newmtl'):
words = line.split()
if (len(words) == 2):
currentMaterial = words[1]
else:
currentMaterial = 'undefined'
print('Material: ' + currentMaterial )
MATERIALS[currentMaterial] = {}
elif line.startswith('illum'):
words = line.split()
MATERIALS[currentMaterial][words[0]] = int(words[1])
elif line.startswith('Ns') or line.startswith('Ni') or line.startswith('d'):
words = line.split()
MATERIALS[currentMaterial][words[0]] = float(words[1])
elif line.startswith('Ka') or line.startswith('Kd') or line.startswith('Ks'):
words = line.split()
MATERIALS[currentMaterial][words[0]] = [float(words[1]), float(words[2]), float(words[3])]
continue
except:
print('Error while processing line '+str(linenumber))
print(line)
raise
return True
if __name__ == '__main__':
if (len(sys.argv) == 1):
print('ERROR -- Use like this: obj_parser.py objfile.obj mtlfile.mtl')
sys.exit(0)
FILE = sys.argv[1]
hasMaterials = parseMaterials(sys.argv[2])
parseGeometry(FILE, hasMaterials)
dir = os.path.dirname(FILE)
#os.chdir(dir)
createWebGLFile()