]> git.tdb.fi Git - libs/gl.git/blob - blender/io_mspgl/mesh.py
Rename some variable to be a bit clearer
[libs/gl.git] / blender / io_mspgl / mesh.py
1 import bpy
2 import math
3 import mathutils
4
5 def make_edge_key(i1, i2):
6         return (min(i1, i2), max(i1, i2))
7
8 class Edge:
9         def __init__(self, edge):
10                 if edge.__class__==Edge:
11                         self._edge = edge._edge
12                         self.vertices = edge.vertices[:]
13                         self.smooth = edge.smooth
14                 else:
15                         self._edge = edge
16                         self.smooth = False
17                 self.key = edge.key
18                 self.faces = []
19
20         def __getattr__(self, attr):
21                 return getattr(self._edge, attr)
22
23         def check_smooth(self, limit):
24                 if len(self.faces)!=2:
25                         return
26
27                 d = self.faces[0].normal.dot(self.faces[1].normal)
28                 self.smooth = ((d>limit and self.faces[0].use_smooth and self.faces[1].use_smooth) or d>0.99995)
29
30         def other_face(self, f):
31                 if f.index==self.faces[0].index:
32                         if len(self.faces)>=2:
33                                 return self.faces[1]
34                         else:
35                                 return None
36                 else:
37                         return self.faces[0]
38
39         def other_vertex(self, v):
40                 if v.index==self.vertices[0].index:
41                         return self.vertices[1]
42                 else:
43                         return self.vertices[0]
44
45
46 class Vertex:
47         def __init__(self, vertex):
48                 if vertex.__class__==Vertex:
49                         self._vertex = vertex._vertex
50                         self.uvs = vertex.uvs[:]
51                         self.tan = vertex.tan
52                         self.bino = vertex.bino
53                 else:
54                         self._vertex = vertex
55                         self.uvs = []
56                         self.tan = None
57                         self.bino = None
58                 self.index = vertex.index
59                 self.co = vertex.co
60                 self.normal = vertex.normal
61                 self.flag = False
62                 self.edges = []
63                 self.faces = []
64                 self.groups = vertex.groups[:]
65
66         def __getattr__(self, attr):
67                 return getattr(self._vertex, attr)
68
69         def __cmp__(self, other):
70                 if other is None:
71                         return 1
72                 return cmp(self.index, other.index)
73
74
75 class VertexGroup:
76         def __init__(self, group):
77                 self._group = group
78                 self.group = group.group
79                 self.weight = group.weight
80
81         def __getattr__(self, attr):
82                 return getattr(self._group, attr)
83
84
85 class Face:
86         def __init__(self, face):
87                 self._face = face
88                 self.index = face.index
89                 self.edges = []
90                 self.vertices = face.vertices[:]
91                 self.uvs = []
92                 self.flag = False
93
94         def __getattr__(self, attr):
95                 return getattr(self._face, attr)
96
97         def __cmp__(self, other):
98                 if other is None:
99                         return 1
100                 return cmp(self.index, other.index)
101
102         def pivot_vertex(self, v):
103                 n = self.vertices.index(v)
104                 return [(n+i)%len(self.vertices) for i in range(len(self.vertices))]
105
106         def pivot_vertices(self, *vt):
107                 flags = [(v in vt) for v in self.vertices]
108                 l = len(self.vertices)
109                 for i in range(l):
110                         if flags[i] and not flags[(i+l-1)%l]:
111                                 return self.vertices[i:]+self.vertices[:i]
112
113         def get_edge(self, v1, v2):     
114                 key = make_edge_key(v1.index, v2.index)
115                 for e in self.edges:
116                         if e.key==key:
117                                 return e
118                 raise KeyError("No edge %s"%(key,))
119
120         def other_edge(self, e, v):
121                 for d in self.edges:
122                         if d!=e and v in d.vertices:
123                                 return d
124
125         def get_neighbors(self):
126                 neighbors = [e.other_face(self) for e in self.edges]
127                 return list(filter(bool, neighbors))
128
129
130 class Line:
131         def __init__(self, e):
132                 self.edge = e
133                 self.vertices = e.vertices[:]
134                 self.flag = False
135
136
137 class UvLayer:
138         def __init__(self, arg):
139                 if type(arg)==str:
140                         self._layer = None
141                         self.name = arg
142                 else:
143                         self._layer = arg
144                         self.name = arg.name
145                         self.uvs = [d.uv for d in self.data]
146
147                 self.unit = None
148                 self.hidden = False
149
150                 dot = self.name.find('.')
151                 if dot>=0:
152                         ext = self.name[dot:]
153                         if ext.startswith(".unit") and ext[5:].isdigit():
154                                 self.unit = int(ext[5:])
155                         elif ext==".hidden":
156                                 self.hidden = True
157
158         def __getattr__(self, attr):
159                 return getattr(self._layer, attr)
160
161
162 class Mesh:
163         def __init__(self, mesh):
164                 self._mesh = mesh
165
166                 self.winding_test = mesh.winding_test
167                 self.tbn_vecs = mesh.tbn_vecs
168                 self.vertex_groups = mesh.vertex_groups
169
170                 self.vertices = [Vertex(v) for v in self.vertices]
171                 self.faces = [Face(f) for f in self.polygons]
172                 self.edges = [Edge(e) for e in self.edges]
173                 self.loops = self.loops[:]
174
175                 self.materials = self.materials[:]
176                 if self.use_uv=='NONE' or not self.uv_layers:
177                         self.uv_layers = []
178                 else:
179                         self.uv_layers = [UvLayer(u) for u in self.uv_layers]
180                         self.uv_layers = sorted([u for u in self.uv_layers if not u.hidden], key=(lambda u: (u.unit or 1000, u.name)))
181
182                         if self.use_uv=='UNIT0':
183                                 self.uv_layers = [self.uv_layers[0]]
184
185                         next_unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
186                         for u in self.uv_layers:
187                                 if not u.unit:
188                                         u.unit = next_unit
189                                         next_unit += 1
190
191                 for v in self.vertices:
192                         v.groups = [VertexGroup(g) for g in v.groups]
193
194                 edge_map = {e.key: e for e in self.edges}
195                 for f in self.faces:
196                         if len(f.vertices)>4:
197                                 raise ValueError("Ngons are not supported")
198
199                         f.vertices = [self.vertices[i] for i in f.vertices]
200                         for v in f.vertices:
201                                 v.faces.append(f)
202
203                         for k in f.edge_keys:
204                                 e = edge_map[k]
205                                 e.faces.append(f)
206                                 f.edges.append(e)
207
208                 for e in self.edges:
209                         e.vertices = [self.vertices[i] for i in e.vertices]
210                         for v in e.vertices:
211                                 v.edges.append(e)
212
213                 if self.use_lines:
214                         self.lines = [Line(e) for e in self.edges if not e.faces]
215                 else:
216                         self.lines = []
217
218         def __getattr__(self, attr):
219                 return getattr(self._mesh, attr)
220
221         def transform(self, matrix):
222                 for v in self.vertices:
223                         v.co = matrix*v.co
224
225         def splice(self, other):
226                 if len(self.uv_layers)!=len(other.uv_layers):
227                         raise ValueError("Meshes have incompatible UV layers")
228                 for i, u in enumerate(self.uv_layers):
229                         if u.name!=other.uv_layers[i].name:
230                                 raise ValueError("Meshes have incompatible UV layers")
231
232                 material_map = []
233                 for m in other.materials:
234                         if m in self.materials:
235                                 material_map.append(self.materials.index(m))
236                         else:
237                                 material_map.append(len(self.materials))
238                                 self.materials.append(m)
239
240                 for i, u in enumerate(self.uv_layers):
241                         u.uvs += other.uv_layers[i].uvs
242
243                 offset = len(self.vertices)
244                 self.vertices += other.vertices
245                 for v in self.vertices[offset:]:
246                         v.index += offset
247
248                 loop_offset = len(self.loops)
249                 self.loops += other.loops
250
251                 offset = len(self.faces)
252                 self.faces += other.faces
253                 for f in self.faces[offset:]:
254                         f.index += offset
255                         f.loop_start += loop_offset
256                         f.loop_indices = range(f.loop_start, f.loop_start+f.loop_total)
257                         if other.materials:
258                                 f.material_index = material_map[f.material_index]
259
260                 offset = len(self.edges)
261                 self.edges += other.edges
262                 for e in self.edges[offset:]:
263                         e.index += offset
264                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
265
266                 self.lines += other.lines
267
268         def prepare_smoothing(self, progress):
269                 smooth_limit = -1
270                 if self.smoothing=='NONE':
271                         for f in self.faces:
272                                 f.use_smooth = False
273
274                         smooth_limit = 1
275                 elif self.use_auto_smooth:
276                         smooth_limit = math.cos(self.auto_smooth_angle)
277
278                 for e in self.edges:
279                         e.check_smooth(smooth_limit)
280
281                 progress.push_task("Sharp edges", 0.0, 0.7)
282                 self.split_vertices(self.find_smooth_group, progress)
283
284                 if self.smoothing!='BLENDER':
285                         progress.set_task("Updating normals", 0.7, 1.0)
286                         self.compute_normals(progress)
287
288                 progress.pop_task()
289
290         def prepare_vertex_groups(self, obj):
291                 for v in self.vertices:
292                         if v.groups:
293                                 weight_sum = sum(g.weight for g in v.groups)
294                                 v.groups = sorted(v.groups, key=(lambda g: g.weight), reverse=True)[:self.max_groups_per_vertex]
295                                 weight_scale = weight_sum/sum(g.weight for g in v.groups)
296                                 for g in v.groups:
297                                         g.weight *= weight_scale
298
299                 if obj.parent and obj.parent.type=="ARMATURE":
300                         armature = obj.parent.data
301                         bone_indices = {b.name: i for i, b in enumerate(armature.bones)}
302                         group_index_map = {i: i for i in range(len(obj.vertex_groups))}
303                         for g in first_obj.vertex_groups:
304                                 if g.name in bone_indices:
305                                         group_index_map[g.index] = bone_indices[g.name]
306
307                         for v in self.vertices:
308                                 for g in v.groups:
309                                         g.group = group_index_map[g.group]
310
311         def prepare_uv(self, obj, progress):
312                 if obj.material_tex and self.use_uv!='NONE':
313                         layer = UvLayer("material_tex")
314
315                         if self.use_uv=='UNIT0':
316                                 self.uv_layers = [layer]
317                                 layer.unit = 0
318                         else:
319                                 self.uv_layers.append(layer)
320                                 layer.unit = max((u.unit+1 for u in self.uv_layers if u.unit is not None), default=0)
321
322                         layer.uvs = [None]*len(self.loops)
323                         for f in self.faces:
324                                 uv = mathutils.Vector(((f.material_index+0.5)/len(self.materials), 0.5))
325                                 for i in f.loop_indices:
326                                         layer.uvs[i] = uv
327
328                 array_uv_layers = [t.uv_layer for m in self.materials if m.array_atlas for t in m.texture_slots if t and t.texture_coords=='UV']
329                 array_uv_layers = [u for u in self.uv_layers if u.name in array_uv_layers]
330
331                 if array_uv_layers:
332                         for f in self.faces:
333                                 layer = 0
334                                 if f.material_index<len(self.materials):
335                                         mat = self.materials[f.material_index]
336                                         if mat and mat.array_atlas:
337                                                 layer = mat.array_layer
338
339                                 for l in array_uv_layers:
340                                         for i in f.loop_indices:
341                                                 l.uvs[i] = mathutils.Vector((*l.uvs[i], layer))
342
343                 for f in self.faces:
344                         for u in self.uv_layers:
345                                 f.uvs.append([u.uvs[i] for i in f.loop_indices])
346
347                 prog_count = len(self.uv_layers)
348                 prog_step = 0
349
350                 tbn_layer_index = -1
351                 if self.tbn_vecs:
352                         uv_names = [u.name for u in self.uv_layers]
353                         if self.tbn_uvtex in uv_names:
354                                 prog_count += 1
355                                 tbn_layer_index = uv_names.index(self.tbn_uvtex)
356                                 progress.push_task_slice("Computing TBN", 0, prog_count)
357                                 self.split_vertices(self.find_uv_group, progress, tbn_layer_index)
358                                 progress.set_task_slice(self.tbn_uvtex, 1, prog_count)
359                                 self.compute_tbn(tbn_layer_index, progress)
360                                 progress.pop_task()
361                                 prog_step = 2
362
363                 for i, u in enumerate(self.uv_layers):
364                         if i==tbn_layer_index:
365                                 continue
366
367                         progress.push_task_slice(u.name, prog_step, prog_count)
368                         self.split_vertices(self.find_uv_group, progress, i)
369                         progress.pop_task()
370                         prog_step += 1
371
372                 for v in self.vertices:
373                         if v.faces:
374                                 f = v.faces[0]
375                                 i = f.vertices.index(v)
376                                 v.uvs = [u[i] for u in f.uvs]
377                         else:
378                                 v.uvs = [(0.0, 0.0)]*len(self.uv_layers)
379
380         def split_vertices(self, find_group_func, progress, *args):
381                 vertex_count = len(self.vertices)
382                 for i in range(vertex_count):
383                         v = self.vertices[i]
384                         for f in v.faces:
385                                 f.flag = False
386
387                         groups = []
388                         for f in v.faces:
389                                 if not f.flag:
390                                         groups.append(find_group_func(v, f, *args))
391
392                         for g in groups[1:]:
393                                 nv = Vertex(v)
394                                 nv.index = len(self.vertices)
395                                 self.vertices.append(nv)
396
397                                 for e in v.edges:
398                                         e_faces_in_g = [f for f in e.faces if f in g]
399                                         if not e_faces_in_g:
400                                                 continue
401
402                                         if len(e_faces_in_g)<len(e.faces):
403                                                 ne = Edge(e)
404                                                 ne.index = len(self.edges)
405                                                 self.edges.append(ne)
406
407                                                 ne.other_vertex(v).edges.append(ne)
408
409                                                 for f in e_faces_in_g:
410                                                         e.faces.remove(f)
411                                                         f.edges[f.edges.index(e)] = ne
412                                                         ne.faces.append(f)
413
414                                                 e = ne
415
416                                         e.vertices[e.vertices.index(v)] = nv
417                                         nv.edges.append(e)
418
419                                         e.key = make_edge_key(e.vertices[0].index, e.vertices[1].index)
420
421                                 v.edges = [e for e in v.edges if v in e.vertices]
422
423                                 for f in g:
424                                         v.faces.remove(f)
425                                         f.vertices[f.vertices.index(v)] = nv
426                                         nv.faces.append(f)
427
428                         progress.set_progress(i/vertex_count)
429
430         def find_smooth_group(self, vertex, face):
431                 face.flag = True
432
433                 edges = [e for e in face.edges if vertex in e.vertices]
434
435                 group = [face]
436                 for e in edges:
437                         f = face
438                         while e.smooth:
439                                 f = e.other_face(f)
440                                 if not f or f.flag:
441                                         break
442
443                                 f.flag = True
444                                 group.append(f)
445                                 e = f.other_edge(e, vertex)
446
447                 return group
448
449         def find_uv_group(self, vertex, face, index):
450                 uv = face.uvs[index][face.vertices.index(vertex)]
451                 face.flag = True
452
453                 group = [face]
454                 for f in vertex.faces:
455                         if not f.flag and f.uvs[index][f.vertices.index(vertex)]==uv:
456                                 f.flag = True
457                                 group.append(f)
458
459                 return group
460
461         def compute_normals(self, progress):
462                 for i, v in enumerate(self.vertices):
463                         v.normal = mathutils.Vector()
464                         for f in v.faces:
465                                 fv = f.pivot_vertices(v)
466                                 edge1 = fv[1].co-fv[0].co
467                                 edge2 = fv[-1].co-fv[0].co
468                                 if edge1.length and edge2.length:
469                                         v.normal += f.normal*edge1.angle(edge2)
470
471                         if v.normal.length:
472                                 v.normal.normalize()
473                         else:
474                                 v.normal = mathutils.Vector((0, 0, 1))
475
476                         progress.set_progress(i/len(self.vertices))
477
478         def compute_tbn(self, index, progress):
479                 layer_uvs = self.uv_layers[index].uvs
480
481                 for i, v in enumerate(self.vertices):
482                         v.tan = mathutils.Vector()
483                         v.bino = mathutils.Vector()
484                         for f in v.faces:
485                                 vi = f.pivot_vertex(v)
486                                 uv0 = layer_uvs[f.loop_indices[vi[0]]]
487                                 uv1 = layer_uvs[f.loop_indices[vi[1]]]
488                                 uv2 = layer_uvs[f.loop_indices[vi[-1]]]
489                                 du1 = uv1[0]-uv0[0]
490                                 du2 = uv2[0]-uv0[0]
491                                 dv1 = uv1[1]-uv0[1]
492                                 dv2 = uv2[1]-uv0[1]
493                                 edge1 = f.vertices[vi[1]].co-f.vertices[vi[0]].co
494                                 edge2 = f.vertices[vi[-1]].co-f.vertices[vi[0]].co
495                                 div = (du1*dv2-du2*dv1)
496                                 if div:
497                                         mul = edge1.angle(edge2)/div
498                                         v.tan += (edge1*dv2-edge2*dv1)*mul
499                                         v.bino += (edge2*du1-edge1*du2)*mul
500
501                         if v.tan.length:
502                                 v.tan.normalize()
503                         if v.bino.length:
504                                 v.bino.normalize()
505
506                         progress.set_progress(i/len(self.vertices))
507
508         def drop_references(self):
509                 for v in self.vertices:
510                         v._vertex = None
511                         for g in v.groups:
512                                 g._group = None
513                 for e in self.edges:
514                         e._edge = None
515                 for f in self.faces:
516                         f._face = None
517                 for u in self.uv_layers:
518                         u._layer = None
519                 self._mesh = None
520
521         def create_strip(self, face, max_len):
522                 # Find an edge with another unused face next to it
523                 edge = None
524                 for e in face.edges:
525                         other = e.other_face(face)
526                         if other and not other.flag:
527                                 edge = e
528                                 break
529
530                 if not edge:
531                         return None
532
533                 # Add initial vertices so that we'll complete the edge on the first
534                 # iteration
535                 vertices = face.pivot_vertices(*edge.vertices)
536                 if len(vertices)==3:
537                         result = [vertices[-1], vertices[0]]
538                 else:
539                         result = [vertices[-2], vertices[-1]]
540
541                 while 1:
542                         face.flag = True
543
544                         vertices = face.pivot_vertices(*result[-2:])
545                         k = len(result)%2
546
547                         # Quads need special handling because the winding of every other
548                         # triangle in the strip is reversed
549                         if len(vertices)==4 and not k:
550                                 result.append(vertices[3])
551                         result.append(vertices[2])
552                         if len(vertices)==4 and k:
553                                 result.append(vertices[3])
554
555                         if len(result)>=max_len:
556                                 break
557
558                         # Hop over the last edge
559                         edge = face.get_edge(*result[-2:])
560                         face = edge.other_face(face)
561                         if not face or face.flag:
562                                 break
563
564                 return result
565
566 def create_mesh_from_object(context, obj, progress):
567         if obj.type!="MESH":
568                 raise Exception("Object is not a mesh")
569
570         progress.push_task("Preparing mesh", 0.0, 0.3)
571
572         objs = [(obj, mathutils.Matrix())]
573         i = 0
574         while i<len(objs):
575                 o, m = objs[i]
576                 i += 1
577                 for c in o.children:
578                         if c.type=="MESH" and c.compound:
579                                 objs.append((c, m*c.matrix_local))
580
581         mesh = None
582         bmeshes = []
583         for o, m in objs:
584                 bmesh = o.to_mesh(context.scene, True, "PREVIEW")
585                 bmeshes.append(bmesh)
586
587                 # Object.to_mesh does not copy custom properties
588                 bmesh.winding_test = o.data.winding_test
589                 bmesh.smoothing = o.data.smoothing
590                 bmesh.use_lines = o.data.use_lines
591                 bmesh.vertex_groups = o.data.vertex_groups
592                 bmesh.max_groups_per_vertex = o.data.max_groups_per_vertex
593                 bmesh.use_uv = o.data.use_uv
594                 bmesh.tbn_vecs = o.data.tbn_vecs
595                 bmesh.tbn_uvtex = o.data.tbn_uvtex
596
597                 me = Mesh(bmesh)
598                 me.transform(m)
599
600                 if mesh:
601                         mesh.splice(me)
602                 else:
603                         mesh = me
604
605         progress.set_task("Smoothing", 0.3, 0.6)
606         mesh.prepare_smoothing(progress)
607         progress.set_task("Vertex groups", 0.6, 0.7)
608         mesh.prepare_vertex_groups(obj)
609         progress.set_task("Preparing UVs", 0.7, 1.0)
610         mesh.prepare_uv(obj, progress)
611
612         mesh.drop_references()
613         for m in bmeshes:
614                 bpy.data.meshes.remove(m)
615
616         progress.pop_task()
617
618         return mesh