OSDN Git Service

implement tail bone.
[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, name, pos):
301         self.name=name
302         self.pos=[pos.x, pos.y, pos.z]
303         self.parent_index=None
304         self.tail_index=None
305         self.type=0
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.name, b.head['ARMATURESPACE'])
323                     self.addBone(bone)
324                     self.getBone(bone, b)
325
326     def getBone(self, parent, b):
327         if len(b.children)==0:
328             # 末端の非表示ボーン
329             bone=Bone(b.name+'_tail', b.tail['ARMATURESPACE'])
330             bone.type=7
331             self.addBone(bone)
332             assert(parent)
333             bone.parent_index=parent.index
334             parent.tail_index=bone.index
335             return
336
337         for i, c in enumerate(b.children):
338             bone=Bone(c.name, c.head['ARMATURESPACE'])
339             self.addBone(bone)
340             if parent:
341                 bone.parent_index=parent.index
342                 if i==0:
343                     parent.tail_index=bone.index
344             self.getBone(bone, c)
345
346     def addBone(self, bone):
347         bone.index=len(self.bones)
348         self.bones.append(bone)
349         self.boneMap[bone.name]=bone.index
350
351
352 class PmdExporter(object):
353
354     def setup(self, scene):
355         # 木構造を構築する
356         object_node_map={}
357         for o in scene.objects:
358             object_node_map[o]=Node(o)
359         for node in object_node_map.values():
360             if node.o.parent:
361                 object_node_map[node.o.parent].children.append(node)
362         # ルートを得る
363         root=object_node_map[scene.objects.active]
364
365         # ワンスキンメッシュを作る
366         self.oneSkinMesh=OneSkinMesh(root)
367         print(self.oneSkinMesh)
368         self.name=root.o.name
369
370     def write(self, path):
371         io=pmd.IO()
372         io.name=self.name
373         io.comment="blender export"
374         io.version=1.0
375
376         # bones
377         builder=BoneBuilder()
378         builder.build(self.oneSkinMesh.armatureObj)
379         for b in builder.bones:
380             bone=io.addBone()
381             bone.name=b.name
382             bone.type=b.type
383             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
384             bone.tail_index=b.tail_index if b.tail_index!=None else 0
385             # ToDo
386             bone.ik_index=0xFFFF
387             # convert right-handed z-up to left-handed y-up
388             bone.pos.x=b.pos[0]
389             bone.pos.y=b.pos[2]
390             bone.pos.z=b.pos[1]
391
392         # 頂点
393         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
394             # convert right-handed z-up to left-handed y-up
395             v=io.addVertex()
396             v.pos.x=pos[0]
397             v.pos.y=pos[2]
398             v.pos.z=pos[1]
399             v.normal.x=normal[0]
400             v.normal.y=normal[2]
401             v.normal.z=normal[1]
402             v.uv.x=uv[0]
403             v.uv.y=uv[1]
404             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
405             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
406             v.weight0=int(100*weight)
407             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
408
409         # 面とマテリアル
410         vertexCount=self.oneSkinMesh.getVertexCount()
411         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
412             print(m, len(indices))
413             m=Blender.Material.Get(m)
414             # マテリアル
415             material=io.addMaterial()
416             material.diffuse.r=m.R
417             material.diffuse.g=m.G
418             material.diffuse.b=m.B
419             material.diffuse.a=m.alpha
420             material.sinness=m.spec
421             material.specular.r=m.specR
422             material.specular.g=m.specG
423             material.specular.b=m.specB
424             material.ambient.r=m.amb
425             material.ambient.g=m.amb
426             material.ambient.b=m.amb
427             material.vertex_count=len(indices)
428             material.toon_index=0
429             # ToDo
430             material.texture=""
431             # 面
432             for i in indices:
433                 assert(i<vertexCount)
434             for i in xrange(0, len(indices), 3):
435                 # reverse triangle
436                 io.indices.append(indices[i+2])
437                 io.indices.append(indices[i+1])
438                 io.indices.append(indices[i])
439
440                 #io.indices.append(indices[i])
441                 #io.indices.append(indices[i+1])
442                 #io.indices.append(indices[i+2])
443
444         # 書き込み
445         return io.write(path.encode(FS_ENCODING))
446
447
448 def export_pmd(filename):
449     filename=filename.decode(INTERNAL_ENCODING)
450
451     Blender.Window.WaitCursor(1) 
452     t = Blender.sys.time() 
453
454     if not filename.lower().endswith(EXTENSION):
455         filename += EXTENSION
456     print "pmd exporter: %s" % filename
457
458     exporter=PmdExporter()
459
460     # 情報収集
461     exporter.setup(Blender.Scene.GetCurrent())
462
463     # 出力
464     exporter.write(filename)
465
466     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
467     Blender.Redraw()
468     Blender.Window.WaitCursor(0) 
469  
470
471 Blender.Window.FileSelector(
472         export_pmd,
473         'Export Metasequoia PMD',
474         Blender.sys.makename(ext=EXTENSION))
475