OSDN Git Service

9ce8df21210c7d5aaaa1aac534f8d9e4d2003d90
[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 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
33 EXTENSION = u'.pmd'
34
35
36 class Node(object):
37     __slots__=['o', 'children']
38     def __init__(self, o):
39         self.o=o
40         self.children=[]
41
42
43 ###############################################################################
44 # Blenderのメッシュをワンスキンメッシュ化する
45 ###############################################################################
46 def near(x, y, EPSILON=1e-5):
47     d=x-y
48     return d>=-EPSILON and d<=EPSILON
49
50
51 class VertexKey(object):
52     """
53     重複頂点の検索キー
54     """
55     __slots__=[
56             'x', 'y', 'z', # 位置
57             'nx', 'ny', 'nz', # 法線
58             'u', 'v', # uv
59             ]
60
61     def __init__(self, x, y, z, nx, ny, nz, u, v):
62         self.x=x
63         self.y=y
64         self.z=z
65         self.nx=nx
66         self.ny=ny
67         self.nz=nz
68         self.u=u
69         self.v=v
70
71     def __str__(self):
72         return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
73                 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
74
75     def __hash__(self):
76         #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
77         return int((self.x+self.y+self.z)*100)
78
79     def __eq__(self, rhs):
80         #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)
81         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
82         return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
83
84
85 class VertexArray(object):
86     """
87     頂点配列
88     """
89     def __init__(self):
90         # マテリアル毎に分割したインデックス配列
91         self.indexArrays={}
92         # 頂点属性
93         self.vertices=[]
94         self.normals=[]
95         self.uvs=[]
96         # skinning属性
97         self.b0=[]
98         self.b1=[]
99         self.weight=[]
100
101         self.vertexMap={}
102         self.indexMap={}
103
104     def __str__(self):
105         return "<VertexArray %d vertices, %d indexArrays>" % (
106                 len(self.vertices), len(self.indexArrays))
107
108     def zip(self):
109         return zip(
110                 self.vertices, self.normals, self.uvs,
111                 self.b0, self.b1, self.weight)
112
113     def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
114         """
115         頂点属性からその頂点のインデックスを得る
116         """
117         key=VertexKey(
118                 pos[0], pos[1], pos[2],
119                 normal[0], normal[1], normal[2],
120                 uv[0], uv[1])
121         if key in self.vertexMap:
122             # 同じ頂点を登録済み
123             index=self.vertexMap[key]
124         else:
125             index=len(self.vertices)
126             # 新規頂点
127             self.vertexMap[key]=index
128             # append...
129             self.vertices.append((pos.x, pos.y, pos.z))
130             self.normals.append((normal.x, normal.y, normal.z))
131             self.uvs.append((uv.x, uv.y))
132             self.b0.append(b0)
133             self.b1.append(b1)
134             self.weight.append(weight0)
135             
136         # indexのマッピングを保存する
137         if not base_index in self.indexMap:
138             self.indexMap[base_index]=set()
139         self.indexMap[base_index].add(index)
140
141         assert(index<=65535)
142         return index
143
144     def getMappedIndices(self, base_index):
145         return self.indexMap[base_index]
146
147     def addTriangle(self,
148             material,
149             base_index0, base_index1, base_index2,
150             pos0, pos1, pos2,
151             n0, n1, n2,
152             uv0, uv1, uv2,
153             b0_0, b0_1, b0_2,
154             b1_0, b1_1, b1_2,
155             weight0, weight1, weight2
156             ):
157         if not material in self.indexArrays:
158             self.indexArrays[material]=[]
159
160         index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
161         index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
162         index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
163
164         self.indexArrays[material]+=[index0, index1, index2]
165
166
167 class Morph(object):
168     __slots__=['name', 'type', 'indices', 'offsets']
169     def __init__(self, name, type):
170         self.name=name
171         self.type=type
172         self.indices=[]
173         self.offsets=[]
174
175 class OneSkinMesh(object):
176     __slots__=['armatureObj', 'vertexArray', 'morphList']
177     def __init__(self, root):
178         self.armatureObj=None
179         self.vertexArray=VertexArray()
180         self.morphList=[]
181         self.__create(root)
182
183     def __str__(self):
184         return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
185                 self.armatureObj.name if self.armatureObj else None, 
186                 self.vertexArray,
187                 len(self.morphList))
188
189     def __create(self, node):
190         if node.o.getType()=='Mesh':
191             self.__addMesh(node.o)
192
193         for child in node.children:
194             self.__create(child)
195
196     def __addMesh(self, obj):
197         if obj.restrictDisplay:
198             # 非表示
199             return
200
201         print("export", obj.name)
202
203         ############################################################
204         # search armature modifier
205         ############################################################
206         for m in obj.modifiers:
207             if m.name=="Armature":
208                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
209                 if not self.armatureObj:
210                     self.armatureObj=armatureObj
211                 elif self.armatureObj!=armatureObj:
212                     print "warning! found multiple armature. ignored.", armatureObj.name
213
214         ############################################################
215         # bone weight
216         ############################################################
217         mesh=obj.getData(mesh=True)
218         weightMap={}
219         secondWeightMap={}
220         for name in mesh.getVertGroupNames():
221             for i, w in mesh.getVertsFromGroup(name, 1):
222                 if w>0:
223                     if i in weightMap:
224                         if i in secondWeightMap:
225                             # 上位2つのweightを採用する
226                             if w<secondWeightMap[i]:
227                                 pass
228                             elif w<weightMap[i]:
229                                 # 2つ目を入れ替え
230                                 secondWeightMap[i]=(name, w)
231                             else:
232                                 # 1つ目を入れ替え
233                                 weightMap[i]=(name, w)
234                         else:
235                             if w>weightMap[i][1]:
236                                 # 多い方をweightMapに
237                                 secondWeightMap[i]=weightMap[i]
238                                 weightMap[i]=(name, w)
239                             else:
240                                 secondWeightMap[i]=(name, w)
241                     else:
242                         weightMap[i]=(name, w)
243
244         # 合計値が1になるようにする
245         for i in xrange(len(mesh.verts)):
246         #for i, name_weight in weightMap.items():
247             if i in secondWeightMap:
248                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
249             elif i in weightMap:
250                 weightMap[i]=(weightMap[i][0], 1.0)
251                 secondWeightMap[i]=("", 0)
252             else:
253                 print "no weight vertex"
254                 weightMap[i]=("", 0)
255                 secondWeightMap[i]=("", 0)
256                 
257
258         ############################################################
259         # faces
260         # 新たにメッシュを生成する
261         ############################################################
262         mesh=Blender.Mesh.New()
263         # not applied modifiers
264         mesh.getFromObject(obj.name, 1)
265         # apply object transform
266         mesh.transform(obj.getMatrix())
267         if len(mesh.verts)==0:
268             return
269
270         for face in mesh.faces:
271             faceVertexCount=len(face.v)
272             material=mesh.materials[face.mat]
273             if faceVertexCount==3:
274                 v0=face.v[0]
275                 v1=face.v[1]
276                 v2=face.v[2]
277                 # triangle
278                 self.vertexArray.addTriangle(
279                         material.name,
280                         v0.index, v1.index, v2.index,
281                         v0.co, v1.co, v2.co,
282                         # ToDo vertex normal
283                         #v0.no, v1.no, v2.no,
284                         face.no, face.no, face.no,
285                         face.uv[0], face.uv[1], face.uv[2],
286                         weightMap[v0.index][0],
287                         weightMap[v1.index][0],
288                         weightMap[v2.index][0],
289                         secondWeightMap[v0.index][0],
290                         secondWeightMap[v1.index][0],
291                         secondWeightMap[v2.index][0],
292                         weightMap[v0.index][1],
293                         weightMap[v1.index][1],
294                         weightMap[v2.index][1]
295                         )
296             elif faceVertexCount==4:
297                 v0=face.v[0]
298                 v1=face.v[1]
299                 v2=face.v[2]
300                 v3=face.v[3]
301                 # quadrangle
302                 self.vertexArray.addTriangle(
303                         material.name,
304                         v0.index, v1.index, v2.index,
305                         v0.co, v1.co, v2.co,
306                         #v0.no, v1.no, v2.no,
307                         face.no, face.no, face.no,
308                         face.uv[0], face.uv[1], face.uv[2],
309                         weightMap[v0.index][0],
310                         weightMap[v1.index][0],
311                         weightMap[v2.index][0],
312                         secondWeightMap[v0.index][0],
313                         secondWeightMap[v1.index][0],
314                         secondWeightMap[v2.index][0],
315                         weightMap[v0.index][1],
316                         weightMap[v1.index][1],
317                         weightMap[v2.index][1]
318                         )
319                 self.vertexArray.addTriangle(
320                         material.name,
321                         v2.index, v3.index, v0.index,
322                         v2.co, v3.co, v0.co,
323                         #v2.no, v3.no, v0.no,
324                         face.no, face.no, face.no,
325                         face.uv[2], face.uv[3], face.uv[0],
326                         weightMap[v2.index][0],
327                         weightMap[v3.index][0],
328                         weightMap[v0.index][0],
329                         secondWeightMap[v2.index][0],
330                         secondWeightMap[v3.index][0],
331                         secondWeightMap[v0.index][0],
332                         weightMap[v2.index][1],
333                         weightMap[v3.index][1],
334                         weightMap[v0.index][1]
335                         )
336
337         ############################################################
338         # skin
339         ############################################################
340         # base
341         indexRelativeMap={}
342         blenderMesh=obj.getData(mesh=True)
343         if blenderMesh.key:
344             for b in blenderMesh.key.blocks:
345                 if b.name=='Basis':
346                     print(b.name)
347                     morph=self.__getOrCreateMorph('base', 0)
348                     relativeIndex=0
349                     basis=b
350                     for index in blenderMesh.getVertsFromGroup(
351                             MMD_SHAPE_GROUP_NAME):
352                         v=b.data[index]
353                         pos=[v[0], v[1], v[2]]
354                         indices=self.vertexArray.getMappedIndices(index)
355                         for i in indices:
356                             morph.indices.append(i)
357                             morph.offsets.append(pos)
358                             indexRelativeMap[i]=relativeIndex
359                             relativeIndex+=1
360                     break
361
362             assert(basis)
363
364             # shape keys
365             for b in obj.getData(mesh=True).key.blocks:
366                 if b.name=='Basis':
367                     continue
368
369                 print(b.name)
370                 morph=self.__getOrCreateMorph(b.name, 4)
371                 for index in obj.getData(mesh=True).getVertsFromGroup(
372                         MMD_SHAPE_GROUP_NAME):
373                     #offset=[d-s for d, s in zip(
374                     #    b.data[index], basis.data[index])]
375                     src=basis.data[index]
376                     dst=b.data[index]
377                     offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
378                     indices=self.vertexArray.getMappedIndices(index)
379                     for i in indices:
380                         morph.indices.append(indexRelativeMap[i])
381                         morph.offsets.append(offset)
382
383     def __getOrCreateMorph(self, name, type):
384         for m in self.morphList:
385             if m.name==name:
386                 return m
387         m=Morph(name, type)
388         self.morphList.append(m)
389         return m
390
391     def getVertexCount(self):
392         return len(self.vertexArray.vertices)
393
394
395 class Bone(object):
396     __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
397     def __init__(self, name, pos):
398         self.index=-1
399         self.name=name
400         self.pos=[pos.x, pos.y, pos.z]
401         self.parent_index=None
402         self.tail_index=None
403         self.type=0
404
405     def __str__(self):
406         return "<Bone %s %d>" % (self.name, self.type)
407
408 class BoneBuilder(object):
409     __slots__=['bones', 'boneMap', 'ik_list']
410     def __init__(self):
411         self.bones=[]
412         self.boneMap={}
413         self.ik_list=[]
414
415     def build(self, armatureObj):
416         if armatureObj:
417             armature=armatureObj.getData()
418             for b in armature.bones.values():
419                 if not b.parent:
420                     # root bone
421                     bone=Bone(b.name, b.head['ARMATURESPACE'])
422                     self.__addBone(bone)
423                     self.__getBone(bone, b)
424
425         pose = armatureObj.getPose()
426         for b in pose.bones.values():
427             for c in b.constraints:
428                 if c.type==Blender.Constraint.Type.IKSOLVER:
429                     # IK effector
430                     e=b
431                     for i in range(c[Blender.Constraint.Settings.CHAINLEN]):
432                         # IK影響下
433                         self.__boneByName(e.name).type=4
434                         e=e.parent
435                     # IK target
436                     assert(c[Blender.Constraint.Settings.TARGET]==armatureObj)
437                     self.__boneByName(
438                             c[Blender.Constraint.Settings.BONE]).type=2
439                     # IK 接続先
440                     link=self.__boneByName(b.name)
441                     link_tail=self.bones[link.tail_index]
442                     if link_tail.type==7:
443                         # IK接続先
444                         link_tail.type=6
445                         
446
447     def __boneByName(self, name):
448         return self.bones[self.boneMap[name]]
449                     
450     def __getBone(self, parent, b):
451         if not Blender.Armature.CONNECTED in b.options:
452             #print b, b.options
453             pass
454
455         if len(b.children)==0:
456             # 末端の非表示ボーン
457             bone=Bone(b.name+'_tail', b.tail['ARMATURESPACE'])
458             bone.type=7
459             self.__addBone(bone)
460             assert(parent)
461             bone.parent_index=parent.index
462             parent.tail_index=bone.index
463             return
464
465         for i, c in enumerate(b.children):
466             bone=Bone(c.name, c.head['ARMATURESPACE'])
467             self.__addBone(bone)
468             if parent:
469                 bone.parent_index=parent.index
470                 if i==0:
471                     parent.tail_index=bone.index
472             self.__getBone(bone, c)
473
474     def __addBone(self, bone):
475         bone.index=len(self.bones)
476         self.bones.append(bone)
477         self.boneMap[bone.name]=bone.index
478
479
480 class PmdExporter(object):
481
482     def setup(self, scene):
483         # 木構造を構築する
484         object_node_map={}
485         for o in scene.objects:
486             object_node_map[o]=Node(o)
487         for node in object_node_map.values():
488             if node.o.parent:
489                 object_node_map[node.o.parent].children.append(node)
490         # ルートを得る
491         root=object_node_map[scene.objects.active]
492
493         # ワンスキンメッシュを作る
494         self.oneSkinMesh=OneSkinMesh(root)
495         print(self.oneSkinMesh)
496         self.name=root.o.name
497
498     def write(self, path):
499         io=pmd.IO()
500         io.name=self.name
501         io.comment="blender export"
502         io.version=1.0
503
504         # bones
505         builder=BoneBuilder()
506         builder.build(self.oneSkinMesh.armatureObj)
507         for b in builder.bones:
508             bone=io.addBone()
509             bone.name=b.name
510             bone.type=b.type
511             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
512             bone.tail_index=b.tail_index if b.tail_index!=None else 0
513             # ToDo
514             bone.ik_index=0xFFFF
515             # convert right-handed z-up to left-handed y-up
516             bone.pos.x=b.pos[0]
517             bone.pos.y=b.pos[2]
518             bone.pos.z=b.pos[1]
519
520         # 頂点
521         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
522             # convert right-handed z-up to left-handed y-up
523             v=io.addVertex()
524             v.pos.x=pos[0]
525             v.pos.y=pos[2]
526             v.pos.z=pos[1]
527             v.normal.x=normal[0]
528             v.normal.y=normal[2]
529             v.normal.z=normal[1]
530             v.uv.x=uv[0]
531             v.uv.y=uv[1]
532             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
533             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
534             v.weight0=int(100*weight)
535             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
536
537         # 面とマテリアル
538         vertexCount=self.oneSkinMesh.getVertexCount()
539         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
540             m=Blender.Material.Get(m)
541             # マテリアル
542             material=io.addMaterial()
543             material.diffuse.r=m.R
544             material.diffuse.g=m.G
545             material.diffuse.b=m.B
546             material.diffuse.a=m.alpha
547             material.sinness=m.spec
548             material.specular.r=m.specR
549             material.specular.g=m.specG
550             material.specular.b=m.specB
551             material.ambient.r=m.amb
552             material.ambient.g=m.amb
553             material.ambient.b=m.amb
554             material.vertex_count=len(indices)
555             material.toon_index=0
556             # ToDo
557             material.texture=""
558             # 面
559             for i in indices:
560                 assert(i<vertexCount)
561             for i in xrange(0, len(indices), 3):
562                 # reverse triangle
563                 io.indices.append(indices[i+2])
564                 io.indices.append(indices[i+1])
565                 io.indices.append(indices[i])
566
567                 #io.indices.append(indices[i])
568                 #io.indices.append(indices[i+1])
569                 #io.indices.append(indices[i+2])
570
571         # 表情
572         for m in self.oneSkinMesh.morphList:
573             # morph
574             morph=io.addMorph()
575             morph.name=m.name
576             morph.type=m.type
577             for index, offset in zip(m.indices, m.offsets):
578                 # convert right-handed z-up to left-handed y-up
579                 morph.append(index, offset[0], offset[2], offset[1])
580             morph.vertex_count=len(m.indices)
581
582         # 書き込み
583         return io.write(path.encode(FS_ENCODING))
584
585
586 def export_pmd(filename):
587     filename=filename.decode(INTERNAL_ENCODING)
588
589     Blender.Window.WaitCursor(1) 
590     t = Blender.sys.time() 
591
592     if not filename.lower().endswith(EXTENSION):
593         filename += EXTENSION
594     print "pmd exporter: %s" % filename
595
596     exporter=PmdExporter()
597
598     # 情報収集
599     exporter.setup(Blender.Scene.GetCurrent())
600
601     # 出力
602     exporter.write(filename)
603
604     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
605     Blender.Redraw()
606     Blender.Window.WaitCursor(0) 
607  
608
609 Blender.Window.FileSelector(
610         export_pmd,
611         'Export Metasequoia PMD',
612         Blender.sys.makename(ext=EXTENSION))
613