OSDN Git Service

add none terminate IK tail.
[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
176 class IKSolver(object):
177     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
178     def __init__(self, target, effector, length, iterations, weight):
179         self.target=target
180         self.effector=effector
181         self.length=length
182         self.iterations=iterations
183         self.weight=weight
184
185
186 class OneSkinMesh(object):
187     __slots__=['armatureObj', 'vertexArray', 'morphList']
188     def __init__(self, root):
189         self.armatureObj=None
190         self.vertexArray=VertexArray()
191         self.morphList=[]
192         self.__create(root)
193
194     def __str__(self):
195         return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
196                 self.armatureObj.name if self.armatureObj else None, 
197                 self.vertexArray,
198                 len(self.morphList))
199
200     def __create(self, node):
201         if node.o.getType()=='Mesh':
202             self.__addMesh(node.o)
203
204         for child in node.children:
205             self.__create(child)
206
207     def __addMesh(self, obj):
208         if obj.restrictDisplay:
209             # 非表示
210             return
211
212         print("export", obj.name)
213
214         ############################################################
215         # search armature modifier
216         ############################################################
217         for m in obj.modifiers:
218             if m.name=="Armature":
219                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
220                 if not self.armatureObj:
221                     self.armatureObj=armatureObj
222                 elif self.armatureObj!=armatureObj:
223                     print "warning! found multiple armature. ignored.", armatureObj.name
224
225         ############################################################
226         # bone weight
227         ############################################################
228         mesh=obj.getData(mesh=True)
229         weightMap={}
230         secondWeightMap={}
231         for name in mesh.getVertGroupNames():
232             for i, w in mesh.getVertsFromGroup(name, 1):
233                 if w>0:
234                     if i in weightMap:
235                         if i in secondWeightMap:
236                             # 上位2つのweightを採用する
237                             if w<secondWeightMap[i]:
238                                 pass
239                             elif w<weightMap[i]:
240                                 # 2つ目を入れ替え
241                                 secondWeightMap[i]=(name, w)
242                             else:
243                                 # 1つ目を入れ替え
244                                 weightMap[i]=(name, w)
245                         else:
246                             if w>weightMap[i][1]:
247                                 # 多い方をweightMapに
248                                 secondWeightMap[i]=weightMap[i]
249                                 weightMap[i]=(name, w)
250                             else:
251                                 secondWeightMap[i]=(name, w)
252                     else:
253                         weightMap[i]=(name, w)
254
255         # 合計値が1になるようにする
256         for i in xrange(len(mesh.verts)):
257         #for i, name_weight in weightMap.items():
258             if i in secondWeightMap:
259                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
260             elif i in weightMap:
261                 weightMap[i]=(weightMap[i][0], 1.0)
262                 secondWeightMap[i]=("", 0)
263             else:
264                 print "no weight vertex"
265                 weightMap[i]=("", 0)
266                 secondWeightMap[i]=("", 0)
267                 
268
269         ############################################################
270         # faces
271         # 新たにメッシュを生成する
272         ############################################################
273         mesh=Blender.Mesh.New()
274         # not applied modifiers
275         mesh.getFromObject(obj.name, 1)
276         # apply object transform
277         mesh.transform(obj.getMatrix())
278         if len(mesh.verts)==0:
279             return
280
281         for face in mesh.faces:
282             faceVertexCount=len(face.v)
283             material=mesh.materials[face.mat]
284             if faceVertexCount==3:
285                 v0=face.v[0]
286                 v1=face.v[1]
287                 v2=face.v[2]
288                 # triangle
289                 self.vertexArray.addTriangle(
290                         material.name,
291                         v0.index, v1.index, v2.index,
292                         v0.co, v1.co, v2.co,
293                         # ToDo vertex normal
294                         #v0.no, v1.no, v2.no,
295                         face.no, face.no, face.no,
296                         face.uv[0], face.uv[1], face.uv[2],
297                         weightMap[v0.index][0],
298                         weightMap[v1.index][0],
299                         weightMap[v2.index][0],
300                         secondWeightMap[v0.index][0],
301                         secondWeightMap[v1.index][0],
302                         secondWeightMap[v2.index][0],
303                         weightMap[v0.index][1],
304                         weightMap[v1.index][1],
305                         weightMap[v2.index][1]
306                         )
307             elif faceVertexCount==4:
308                 v0=face.v[0]
309                 v1=face.v[1]
310                 v2=face.v[2]
311                 v3=face.v[3]
312                 # quadrangle
313                 self.vertexArray.addTriangle(
314                         material.name,
315                         v0.index, v1.index, v2.index,
316                         v0.co, v1.co, v2.co,
317                         #v0.no, v1.no, v2.no,
318                         face.no, face.no, face.no,
319                         face.uv[0], face.uv[1], face.uv[2],
320                         weightMap[v0.index][0],
321                         weightMap[v1.index][0],
322                         weightMap[v2.index][0],
323                         secondWeightMap[v0.index][0],
324                         secondWeightMap[v1.index][0],
325                         secondWeightMap[v2.index][0],
326                         weightMap[v0.index][1],
327                         weightMap[v1.index][1],
328                         weightMap[v2.index][1]
329                         )
330                 self.vertexArray.addTriangle(
331                         material.name,
332                         v2.index, v3.index, v0.index,
333                         v2.co, v3.co, v0.co,
334                         #v2.no, v3.no, v0.no,
335                         face.no, face.no, face.no,
336                         face.uv[2], face.uv[3], face.uv[0],
337                         weightMap[v2.index][0],
338                         weightMap[v3.index][0],
339                         weightMap[v0.index][0],
340                         secondWeightMap[v2.index][0],
341                         secondWeightMap[v3.index][0],
342                         secondWeightMap[v0.index][0],
343                         weightMap[v2.index][1],
344                         weightMap[v3.index][1],
345                         weightMap[v0.index][1]
346                         )
347
348         ############################################################
349         # skin
350         ############################################################
351         # base
352         indexRelativeMap={}
353         blenderMesh=obj.getData(mesh=True)
354         if blenderMesh.key:
355             for b in blenderMesh.key.blocks:
356                 if b.name=='Basis':
357                     print(b.name)
358                     morph=self.__getOrCreateMorph('base', 0)
359                     relativeIndex=0
360                     basis=b
361                     for index in blenderMesh.getVertsFromGroup(
362                             MMD_SHAPE_GROUP_NAME):
363                         v=b.data[index]
364                         pos=[v[0], v[1], v[2]]
365                         indices=self.vertexArray.getMappedIndices(index)
366                         for i in indices:
367                             morph.indices.append(i)
368                             morph.offsets.append(pos)
369                             indexRelativeMap[i]=relativeIndex
370                             relativeIndex+=1
371                     break
372
373             assert(basis)
374
375             # shape keys
376             for b in obj.getData(mesh=True).key.blocks:
377                 if b.name=='Basis':
378                     continue
379
380                 print(b.name)
381                 morph=self.__getOrCreateMorph(b.name, 4)
382                 for index in obj.getData(mesh=True).getVertsFromGroup(
383                         MMD_SHAPE_GROUP_NAME):
384                     #offset=[d-s for d, s in zip(
385                     #    b.data[index], basis.data[index])]
386                     src=basis.data[index]
387                     dst=b.data[index]
388                     offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
389                     indices=self.vertexArray.getMappedIndices(index)
390                     for i in indices:
391                         morph.indices.append(indexRelativeMap[i])
392                         morph.offsets.append(offset)
393
394     def __getOrCreateMorph(self, name, type):
395         for m in self.morphList:
396             if m.name==name:
397                 return m
398         m=Morph(name, type)
399         self.morphList.append(m)
400         return m
401
402     def getVertexCount(self):
403         return len(self.vertexArray.vertices)
404
405
406 class Bone(object):
407     __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
408     def __init__(self, name, pos):
409         self.index=-1
410         self.name=name
411         self.pos=[pos.x, pos.y, pos.z]
412         self.parent_index=None
413         self.tail_index=None
414         self.type=0
415
416     def __str__(self):
417         return "<Bone %s %d>" % (self.name, self.type)
418
419 class BoneBuilder(object):
420     __slots__=['bones', 'boneMap', 'ik_list']
421     def __init__(self):
422         self.bones=[]
423         self.boneMap={}
424         self.ik_list=[]
425
426     def build(self, armatureObj):
427         if armatureObj:
428             armature=armatureObj.getData()
429             for b in armature.bones.values():
430                 if b.name=='center':
431                     # root bone
432                     bone=Bone(b.name, b.head['ARMATURESPACE'])
433                     self.__addBone(bone)
434                     self.__getBone(bone, b)
435
436             for b in armature.bones.values():
437                 if not b.parent and b.name!='center':
438                     # root bone
439                     bone=Bone(b.name, b.head['ARMATURESPACE'])
440                     self.__addBone(bone)
441                     self.__getBone(bone, b)
442
443         pose = armatureObj.getPose()
444         cSetting=Blender.Constraint.Settings
445         for b in pose.bones.values():
446             for c in b.constraints:
447                 if c.type==Blender.Constraint.Type.IKSOLVER:
448                     ####################
449                     # IK effector
450                     ####################
451                     # IK 接続先
452                     link=self.__boneByName(b.name)
453                     link_tail=self.bones[link.tail_index]
454                     if link_tail.type==7:
455                         # replace ...先 to IK接続先
456                         link_tail.type=6
457
458                     # IK chain
459                     e=b
460                     chainLength=c[cSetting.CHAINLEN]
461                     for i in range(chainLength):
462                         # IK影響下
463                         self.__boneByName(e.name).type=4
464                         e=e.parent
465
466                     ####################
467                     # IK target
468                     ####################
469                     assert(c[cSetting.TARGET]==armatureObj)
470                     target=self.__boneByName(
471                             c[Blender.Constraint.Settings.BONE])
472                     target.type=2
473
474                     self.ik_list.append(
475                             IKSolver(target, link_tail, chainLength, 
476                                 c[cSetting.ITERATIONS], c.influence))
477                     # 非末端IK
478                     target_tail=self.bones[target.tail_index]
479                     if target_tail.type!=7:
480                         target_bone=armature.bones[target.name]
481                         bone=Bone(target.name+'_t', 
482                                 target_bone.tail['ARMATURESPACE'])
483                         bone.type=7
484                         self.__addBone(bone)
485                         bone.parent_index=target.index
486                         target.tail_index=bone.index
487
488     def getIndex(self, bone):
489         for i, b in enumerate(self.bones):
490             if b==bone:
491                 return i
492         assert(false)
493
494     def __boneByName(self, name):
495         return self.bones[self.boneMap[name]]
496                     
497     def __getBone(self, parent, b):
498         if not Blender.Armature.CONNECTED in b.options:
499             #print b, b.options
500             pass
501
502         if len(b.children)==0:
503             # 末端の非表示ボーン
504             bone=Bone(b.name+'_t', b.tail['ARMATURESPACE'])
505             bone.type=7
506             self.__addBone(bone)
507             assert(parent)
508             bone.parent_index=parent.index
509             parent.tail_index=bone.index
510             return
511
512         for i, c in enumerate(b.children):
513             bone=Bone(c.name, c.head['ARMATURESPACE'])
514             self.__addBone(bone)
515             if parent:
516                 bone.parent_index=parent.index
517                 if i==0:
518                     parent.tail_index=bone.index
519             self.__getBone(bone, c)
520
521     def __addBone(self, bone):
522         bone.index=len(self.bones)
523         self.bones.append(bone)
524         self.boneMap[bone.name]=bone.index
525
526
527 class PmdExporter(object):
528
529     def setup(self, scene):
530         # 木構造を構築する
531         object_node_map={}
532         for o in scene.objects:
533             object_node_map[o]=Node(o)
534         for node in object_node_map.values():
535             if node.o.parent:
536                 object_node_map[node.o.parent].children.append(node)
537         # ルートを得る
538         root=object_node_map[scene.objects.active]
539
540         # ワンスキンメッシュを作る
541         self.oneSkinMesh=OneSkinMesh(root)
542         print(self.oneSkinMesh)
543         self.name=root.o.name
544
545     def write(self, path):
546         io=pmd.IO()
547         io.name=self.name
548         io.comment="blender export"
549         io.version=1.0
550
551         # skeleton
552         builder=BoneBuilder()
553         builder.build(self.oneSkinMesh.armatureObj)
554
555         # 頂点
556         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
557             # convert right-handed z-up to left-handed y-up
558             v=io.addVertex()
559             v.pos.x=pos[0]
560             v.pos.y=pos[2]
561             v.pos.z=pos[1]
562             v.normal.x=normal[0]
563             v.normal.y=normal[2]
564             v.normal.z=normal[1]
565             v.uv.x=uv[0]
566             v.uv.y=uv[1]
567             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
568             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
569             v.weight0=int(100*weight)
570             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
571
572         # 面とマテリアル
573         vertexCount=self.oneSkinMesh.getVertexCount()
574         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
575             m=Blender.Material.Get(m)
576             # マテリアル
577             material=io.addMaterial()
578             material.diffuse.r=m.R
579             material.diffuse.g=m.G
580             material.diffuse.b=m.B
581             material.diffuse.a=m.alpha
582             material.sinness=0 if m.spec<1e-5 else m.spec*10
583             material.specular.r=m.specR
584             material.specular.g=m.specG
585             material.specular.b=m.specB
586             material.ambient.r=m.mirR
587             material.ambient.g=m.mirG
588             material.ambient.b=m.mirB
589             material.vertex_count=len(indices)
590             material.toon_index=0
591             material.flag=1 if m.enableSSS else 0
592             # ToDo
593             material.texture=""
594             # 面
595             for i in indices:
596                 assert(i<vertexCount)
597             for i in xrange(0, len(indices), 3):
598                 # reverse triangle
599                 io.indices.append(indices[i+2])
600                 io.indices.append(indices[i+1])
601                 io.indices.append(indices[i])
602
603                 #io.indices.append(indices[i])
604                 #io.indices.append(indices[i+1])
605                 #io.indices.append(indices[i+2])
606
607         # bones
608         for b in builder.bones:
609             bone=io.addBone()
610
611             unicode=englishmap.getUnicodeBoneName(b.name)
612             if unicode:
613                 cp932=unicode.encode('cp932')
614             else:
615                 cp932=b.name
616             bone_name="%s\n" % cp932
617             assert(len(bone_name)<20)
618             bone.name=bone_name
619
620             bone_english_name="%s\n" % b.name
621             assert(len(bone_english_name)<20)
622             bone.english_name=bone_english_name
623
624             bone.type=b.type
625             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
626             bone.tail_index=b.tail_index if b.tail_index!=None else 0
627             # ToDo
628             bone.ik_index=0xFFFF
629             # convert right-handed z-up to left-handed y-up
630             bone.pos.x=b.pos[0]
631             bone.pos.y=b.pos[2]
632             bone.pos.z=b.pos[1]
633
634         # IK
635         for ik in builder.ik_list:
636             solver=io.addIK()
637             solver.index=builder.getIndex(ik.target)
638             solver.target=builder.getIndex(ik.effector)
639             solver.length=ik.length
640             b=builder.bones[ik.effector.parent_index]
641             for i in xrange(solver.length):
642                 solver.children.append(builder.getIndex(b))
643                 b=builder.bones[b.parent_index]
644             solver.iterations=ik.iterations
645             solver.weight=ik.weight
646
647         # 表情
648         for i, m in enumerate(self.oneSkinMesh.morphList):
649             # morph
650             morph=io.addMorph()
651
652             unicode=englishmap.getUnicodeSkinName(m.name)
653             if unicode:
654                 cp932=unicode.encode('cp932')
655             else:
656                 cp932=m.name
657             morph.name="%s\n" % cp932
658
659             morph.english_name="%s\n" % m.name
660             morph.type=m.type
661             for index, offset in zip(m.indices, m.offsets):
662                 # convert right-handed z-up to left-handed y-up
663                 morph.append(index, offset[0], offset[2], offset[1])
664             morph.vertex_count=len(m.indices)
665
666             # 表情枠
667             if i>0:
668                 io.face_list.append(i)
669
670         # ボーン表示枠
671         boneDisplayName=io.addBoneDisplayName()
672         boneDisplayName.name="bones\n"
673         boneDisplayName.english_name="bones\n"
674         displayIndex=1
675         for i, b in enumerate(builder.bones):
676             if b.type in [6, 7]:
677                 io.addBoneDisplay(i, displayIndex)
678
679         # English
680         io.english_name="blender export"
681         io.english_coment="blender export"
682
683         for i in range(10):
684             io.getToonTexture(i).name="toon%02d.bmp\n" % i
685
686         # 書き込み
687         return io.write(path.encode(FS_ENCODING))
688
689
690 def export_pmd(filename):
691     filename=filename.decode(INTERNAL_ENCODING)
692
693     Blender.Window.WaitCursor(1) 
694     t = Blender.sys.time() 
695
696     if not filename.lower().endswith(EXTENSION):
697         filename += EXTENSION
698     print "pmd exporter: %s" % filename
699
700     exporter=PmdExporter()
701
702     # 情報収集
703     exporter.setup(Blender.Scene.GetCurrent())
704
705     # 出力
706     exporter.write(filename)
707
708     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
709     Blender.Redraw()
710     Blender.Window.WaitCursor(0) 
711  
712
713 Blender.Window.FileSelector(
714         export_pmd,
715         'Export Metasequoia PMD',
716         Blender.sys.makename(ext=EXTENSION))
717