OSDN Git Service

5cbf3b7c424d3a2edcef50d859e877d4ef7cab4c
[meshio/meshio.git] / swig / blender24 / pmd_export.py
1 #!BPY
2 # coding: utf-8
3 """
4  Name: 'MikuMikuDance model (.pmd)...'
5  Blender: 248
6  Group: 'Export'
7  Tooltip: 'Export PMD file for MikuMikuDance.'
8 """
9 __author__= ["ousttrue"]
10 __version__= "0.2"
11 __url__=()
12 __bpydoc__="""
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
15 """
16 import Blender
17 import os
18 import sys
19
20 from meshio import pmd, englishmap
21
22
23 # ファイルシステムの文字コード
24 # 改造版との共用のため
25 FS_ENCODING=sys.getfilesystemencoding()
26 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
27     INTERNAL_ENCODING='utf-8'
28 else:
29     INTERNAL_ENCODING=FS_ENCODING
30
31
32 EXTENSION = u'.pmd'
33
34
35 class Node(object):
36     __slots__=['o', 'children']
37     def __init__(self, o):
38         self.o=o
39         self.children=[]
40
41
42 ###############################################################################
43 # Blenderのメッシュをワンスキンメッシュ化する
44 ###############################################################################
45 def near(x, y, EPSILON=1e-5):
46     d=x-y
47     return d>=-EPSILON and d<=EPSILON
48
49
50 class VertexKey(object):
51     """
52     重複頂点の検索キー
53     """
54     __slots__=[
55             'x', 'y', 'z', # 位置
56             'nx', 'ny', 'nz', # 法線
57             'u', 'v', # uv
58             ]
59
60     def __init__(self, x, y, z, nx, ny, nz, u, v):
61         self.x=x
62         self.y=y
63         self.z=z
64         self.nx=nx
65         self.ny=ny
66         self.nz=nz
67         self.u=u
68         self.v=v
69
70     def __hash__(self):
71         return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
72
73     def __eq__(self, rhs):
74         return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z) and near(self.nx, rhs.nx) and near(self.ny, rhs.ny) and near(self.nz, rhs.nz) and near(self.u, rhs.u) and near(self.v, rhs.v)
75
76
77 class VertexArray(object):
78     """
79     頂点配列
80     """
81     def __init__(self):
82         # マテリアル毎に分割したインデックス配列
83         self.indexArrays={}
84         # 頂点属性
85         self.vertices=[]
86         self.normals=[]
87         self.uvs=[]
88         # skinning属性
89         self.b0=[]
90         self.b1=[]
91         self.weight=[]
92
93         self.vertexMap={}
94
95     def __str__(self):
96         return "<VertexArray %d vertices, %d indexArrays>" % (
97                 len(self.vertices), len(self.indexArrays))
98
99     def zip(self):
100         return zip(
101                 self.vertices, self.normals, self.uvs,
102                 self.b0, self.b1, self.weight)
103
104     def getIndex(self, pos, normal, uv, b0, b1, weight0):
105         """
106         頂点属性からその頂点のインデックスを得る
107         """
108         key=VertexKey(
109                 pos[0], pos[1], pos[2],
110                 normal[0], normal[1], normal[2],
111                 uv[0], uv[1])
112         if not key in self.vertexMap:
113             self.vertexMap[key]=len(self.vertices)
114             self.vertices.append((pos.x, pos.y, pos.z))
115             self.normals.append((normal.x, normal.y, normal.z))
116             self.uvs.append((uv.x, uv.y))
117             # ToDo
118             self.b0.append(b0)
119             self.b1.append(b1)
120             self.weight.append(weight0)
121         return self.vertexMap[key]
122
123     def addTriangle(self,
124             material,
125             pos0, pos1, pos2,
126             n0, n1, n2,
127             uv0, uv1, uv2,
128             b0_0, b0_1, b0_2,
129             b1_0, b1_1, b1_2,
130             weight0, weight1, weight2
131             ):
132         if not material in self.indexArrays:
133             self.indexArrays[material]=[]
134
135         index0=self.getIndex(pos0, n0, uv0, b0_0, b1_0, weight0)
136         index1=self.getIndex(pos1, n1, uv1, b0_1, b1_1, weight1)
137         index2=self.getIndex(pos2, n2, uv2, b0_2, b1_2, weight2)
138
139         self.indexArrays[material]+=[index0, index1, index2]
140
141
142 class OneSkinMesh(object):
143     __slots__=['armatureObj', 'vertexArray']
144     def __init__(self, root):
145         self.armatureObj=None
146         self.vertexArray=VertexArray()
147         self.__create(root)
148
149     def __str__(self):
150         return "<OneSkinMesh armature:%s, %s>" % (
151                 self.armatureObj.name if self.armatureObj else None, 
152                 self.vertexArray)
153
154     def __create(self, node):
155         if node.o.getType()=='Mesh':
156             self.__addMesh(node.o)
157
158         for child in node.children:
159             self.__create(child)
160
161     def __addMesh(self, obj):
162         if obj.restrictDisplay:
163             # 非表示
164             return
165
166         print("export", obj.name)
167
168         ############################################################
169         # search armature modifier
170         ############################################################
171         for m in obj.modifiers:
172             if m.name=="Armature":
173                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
174                 if not self.armatureObj:
175                     self.armatureObj=armatureObj
176                 elif self.armatureObj!=armatureObj:
177                     print "warning! found multiple armature. ignored.", armatureObj.name
178
179         ############################################################
180         # bone weight
181         ############################################################
182         mesh=obj.getData(mesh=True)
183         weightMap={}
184         secondWeightMap={}
185         for name in mesh.getVertGroupNames():
186             for i, w in mesh.getVertsFromGroup(name, 1):
187                 if w>0:
188                     if i in weightMap:
189                         if i in secondWeightMap:
190                             # 上位2つのweightを採用する
191                             if w<secondWeightMap[i]:
192                                 pass
193                             elif w<weightMap[i]:
194                                 # 2つ目を入れ替え
195                                 secondWeightMap[i]=(name, w)
196                             else:
197                                 # 1つ目を入れ替え
198                                 weightMap[i]=(name, w)
199                         else:
200                             if w>weightMap[i][1]:
201                                 # 多い方をweightMapに
202                                 secondWeightMap[i]=weightMap[i]
203                                 weightMap[i]=(name, w)
204                             else:
205                                 secondWeightMap[i]=(name, w)
206                     else:
207                         weightMap[i]=(name, w)
208
209         # 合計値が1になるようにする
210         for i in xrange(len(mesh.verts)):
211         #for i, name_weight in weightMap.items():
212             if i in secondWeightMap:
213                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
214             elif i in weightMap:
215                 weightMap[i]=(weightMap[i][0], 1.0)
216                 secondWeightMap[i]=("", 0)
217             else:
218                 print "no weight vertex"
219                 weightMap[i]=("", 0)
220                 secondWeightMap[i]=("", 0)
221                 
222
223         ############################################################
224         # faces
225         # 新たにメッシュを生成する
226         ############################################################
227         mesh=Blender.Mesh.New()
228         # not applied modifiers
229         mesh.getFromObject(obj.name, 1)
230         # apply object transform
231         mesh.transform(obj.getMatrix())
232         if len(mesh.verts)==0:
233             return
234
235         for face in mesh.faces:
236             faceVertexCount=len(face.v)
237             material=mesh.materials[face.mat]
238             if faceVertexCount==3:
239                 v0=face.v[0]
240                 v1=face.v[1]
241                 v2=face.v[2]
242                 # triangle
243                 self.vertexArray.addTriangle(
244                         material.name,
245                         v0.co, v1.co, v2.co,
246                         v0.no, v1.no, v2.no,
247                         face.uv[0], face.uv[1], face.uv[2],
248                         weightMap[v0.index][0],
249                         weightMap[v1.index][0],
250                         weightMap[v2.index][0],
251                         secondWeightMap[v0.index][0],
252                         secondWeightMap[v1.index][0],
253                         secondWeightMap[v2.index][0],
254                         weightMap[v0.index][1],
255                         weightMap[v1.index][1],
256                         weightMap[v2.index][1]
257                         )
258             elif faceVertexCount==4:
259                 v0=face.v[0]
260                 v1=face.v[1]
261                 v2=face.v[2]
262                 v3=face.v[3]
263                 # quadrangle
264                 self.vertexArray.addTriangle(
265                         material.name,
266                         v0.co, v1.co, v2.co,
267                         v0.no, v1.no, v2.no,
268                         face.uv[0], face.uv[1], face.uv[2],
269                         weightMap[v0.index][0],
270                         weightMap[v1.index][0],
271                         weightMap[v2.index][0],
272                         secondWeightMap[v0.index][0],
273                         secondWeightMap[v1.index][0],
274                         secondWeightMap[v2.index][0],
275                         weightMap[v0.index][1],
276                         weightMap[v1.index][1],
277                         weightMap[v2.index][1]
278                         )
279                 self.vertexArray.addTriangle(
280                         material.name,
281                         v2.co, v3.co, v0.co,
282                         v2.no, v3.no, v0.no,
283                         face.uv[2], face.uv[3], face.uv[0],
284                         weightMap[v2.index][0],
285                         weightMap[v3.index][0],
286                         weightMap[v0.index][0],
287                         secondWeightMap[v2.index][0],
288                         secondWeightMap[v3.index][0],
289                         secondWeightMap[v0.index][0],
290                         weightMap[v2.index][1],
291                         weightMap[v3.index][1],
292                         weightMap[v0.index][1]
293                         )
294
295     def getVertexCount(self):
296         return len(self.vertexArray.vertices)
297
298
299 class Bone(object):
300     def __init__(self, bone):
301         self.name=bone.name
302         pos=bone.head['ARMATURESPACE']
303         self.pos=[pos.x, pos.y, pos.z]
304         self.parent_index=None
305         self.tail_index=None
306
307     def __str__(self):
308         return "<Bone %s>" % self.name
309
310 class BoneBuilder(object):
311     __slots__=['bones', 'boneMap']
312     def __init__(self):
313         self.bones=[]
314         self.boneMap={}
315
316     def build(self, armatureObj):
317         if armatureObj:
318             armature=armatureObj.getData()
319             for b in armature.bones.values():
320                 if not b.parent:
321                     # root bone
322                     bone=Bone(b)
323                     self.addBone(bone)
324                     self.getBone(bone, b)
325
326     def getBone(self, parent, b):
327         if len(b.children)==0:
328             return
329
330         for i, c in enumerate(b.children):
331             bone=Bone(c)
332             self.addBone(bone)
333             if parent:
334                 bone.parent_index=parent.index
335                 if i==0:
336                     parent.tail_index=bone.index
337             self.getBone(bone, c)
338
339     def addBone(self, bone):
340         bone.index=len(self.bones)
341         self.bones.append(bone)
342         self.boneMap[bone.name]=bone.index
343
344
345 class PmdExporter(object):
346
347     def setup(self, scene):
348         # 木構造を構築する
349         object_node_map={}
350         for o in scene.objects:
351             object_node_map[o]=Node(o)
352         for node in object_node_map.values():
353             if node.o.parent:
354                 object_node_map[node.o.parent].children.append(node)
355         # ルートを得る
356         root=object_node_map[scene.objects.active]
357
358         # ワンスキンメッシュを作る
359         self.oneSkinMesh=OneSkinMesh(root)
360         print(self.oneSkinMesh)
361         self.name=root.o.name
362
363     def write(self, path):
364         io=pmd.IO()
365         io.name=self.name
366         io.comment="blender export"
367         io.version=1.0
368
369         # bones
370         builder=BoneBuilder()
371         builder.build(self.oneSkinMesh.armatureObj)
372         for b in builder.bones:
373             bone=io.addBone()
374             bone.name=b.name
375             bone.type=0
376             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
377             bone.tail_index=b.tail_index if b.tail_index!=None else 0xFFFF
378             # ToDo
379             bone.ik_index=0xFFFF
380             # convert right-handed z-up to left-handed y-up
381             bone.pos.x=b.pos[0]
382             bone.pos.y=b.pos[2]
383             bone.pos.z=b.pos[1]
384
385         # 頂点
386         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
387             # convert right-handed z-up to left-handed y-up
388             v=io.addVertex()
389             v.pos.x=pos[0]
390             v.pos.y=pos[2]
391             v.pos.z=pos[1]
392             v.normal.x=normal[0]
393             v.normal.y=normal[2]
394             v.normal.z=normal[1]
395             v.uv.x=uv[0]
396             v.uv.y=uv[1]
397             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
398             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
399             v.weight0=int(100*weight)
400             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
401
402         # 面とマテリアル
403         vertexCount=self.oneSkinMesh.getVertexCount()
404         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
405             print(m, len(indices))
406             m=Blender.Material.Get(m)
407             # マテリアル
408             material=io.addMaterial()
409             material.diffuse.r=m.R
410             material.diffuse.g=m.G
411             material.diffuse.b=m.B
412             material.diffuse.a=m.alpha
413             material.sinness=m.spec
414             material.specular.r=m.specR
415             material.specular.g=m.specG
416             material.specular.b=m.specB
417             material.ambient.r=m.amb
418             material.ambient.g=m.amb
419             material.ambient.b=m.amb
420             material.vertex_count=len(indices)
421             material.toon_index=0
422             # ToDo
423             material.texture=""
424             # 面
425             for i in indices:
426                 assert(i<vertexCount)
427             for i in xrange(0, len(indices), 3):
428                 # reverse triangle
429                 io.indices.append(indices[i+2])
430                 io.indices.append(indices[i+1])
431                 io.indices.append(indices[i])
432
433                 #io.indices.append(indices[i])
434                 #io.indices.append(indices[i+1])
435                 #io.indices.append(indices[i+2])
436
437         # 書き込み
438         return io.write(path.encode(FS_ENCODING))
439
440
441 def export_pmd(filename):
442     filename=filename.decode(INTERNAL_ENCODING)
443
444     Blender.Window.WaitCursor(1) 
445     t = Blender.sys.time() 
446
447     if not filename.lower().endswith(EXTENSION):
448         filename += EXTENSION
449     print "pmd exporter: %s" % filename
450
451     exporter=PmdExporter()
452
453     # 情報収集
454     exporter.setup(Blender.Scene.GetCurrent())
455
456     # 出力
457     exporter.write(filename)
458
459     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
460     Blender.Redraw()
461     Blender.Window.WaitCursor(0) 
462  
463
464 Blender.Window.FileSelector(
465         export_pmd,
466         'Export Metasequoia PMD',
467         Blender.sys.makename(ext=EXTENSION))
468