]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Fix line exporting
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import math
2 import mathutils
3
4 def make_edge_key(i1, i2):
5         return (min(i1, i2), max(i1, i2))
6
7 class Edge:
8         def __init__(self, me):
9                 if me.__class__==Edge:
10                         self._medge = me._medge
11                         self.vertices = me.vertices[:]
12                         self.smooth = me.smooth
13                 else:
14                         self._medge = me
15                         self.smooth = False
16                 self.faces = []
17
18         def __getattr__(self, attr):
19                 return getattr(self._medge, attr)
20
21         def check_smooth(self, limit):
22                 if len(self.faces)!=2:
23                         return
24
25                 d = self.faces[0].normal.dot(self.faces[1].normal)
26                 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
27
28         def other_face(self, f):
29                 if f.index==self.faces[0].index:
30                         if len(self.faces)>=2:
31                                 return self.faces[1]
32                         else:
33                                 return None
34                 else:
35                         return self.faces[0]
36
37         def other_vertex(self, v):
38                 if v.index==self.vertices[0].index:
39                         return self.vertices[1]
40                 else:
41                         return self.vertices[0]
42
43
44 class Vertex:
45         def __init__(self, mv):
46                 if mv.__class__==Vertex:
47                         self._mvert = mv._mvert
48                         self.normal = mv.normal
49                         self.uvs = mv.uvs[:]
50                         self.tan = mv.tan
51                         self.bino = mv.bino
52                         self.group_weight_scale = mv.group_weight_scale
53                 else:
54                         self._mvert = mv
55                         self.uvs = []
56                         self.tan = None
57                         self.bino = None
58                         self.group_weight_scale = 1
59                 self.flag = False
60                 self.faces = []
61
62         def __getattr__(self, attr):
63                 return getattr(self._mvert, attr)
64
65         def __cmp__(self, other):
66                 if other is None:
67                         return 1
68                 return cmp(self.index, other.index)
69
70
71 class Face:
72         def __init__(self, mf):
73                 self._mface = mf
74                 self.edges = []
75                 self.vertices = mf.vertices[:]
76                 self.uvs = []
77                 self.flag = False
78
79         def __getattr__(self, attr):
80                 return getattr(self._mface, attr)
81
82         def __cmp__(self, other):
83                 if other is None:
84                         return 1
85                 return cmp(self.index, other.index)
86
87         def pivot_vertices(self, *vt):
88                 flags = [(v in vt) for v in self.vertices]
89                 l = len(self.vertices)
90                 for i in range(l):
91                         if flags[i] and not flags[(i+l-1)%l]:
92                                 return self.vertices[i:]+self.vertices[:i]
93
94         def get_edge(self, v1, v2):     
95                 key = make_edge_key(v1.index, v2.index)
96                 for e in self.edges:
97                         if e.key==key:
98                                 return e
99                 raise KeyError("No edge %s"%(key,))
100
101         def get_neighbors(self):
102                 neighbors = [e.other_face(self) for e in self.edges]
103                 return list(filter(bool, neighbors))
104
105
106 class Line:
107         def __init__(self, e):
108                 self.edge = e
109                 self.vertices = e.vertices[:]
110                 self.flag = False
111
112
113 class UvLayer:
114         def __init__(self, l, t):
115                 self._layer = l
116                 self.uvtex = t
117                 self.name = self.uvtex.name
118                 self.unit = None
119                 self.hidden = False
120                 dot = self.name.find('.')
121                 if dot>=0:
122                         ext = self.name[dot:]
123                         if ext.startswith(".unit") and ext[5:].isdigit():
124                                 self.unit = int(ext[5:])
125                         elif ext==".hidden":
126                                 self.hidden = True
127
128         def __getattr__(self, attr):
129                 return getattr(self._layer, attr)
130
131 class FakeUvLayer:
132         def __init__(self, n):
133                 self.uvtex = None
134                 self.name = n
135                 self.unit = None
136                 self.hidden = False
137
138 class Mesh:
139         def __init__(self, m):
140                 self._mesh = m
141
142                 self.vertices = [Vertex(v) for v in self.vertices]
143                 self.faces = [Face(f) for f in self.polygons]
144
145                 self.materials = self.materials[:]
146
147                 self.uv_layers = [UvLayer(self.uv_layers[i], self.uv_textures[i]) for i in range(len(self.uv_layers))]
148                 self.assign_texture_units()
149
150                 for f in self.faces:
151                         f.vertices = [self.vertices[i] for i in f.vertices]
152                         for v in f.vertices:
153                                 v.faces.append(f)
154                         for u in self.uv_layers:
155                                 f.uvs.append([u.data[f.loop_indices[i]].uv for i in range(len(f.vertices))])
156
157                 self.edges = dict([(e.key, Edge(e)) for e in self.edges])
158                 for f in self.faces:
159                         for k in f.edge_keys:
160                                 e = self.edges[k]
161                                 e.faces.append(self.faces[f.index])
162                                 f.edges.append(e)
163
164                 self.lines = [Line(e) for e in self.edges.values() if not e.faces]
165                 for l in self.lines:
166                         l.vertices = [self.vertices[i] for i in l.vertices]
167
168                 if self.use_auto_smooth:
169                         smooth_limit = math.cos(self.auto_smooth_angle)
170                 else:
171                         smooth_limit = -1
172
173                 for e in self.edges.values():
174                         e.vertices = [self.vertices[i] for i in e.vertices]
175                         e.check_smooth(smooth_limit)
176
177         def __getattr__(self, attr):
178                 return getattr(self._mesh, attr)
179
180         def splice(self, other):
181                 material_map = []
182                 for m in other.materials:
183                         if m in self.materials:
184                                 material_map.append(self.materials.index(m))
185                         else:
186                                 material_map.append(len(self.materials))
187                                 self.materials.append(m)
188
189                 offset = len(self.vertices)
190                 for v in other.vertices:
191                         v.index += offset
192                         self.vertices.append(v)
193
194                 offset = len(self.faces)
195                 for f in other.faces:
196                         f.index += offset
197                         if other.materials:
198                                 f.material_index = material_map[f.material_index]
199                         self.faces.append(f)
200
201                 for e in other.edges.values():
202                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
203                         self.edges[e.key] = e
204
205                 self.lines += other.lines
206
207         def flatten_faces(self):
208                 for f in self.faces:
209                         f.use_smooth = False
210
211                 for e in self.edges.values():
212                         e.check_smooth(1)
213
214         def assign_texture_units(self):
215                 # Assign texture units for any non-hidden UV layers that lack one
216                 units = [u.unit for u in self.uv_layers if u.unit is not None]
217                 if units:
218                         free_unit = max(units)+1
219                 else:
220                         free_unit = 0
221                 for u in self.uv_layers:
222                         if u.unit is None:
223                                 if not u.hidden:
224                                         u.unit = free_unit
225                                         free_unit += 1
226
227         def generate_material_uv(self):
228                 self.uv_layers.append(FakeUvLayer("material_tex"))
229                 self.assign_texture_units()
230                 for f in self.faces:
231                         f.uvs.append([((f.material_index+0.5)/len(self.materials), 0.5)]*len(f.vertices))
232
233         def split_vertices(self, find_group_func, progress, *args):
234                 groups = []
235                 for i in range(len(self.vertices)):
236                         v = self.vertices[i]
237                         for f in v.faces:
238                                 f.flag = False
239
240                         vg = []
241                         for f in v.faces:
242                                 if not f.flag:
243                                         vg.append(find_group_func(v, f, *args))
244
245                         groups.append(vg)
246
247                         if progress:
248                                 progress.set_progress(i*0.5/len(self.vertices))
249
250                 for i in range(len(self.vertices)):
251                         if len(groups[i])==1:
252                                 continue
253
254                         for g in groups[i][1:]:
255                                 v = Vertex(self.vertices[i])
256                                 v.index = len(self.vertices)
257                                 self.vertices.append(v)
258
259                                 v_edges = []
260                                 v_edge_keys = set()
261                                 for f in g:
262                                         for e in f.edges:
263                                                 if e.key in v_edge_keys or self.vertices[i] not in e.vertices:
264                                                         continue
265
266                                                 e_faces_in_g = [c for c in e.faces if c in g]
267                                                 boundary = len(e_faces_in_g)<len(e.faces)
268                                                 v_edges.append((e, boundary, e_faces_in_g))
269                                                 v_edge_keys.add(e.key)
270
271                                 for e, boundary, e_faces_in_g in v_edges:
272                                         if boundary:
273                                                 ne = Edge(e)
274                                                 for c in e_faces_in_g:
275                                                         e.faces.remove(c)
276                                                         c.edges[c.edges.index(e)] = ne
277                                                         ne.faces.append(c)
278                                                 e = ne
279                                         else:
280                                                 del self.edges[e.key]
281
282                                         e.vertices[e.vertices.index(self.vertices[i])] = v
283
284                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
285                                         self.edges[e.key] = e
286
287                                 for f in g:
288                                         self.vertices[i].faces.remove(f)
289                                         f.vertices[f.vertices.index(self.vertices[i])] = v
290                                         v.faces.append(f)
291
292                         if progress:
293                                 progress.set_progress(0.5+i*0.5/len(self.vertices))
294
295         def split_smooth(self, progress = None):
296                 self.split_vertices(self.find_smooth_group, progress)
297
298         def split_uv(self, index, progress = None):
299                 self.split_vertices(self.find_uv_group, progress, index)
300
301         def find_smooth_group(self, vertex, face):
302                 face.flag = True
303                 queue = [face]
304
305                 for f in queue:
306                         for e in f.edges:
307                                 other = e.other_face(f)
308                                 if other not in vertex.faces:
309                                         continue
310
311                                 if e.smooth:
312                                         if not other.flag:
313                                                 other.flag = True
314                                                 queue.append(other)
315
316                 return queue
317
318         def find_uv_group(self, vertex, face, index):
319                 uv = face.uvs[index][face.vertices.index(vertex)]
320                 face.flag = True
321                 group = [face]
322                 for f in vertex.faces:
323                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
324                                 f.flag = True
325                                 group.append(f)
326                 return group
327
328         def compute_normals(self):
329                 for v in self.vertices:
330                         if v.faces:
331                                 v.normal = mathutils.Vector()
332                                 for f in v.faces:
333                                         fv = f.pivot_vertices(v)
334                                         edge1 = fv[1].co-fv[0].co
335                                         edge2 = fv[-1].co-fv[0].co
336                                         if edge1.length and edge2.length:
337                                                 weight = 1
338                                                 if len(f.get_edge(fv[0], fv[1]).faces)==1:
339                                                         weight += 1
340                                                 if len(f.get_edge(fv[0], fv[-1]).faces)==1:
341                                                         weight += 1
342                                                 v.normal += f.normal*edge1.angle(edge2)*weight
343                                 if v.normal.length:
344                                         v.normal.normalize()
345                                 else:
346                                         v.normal = mathutils.Vector((0, 0, 1))
347                         else:
348                                 # XXX Should use edges to compute normal
349                                 v.normal = mathutils.Vector((0, 0, 1))
350
351         def compute_uv(self):
352                 for v in self.vertices:
353                         if v.faces:
354                                 f = v.faces[0]
355                                 i = f.vertices.index(v)
356                                 v.uvs = [u[i] for u in f.uvs]
357                         else:
358                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
359
360         def compute_tbn(self, index):
361                 if not self.uv_layers:
362                         return
363
364                 for v in self.vertices:
365                         v.tan = mathutils.Vector()
366                         v.bino = mathutils.Vector()
367                         for f in v.faces:
368                                 fv = f.pivot_vertices(v)
369                                 uv0 = fv[0].uvs[index]
370                                 uv1 = fv[1].uvs[index]
371                                 uv2 = fv[-1].uvs[index]
372                                 du1 = uv1[0]-uv0[0]
373                                 du2 = uv2[0]-uv0[0]
374                                 dv1 = uv1[1]-uv0[1]
375                                 dv2 = uv2[1]-uv0[1]
376                                 edge1 = fv[1].co-fv[0].co
377                                 edge2 = fv[-1].co-fv[0].co
378                                 div = (du1*dv2-du2*dv1)
379                                 if div:
380                                         mul = edge1.angle(edge2)/div
381                                         v.tan += (edge1*dv2-edge2*dv1)*mul
382                                         v.bino += (edge2*du1-edge1*du2)*mul
383
384                         if v.tan.length:
385                                 v.tan.normalize()
386                         if v.bino.length:
387                                 v.bino.normalize()
388
389         def sort_vertex_groups(self, max_groups):
390                 for v in self.vertices:
391                         if v.groups:
392                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)
393                                 v.group_weight_scale = 1.0/sum(g.weight for g in v.groups[:max_groups])
394
395         def create_strip(self, face, max_len):
396                 # Find an edge with another unused face next to it
397                 edge = None
398                 for e in face.edges:
399                         other = e.other_face(face)
400                         if other and not other.flag:
401                                 edge = e
402                                 break
403
404                 if not edge:
405                         return None
406
407                 # Add initial vertices so that we'll complete the edge on the first
408                 # iteration
409                 vertices = face.pivot_vertices(*edge.vertices)
410                 if len(vertices)==3:
411                         result = [vertices[-1], vertices[0]]
412                 else:
413                         result = [vertices[-2], vertices[-1]]
414
415                 while 1:
416                         face.flag = True
417
418                         vertices = face.pivot_vertices(*result[-2:])
419                         k = len(result)%2
420
421                         # Quads need special handling because the winding of every other
422                         # triangle in the strip is reversed
423                         if len(vertices)==4 and not k:
424                                 result.append(vertices[3])
425                         result.append(vertices[2])
426                         if len(vertices)==4 and k:
427                                 result.append(vertices[3])
428
429                         if len(result)>=max_len:
430                                 break
431
432                         # Hop over the last edge
433                         edge = face.get_edge(*result[-2:])
434                         face = edge.other_face(face)
435                         if not face or face.flag:
436                                 break
437
438                 return result