OSDN Git Service

fix bone group name.
[meshio/meshio.git] / swig / blender / 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__= "1.2"
11 __url__=()
12 __bpydoc__="""
13 pmd Importer
14
15 This script exports a pmd model.
16
17 0.1 20100318: first implementation.
18 0.2 20100519: refactoring. use C extension.
19 1.0 20100530: implement basic features.
20 1.1 20100612: integrate 2.4 and 2.5.
21 1.2 20100616: implement rigid body.
22 1.3 20100619: fix rigid body, bone weight.
23 1.4 20100626: refactoring.
24 1.5 20100629: sphere map.
25 """
26
27 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
28 BASE_SHAPE_NAME='Basis'
29 RIGID_SHAPE_TYPE='rigid_shape_type'
30 RIGID_PROCESS_TYPE='rigid_process_type'
31 RIGID_BONE_NAME='rigid_bone_name'
32 #RIGID_LOCATION='rigid_loation'
33 RIGID_GROUP='ribid_group'
34 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
35 RIGID_WEIGHT='rigid_weight'
36 RIGID_LINEAR_DAMPING='rigid_linear_damping'
37 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
38 RIGID_RESTITUTION='rigid_restitution'
39 RIGID_FRICTION='rigid_friction'
40 CONSTRAINT_NAME='constraint_name'
41 CONSTRAINT_A='const_a'
42 CONSTRAINT_B='const_b'
43 CONSTRAINT_POS_MIN='const_pos_min'
44 CONSTRAINT_POS_MAX='const_pos_max'
45 CONSTRAINT_ROT_MIN='const_rot_min'
46 CONSTRAINT_ROT_MAX='const_rot_max'
47 CONSTRAINT_SPRING_POS='const_spring_pos'
48 CONSTRAINT_SPRING_ROT='const_spring_rot'
49
50
51 ###############################################################################
52 # import
53 ###############################################################################
54 import os
55 import sys
56
57 # C extension
58 from meshio import pmd, englishmap
59
60 def isBlender24():
61     return sys.version_info[0]<3
62
63 if isBlender24():
64     # for 2.4
65     import Blender
66     from Blender import Mathutils
67     import bpy
68
69     # wrapper
70     import bl24 as bl
71
72     def setMaterialParams(material, m):
73         # diffuse
74         material.diffuse.r=m.R
75         material.diffuse.g=m.G
76         material.diffuse.b=m.B
77         material.diffuse.a=m.alpha
78         # specular
79         material.sinness=0 if m.spec<1e-5 else m.spec*10
80         material.specular.r=m.specR
81         material.specular.g=m.specG
82         material.specular.b=m.specB
83         # ambient
84         material.ambient.r=m.mirR
85         material.ambient.g=m.mirG
86         material.ambient.b=m.mirB
87         # flag
88         material.flag=1 if m.enableSSS else 0
89
90     def toCP932(s):
91         return s
92
93
94 else:
95     # for 2.5
96     import bpy
97     from bpy.props import *
98     import mathutils
99
100     # wrapper
101     import bl25 as bl
102
103     xrange=range
104
105     def setMaterialParams(material, m):
106         # diffuse
107         material.diffuse.r=m.diffuse_color[0]
108         material.diffuse.g=m.diffuse_color[1]
109         material.diffuse.b=m.diffuse_color[2]
110         material.diffuse.a=m.alpha
111         # specular
112         material.sinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
113         material.specular.r=m.specular_color[0]
114         material.specular.g=m.specular_color[1]
115         material.specular.b=m.specular_color[2]
116         # ambient
117         material.ambient.r=m.mirror_color[0]
118         material.ambient.g=m.mirror_color[1]
119         material.ambient.b=m.mirror_color[2]
120         # flag
121         material.flag=1 if m.subsurface_scattering.enabled else 0
122         # toon
123         material.toon_index=7
124
125     def toCP932(s):
126         return s.encode('cp932')
127
128
129 class Node(object):
130     __slots__=['o', 'children']
131     def __init__(self, o):
132         self.o=o
133         self.children=[]
134
135
136 ###############################################################################
137 # Blenderのメッシュをワンスキンメッシュ化する
138 ###############################################################################
139 def near(x, y, EPSILON=1e-5):
140     d=x-y
141     return d>=-EPSILON and d<=EPSILON
142
143
144 class VertexKey(object):
145     """
146     重複頂点の検索キー
147     """
148     __slots__=[
149             'obj', 'index',
150             'x', 'y', 'z', # 位置
151             'nx', 'ny', 'nz', # 法線
152             'u', 'v', # uv
153             ]
154
155     def __init__(self, obj, index, x, y, z, nx, ny, nz, u, v):
156         self.obj=obj
157         self.index=index
158         self.x=x
159         self.y=y
160         self.z=z
161         self.nx=nx
162         self.ny=ny
163         self.nz=nz
164         self.u=u
165         self.v=v
166
167     def __str__(self):
168         return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
169                 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
170
171     def __hash__(self):
172         #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
173         return int((self.x+self.y+self.z)*100)
174
175     def __eq__(self, rhs):
176         #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)
177         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
178         #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
179         return self.obj==rhs.obj and self.index==rhs.index
180
181
182 class VertexArray(object):
183     """
184     頂点配列
185     """
186     def __init__(self):
187         # マテリアル毎に分割したインデックス配列
188         self.indexArrays={}
189         # 頂点属性
190         self.vertices=[]
191         self.normals=[]
192         self.uvs=[]
193         # skinning属性
194         self.b0=[]
195         self.b1=[]
196         self.weight=[]
197
198         self.vertexMap={}
199         self.indexMap={}
200
201     def __str__(self):
202         return "<VertexArray %d vertices, %d indexArrays>" % (
203                 len(self.vertices), len(self.indexArrays))
204
205     def zip(self):
206         return zip(
207                 self.vertices, self.normals, self.uvs,
208                 self.b0, self.b1, self.weight)
209
210     def each(self):
211         keys=[key for key in self.indexArrays.keys()]
212         keys.sort()
213         for key in keys:
214             yield(key, self.indexArrays[key])
215
216     def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
217         """
218         頂点属性からその頂点のインデックスを得る
219         """
220         key=VertexKey(
221                 obj, base_index,
222                 pos[0], pos[1], pos[2],
223                 normal[0], normal[1], normal[2],
224                 uv[0], uv[1])
225         if key in self.vertexMap:
226             # 同じ頂点を登録済み
227             index=self.vertexMap[key]
228         else:
229             index=len(self.vertices)
230             # 新規頂点
231             self.vertexMap[key]=index
232             # append...
233             self.vertices.append((pos.x, pos.y, pos.z))
234             self.normals.append((normal.x, normal.y, normal.z))
235             self.uvs.append((uv[0], uv[1]))
236             self.b0.append(b0)
237             self.b1.append(b1)
238             self.weight.append(weight0)
239             
240         # indexのマッピングを保存する
241         if not base_index in self.indexMap:
242             self.indexMap[base_index]=set()
243         self.indexMap[base_index].add(index)
244
245         assert(index<=65535)
246         return index
247
248     def getMappedIndices(self, base_index):
249         return self.indexMap[base_index]
250
251     def addTriangle(self,
252             obj, material,
253             base_index0, base_index1, base_index2,
254             pos0, pos1, pos2,
255             n0, n1, n2,
256             uv0, uv1, uv2,
257             b0_0, b0_1, b0_2,
258             b1_0, b1_1, b1_2,
259             weight0, weight1, weight2
260             ):
261         index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
262         index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
263         index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
264
265         if not material in self.indexArrays:
266             self.indexArrays[material]=[]
267         self.indexArrays[material]+=[index0, index1, index2]
268
269
270 class Morph(object):
271     __slots__=['name', 'type', 'offsets']
272     def __init__(self, name, type):
273         self.name=name
274         self.type=type
275         self.offsets=[]
276
277     def add(self, index, offset):
278         self.offsets.append((index, offset))
279
280     def sort(self):
281         if isBlender24():
282             self.offsets.sort(lambda l, r: l[0]-r[0])
283         else:
284             self.offsets.sort(key=lambda e: e[0])
285
286     def __str__(self):
287         return "<Morph %s>" % self.name
288
289 class IKSolver(object):
290     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
291     def __init__(self, target, effector, length, iterations, weight):
292         self.target=target
293         self.effector=effector
294         self.length=length
295         self.iterations=iterations
296         self.weight=weight
297
298
299 class OneSkinMesh(object):
300     __slots__=['obj_index', 'scene', 'vertexArray', 'morphList', 
301             'rigidbodies',
302             'constraints',
303             ]
304     def __init__(self, scene):
305         self.vertexArray=VertexArray()
306         self.morphList=[]
307         self.rigidbodies=[]
308         self.constraints=[]
309         self.scene=scene
310         self.obj_index=0
311
312     def __str__(self):
313         return "<OneSkinMesh %s, morph:%d>" % (
314                 self.vertexArray,
315                 len(self.morphList))
316
317     def addMesh(self, obj):
318         if bl.object.isVisible(obj):
319             return
320         if not bl.modifier.hasType(obj, 'ARMATURE'):
321             return
322         self.__mesh(obj)
323         self.__skin(obj)
324         self.__rigidbody(obj)
325         self.__constraint(obj)
326
327     def __getWeightMap(self, obj, mesh):
328         # bone weight
329         weightMap={}
330         secondWeightMap={}
331         def setWeight(i, name, w):
332             if w>0:
333                 if i in weightMap:
334                     if i in secondWeightMap:
335                         # 上位2つのweightを採用する
336                         if w<secondWeightMap[i][1]:
337                             pass
338                         elif w<weightMap[i][1]:
339                             # 2つ目を入れ替え
340                             secondWeightMap[i]=(name, w)
341                         else:
342                             # 1つ目を入れ替え
343                             weightMap[i]=(name, w)
344                     else:
345                         if w>weightMap[i][1]:
346                             # 多い方をweightMapに
347                             secondWeightMap[i]=weightMap[i]
348                             weightMap[i]=(name, w)
349                         else:
350                             secondWeightMap[i]=(name, w)
351                 else:
352                     weightMap[i]=(name, w)
353
354         if isBlender24():
355             for name in bl.object.getVertexGroupNames(obj):
356                 for i, w in mesh.getVertsFromGroup(name, 1):
357                     setWeight(i, name, w)
358         else:
359             for i, v in enumerate(mesh.verts):
360                 if len(v.groups)>0:
361                     for g in v.groups:
362                         setWeight(i, obj.vertex_groups[g.group].name, g.weight)
363                 else:
364                     setWeight(i, obj.vertex_groups[0].name, 1)
365
366         # 合計値が1になるようにする
367         for i in xrange(len(mesh.verts)):
368         #for i, name_weight in weightMap.items():
369             if i in secondWeightMap:
370                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
371             elif i in weightMap:
372                 weightMap[i]=(weightMap[i][0], 1.0)
373                 secondWeightMap[i]=("", 0)
374             else:
375                 print("no weight vertex")
376                 weightMap[i]=("", 0)
377                 secondWeightMap[i]=("", 0)
378
379         return weightMap, secondWeightMap
380
381     def __processFaces(self, mesh, weightMap, secondWeightMap):
382         # 各面の処理
383         for i, face in enumerate(mesh.faces):
384             faceVertexCount=bl.face.getVertexCount(face)
385             material=mesh.materials[bl.face.getMaterialIndex(face)]
386             v=[mesh.verts[index] for index in bl.face.getVertices(face)]
387             uv=bl.mesh.getFaceUV(
388                     mesh, i, face, bl.face.getVertexCount(face))
389             # flip triangle
390             if faceVertexCount==3:
391                 # triangle
392                 self.vertexArray.addTriangle(
393                         self.obj_index, material.name,
394                         v[2].index, 
395                         v[1].index, 
396                         v[0].index,
397                         v[2].co, 
398                         v[1].co, 
399                         v[0].co,
400                         # ToDo vertex normal
401                         #v0.no, v1.no, v2.no,
402                         bl.face.getNormal(face), 
403                         bl.face.getNormal(face), 
404                         bl.face.getNormal(face),
405                         uv[2], 
406                         uv[1], 
407                         uv[0],
408                         weightMap[v[2].index][0],
409                         weightMap[v[1].index][0],
410                         weightMap[v[0].index][0],
411                         secondWeightMap[v[2].index][0],
412                         secondWeightMap[v[1].index][0],
413                         secondWeightMap[v[0].index][0],
414                         weightMap[v[2].index][1],
415                         weightMap[v[1].index][1],
416                         weightMap[v[0].index][1]
417                         )
418             elif faceVertexCount==4:
419                 # quadrangle
420                 self.vertexArray.addTriangle(
421                         self.obj_index, material.name,
422                         v[2].index, 
423                         v[1].index, 
424                         v[0].index,
425                         v[2].co, 
426                         v[1].co, 
427                         v[0].co,
428                         #v0.no, v1.no, v2.no,
429                         bl.face.getNormal(face), 
430                         bl.face.getNormal(face), 
431                         bl.face.getNormal(face), 
432                         uv[2], 
433                         uv[1], 
434                         uv[0],
435                         weightMap[v[2].index][0],
436                         weightMap[v[1].index][0],
437                         weightMap[v[0].index][0],
438                         secondWeightMap[v[2].index][0],
439                         secondWeightMap[v[1].index][0],
440                         secondWeightMap[v[0].index][0],
441                         weightMap[v[2].index][1],
442                         weightMap[v[1].index][1],
443                         weightMap[v[0].index][1]
444                         )
445                 self.vertexArray.addTriangle(
446                         self.obj_index, material.name,
447                         v[0].index, 
448                         v[3].index, 
449                         v[2].index,
450                         v[0].co, 
451                         v[3].co, 
452                         v[2].co,
453                         #v2.no, v3.no, v0.no,
454                         bl.face.getNormal(face), 
455                         bl.face.getNormal(face), 
456                         bl.face.getNormal(face), 
457                         uv[0], 
458                         uv[3], 
459                         uv[2],
460                         weightMap[v[0].index][0],
461                         weightMap[v[3].index][0],
462                         weightMap[v[2].index][0],
463                         secondWeightMap[v[0].index][0],
464                         secondWeightMap[v[3].index][0],
465                         secondWeightMap[v[2].index][0],
466                         weightMap[v[0].index][1],
467                         weightMap[v[3].index][1],
468                         weightMap[v[2].index][1]
469                         )
470
471     def __mesh(self, obj):
472         if isBlender24():
473             pass
474         else:
475             if RIGID_SHAPE_TYPE in obj:
476                 return
477             if CONSTRAINT_A in obj:
478                 return
479
480         print("export", obj.name)
481
482         # メッシュのコピーを生成してオブジェクトの行列を適用する
483         copyMesh, copyObj=bl.object.duplicate(obj)
484         if len(copyMesh.verts)==0:
485             return
486         # apply transform
487         copyObj.scale=obj.scale
488         bpy.ops.object.scale_apply()
489         copyObj.rotation_euler=obj.rotation_euler
490         bpy.ops.object.rotation_apply()
491         copyObj.location=obj.location
492         bpy.ops.object.location_apply()
493         # apply modifier
494         for m in [m for m in copyObj.modifiers]:
495             if m.type=='SOLIDFY':
496                 continue
497             bpy.ops.object.modifier_apply(modifier=m.name)
498
499         weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
500         self.__processFaces(copyMesh, weightMap, secondWeightMap)
501
502         bl.object.delete(copyObj)
503         self.obj_index+=1
504
505     def createEmptyBasicSkin(self):
506         self.__getOrCreateMorph('base', 0)
507
508     def __skin(self, obj):
509         if not bl.object.hasShapeKey(obj):
510             return
511
512         indexRelativeMap={}
513         blenderMesh=bl.object.getData(obj)
514         baseMorph=None
515
516         # shape keys
517         vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
518
519         # base
520         used=set()
521         for b in bl.object.getShapeKeys(obj):
522             if b.name==BASE_SHAPE_NAME:
523                 baseMorph=self.__getOrCreateMorph('base', 0)
524                 basis=b
525
526                 relativeIndex=0
527                 for index in vg:
528                     v=bl.shapekey.getByIndex(b, index)
529                     pos=[v[0], v[1], v[2]]
530                     indices=self.vertexArray.getMappedIndices(index)
531                     for i in indices:
532                         if i in used:
533                             continue
534                         used.add(i)
535
536                         baseMorph.add(i, pos)
537                         indexRelativeMap[i]=relativeIndex
538                         relativeIndex+=1
539
540                 break
541         assert(basis)
542         print(basis.name, len(baseMorph.offsets))
543
544         if len(baseMorph.offsets)==0:
545             return
546
547         # shape keys
548         for b in bl.object.getShapeKeys(obj):
549             if b.name==BASE_SHAPE_NAME:
550                 continue
551
552             print(b.name)
553             morph=self.__getOrCreateMorph(b.name, 4)
554             used=set()
555             for index, src, dst in zip(
556                     xrange(len(blenderMesh.verts)),
557                     bl.shapekey.get(basis),
558                     bl.shapekey.get(b)):
559                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
560                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
561                     continue
562                 if index in vg:
563                     indices=self.vertexArray.getMappedIndices(index)
564                     for i in indices:
565                         if i in used:
566                             continue
567                         used.add(i) 
568                         morph.add(indexRelativeMap[i], offset)
569
570         # sort skinmap
571         original=self.morphList[:]
572         def getIndex(morph):
573             for i, v in enumerate(englishmap.skinMap):
574                 if v[0]==morph.name:
575                     return i
576             print(morph)
577             return len(englishmap.skinMap)
578         if isBlender24():
579             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
580         else:
581             self.morphList.sort(key=getIndex)
582
583     def __rigidbody(self, obj):
584         if isBlender24():
585             return
586         if not RIGID_SHAPE_TYPE in obj:
587             return
588         self.rigidbodies.append(obj)
589
590     def __constraint(self, obj):
591         if isBlender24():
592             return
593         if not CONSTRAINT_A in obj:
594             return
595         self.constraints.append(obj)
596
597     def __getOrCreateMorph(self, name, type):
598         for m in self.morphList:
599             if m.name==name:
600                 return m
601         m=Morph(name, type)
602         self.morphList.append(m)
603         return m
604
605     def getVertexCount(self):
606         return len(self.vertexArray.vertices)
607
608
609 class Bone(object):
610     __slots__=['index', 'name', 'ik_index',
611             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
612     def __init__(self, name, pos, tail):
613         self.index=-1
614         self.name=name
615         self.pos=pos
616         self.tail=tail
617         self.parent_index=None
618         self.tail_index=None
619         self.type=0
620         self.isConnect=False
621         self.ik_index=0
622
623     def __eq__(self, rhs):
624         return self.index==rhs.index
625
626     def __str__(self):
627         return "<Bone %s %d>" % (self.name, self.type)
628
629 class BoneBuilder(object):
630     __slots__=['bones', 'boneMap', 'ik_list', ]
631     def __init__(self):
632         self.bones=[]
633         self.boneMap={}
634         self.ik_list=[]
635
636     def build(self, armatureObj):
637         if not armatureObj:
638             return
639
640         print("gather bones")
641         armature=bl.object.getData(armatureObj)
642         for b in armature.bones.values():
643             if b.name=='center':
644                 # root bone
645                 bone=Bone(b.name, 
646                         bl.bone.getHeadLocal(b),
647                         bl.bone.getTailLocal(b))
648                 self.__addBone(bone)
649                 self.__getBone(bone, b)
650
651         for b in armature.bones.values():
652             if not b.parent and b.name!='center':
653                 # root bone
654                 bone=Bone(b.name, 
655                         bl.bone.getHeadLocal(b),
656                         bl.bone.getTailLocal(b))
657                 self.__addBone(bone)
658                 self.__getBone(bone, b)
659
660         print("check connection")
661         for b in armature.bones.values():
662             if not b.parent:
663                 self.__checkConnection(b, None)
664
665         print("gather ik")
666         pose = bl.object.getPose(armatureObj)
667         for b in pose.bones.values():
668             for c in b.constraints:
669                 if bl.constraint.isIKSolver(c):
670                     ####################
671                     # IK target
672                     ####################
673                     target=self.__boneByName(bl.constraint.ikTarget(c))
674                     target.type=2
675
676                     ####################
677                     # IK effector
678                     ####################
679                     # IK 接続先
680                     link=self.__boneByName(b.name)
681                     link.type=6
682
683                     # IK chain
684                     e=b.parent
685                     chainLength=bl.constraint.ikChainLen(c)
686                     for i in range(chainLength):
687                         # IK影響下
688                         chainBone=self.__boneByName(e.name)
689                         chainBone.type=4
690                         chainBone.ik_index=target.index
691                         e=e.parent
692                     self.ik_list.append(
693                             IKSolver(target, link, chainLength, 
694                                 int(bl.constraint.ikItration(c) * 0.1), 
695                                 bl.constraint.ikRotationWeight(c)
696                                 ))
697
698         # boneのsort
699         self._sortBy()
700         self._fix()
701         # IKのsort
702         def getIndex(ik):
703             for i, v in enumerate(englishmap.boneMap):
704                 if v[0]==ik.target.name:
705                     return i
706             return len(englishmap.boneMap)
707         if isBlender24():
708             self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
709         else:
710             self.ik_list.sort(key=getIndex)
711
712     def __checkConnection(self, b, p):
713         if bl.bone.isConnected(b):
714             parent=self.__boneByName(p.name)
715             parent.isConnect=True
716
717         for c in b.children:
718             self.__checkConnection(c, b)
719
720     def _sortBy(self):
721         """
722         boneMap順に並べ替える
723         """
724         boneMap=englishmap.boneMap
725         original=self.bones[:]
726         def getIndex(bone):
727             for i, k_v in enumerate(boneMap):
728                 if k_v[0]==bone.name:
729                     return i
730             print(bone)
731             return len(boneMap)
732
733         if isBlender24():
734             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
735         else:
736             self.bones.sort(key=getIndex)
737
738         sortMap={}
739         for i, b in enumerate(self.bones):
740             src=original.index(b)
741             sortMap[src]=i
742         for b in self.bones:
743             b.index=sortMap[b.index]
744             if b.parent_index:
745                 b.parent_index=sortMap[b.parent_index]
746             if b.tail_index:
747                 b.tail_index=sortMap[b.tail_index]
748             if b.ik_index>0:
749                 b.ik_index=sortMap[b.ik_index]
750
751     def _fix(self):
752         """
753         調整
754         """
755         for b in self.bones:
756             # parent index
757             if b.parent_index==None:
758                 b.parent_index=0xFFFF
759             else:
760                 if b.type==6 or b.type==7:
761                     # fix tail bone
762                     parent=self.bones[b.parent_index]
763                     parent.tail_index=b.index
764
765         for b in self.bones:
766             if b.tail_index==None:
767                 b.tail_index=0
768             elif b.type==9:
769                 b.tail_index==0
770
771     def getIndex(self, bone):
772         for i, b in enumerate(self.bones):
773             if b==bone:
774                 return i
775         assert(false)
776
777     def indexByName(self, name):
778         if name=='':
779             return 0
780         else:
781             return self.getIndex(self.__boneByName(name))
782
783     def __boneByName(self, name):
784         return self.boneMap[name]
785                     
786     def __getBone(self, parent, b):
787         if len(b.children)==0:
788             parent.type=7
789             return
790
791         for i, c in enumerate(b.children):
792             bone=Bone(c.name, 
793                     bl.bone.getHeadLocal(c),
794                     bl.bone.getTailLocal(c))
795             self.__addBone(bone)
796             if parent:
797                 bone.parent_index=parent.index
798                 if i==0:
799                     parent.tail_index=bone.index
800             self.__getBone(bone, c)
801
802     def __addBone(self, bone):
803         bone.index=len(self.bones)
804         self.bones.append(bone)
805         self.boneMap[bone.name]=bone
806
807
808 class PmdExporter(object):
809
810     def setup(self, scene):
811         self.armatureObj=None
812         self.scene=scene
813
814         # 木構造を構築する
815         object_node_map={}
816         for o in scene.objects:
817             object_node_map[o]=Node(o)
818         for o in scene.objects:
819         #for node in object_node_map.values():
820             node=object_node_map[o]
821             if node.o.parent:
822                 object_node_map[node.o.parent].children.append(node)
823
824         # ルートを得る
825         root=object_node_map[scene.objects.active]
826
827         # ワンスキンメッシュを作る
828         self.oneSkinMesh=OneSkinMesh(scene)
829         self.__createOneSkinMesh(root)
830         print(self.oneSkinMesh)
831         if len(self.oneSkinMesh.morphList)==0:
832             # create emtpy skin
833             self.oneSkinMesh.createEmptyBasicSkin()
834
835         self.name=root.o.name
836
837         # skeleton
838         self.builder=BoneBuilder()
839         self.builder.build(self.armatureObj)
840
841     def __createOneSkinMesh(self, node):
842         ############################################################
843         # search armature modifier
844         ############################################################
845         for m in node.o.modifiers:
846             if bl.modifier.isType(m, 'ARMATURE'):
847                 armatureObj=bl.modifier.getArmatureObject(m)
848                 if not self.armatureObj:
849                     self.armatureObj=armatureObj
850                 elif self.armatureObj!=armatureObj:
851                     print("warning! found multiple armature. ignored.", 
852                             armatureObj.name)
853
854         if node.o.type.upper()=='MESH':
855             self.oneSkinMesh.addMesh(node.o)
856
857         for child in node.children:
858             self.__createOneSkinMesh(child)
859
860     def write(self, path):
861         io=pmd.IO()
862         io.name=self.name
863         io.comment="blender export"
864         io.version=1.0
865
866         # 頂点
867         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
868             # convert right-handed z-up to left-handed y-up
869             v=io.addVertex()
870             v.pos.x=pos[0]
871             v.pos.y=pos[2]
872             v.pos.z=pos[1]
873             v.normal.x=normal[0]
874             v.normal.y=normal[2]
875             v.normal.z=normal[1]
876             v.uv.x=uv[0]
877             v.uv.y=1.0-uv[1] # reverse vertical
878             v.bone0=self.builder.indexByName(b0)
879             v.bone1=self.builder.indexByName(b1)
880             v.weight0=int(100*weight)
881             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
882
883         # 面とマテリアル
884         vertexCount=self.oneSkinMesh.getVertexCount()
885         for material_name, indices in self.oneSkinMesh.vertexArray.each():
886             print('material:', material_name)
887             m=bl.material.get(material_name)
888             # マテリアル
889             material=io.addMaterial()
890             setMaterialParams(material, m)
891
892             material.vertex_count=len(indices)
893             material.toon_index=0
894             textures=[os.path.basename(path) 
895                 for path in bl.material.eachTexturePath(m)]
896             if len(textures)>0:
897                 material.setTexture(toCP932('*'.join(textures)))
898             else:
899                 material.setTexture(toCP932(""))
900             # 面
901             for i in indices:
902                 assert(i<vertexCount)
903             for i in xrange(0, len(indices), 3):
904                 # reverse triangle
905                 io.indices.append(indices[i])
906                 io.indices.append(indices[i+1])
907                 io.indices.append(indices[i+2])
908
909         # bones
910         boneNameMap={}
911         for i, b in enumerate(self.builder.bones):
912             bone=io.addBone()
913
914             # name
915             boneNameMap[b.name]=i
916             v=englishmap.getUnicodeBoneName(b.name)
917             if not v:
918                 v=[b.name, b.name]
919             assert(v)
920             cp932=v[1].encode('cp932')
921             assert(len(cp932)<20)
922             bone.setName(cp932)
923
924             # english name
925             bone_english_name=toCP932(b.name)
926             assert(len(bone_english_name)<20)
927             bone.setEnglishName(bone_english_name)
928
929             if len(v)>=3:
930                 # has type
931                 if v[2]==5:
932                     b.ik_index=self.builder.indexByName('eyes')
933                 bone.type=v[2]
934             else:
935                 bone.type=b.type
936
937             bone.parent_index=b.parent_index
938             bone.tail_index=b.tail_index
939             bone.ik_index=b.ik_index
940
941             # convert right-handed z-up to left-handed y-up
942             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
943             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
944             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
945
946         # IK
947         for ik in self.builder.ik_list:
948             solver=io.addIK()
949             solver.index=self.builder.getIndex(ik.target)
950             solver.target=self.builder.getIndex(ik.effector)
951             solver.length=ik.length
952             b=self.builder.bones[ik.effector.parent_index]
953             for i in xrange(solver.length):
954                 solver.children.append(self.builder.getIndex(b))
955                 b=self.builder.bones[b.parent_index]
956             solver.iterations=ik.iterations
957             solver.weight=ik.weight
958
959         # 表情
960         for i, m in enumerate(self.oneSkinMesh.morphList):
961             # morph
962             morph=io.addMorph()
963
964             v=englishmap.getUnicodeSkinName(m.name)
965             if not v:
966                 v=[m.name, m.name, 0]
967             assert(v)
968             cp932=v[1].encode('cp932')
969             morph.setName(cp932)
970             morph.setEnglishName(m.name.encode('cp932'))
971             m.type=v[2]
972             morph.type=v[2]
973             for index, offset in m.offsets:
974                 # convert right-handed z-up to left-handed y-up
975                 morph.append(index, offset[0], offset[2], offset[1])
976             morph.vertex_count=len(m.offsets)
977
978         # 表情枠
979         # type==0はbase
980         for i, m in enumerate(self.oneSkinMesh.morphList):
981             if m.type==3:
982                 io.face_list.append(i)
983         for i, m in enumerate(self.oneSkinMesh.morphList):
984             if m.type==2:
985                 io.face_list.append(i)
986         for i, m in enumerate(self.oneSkinMesh.morphList):
987             if m.type==1:
988                 io.face_list.append(i)
989         for i, m in enumerate(self.oneSkinMesh.morphList):
990             if m.type==4:
991                 io.face_list.append(i)
992
993         # ボーン表示枠
994         def createBoneDisplayName(name, english):
995             boneDisplayName=io.addBoneGroup()
996             if isBlender24():
997                 boneDisplayName.name=name.decode('utf-8').encode('cp932')
998                 boneDisplayName.english_name=english
999             else:
1000                 boneDisplayName.setName(name.encode('cp932'))
1001                 boneDisplayName.setEnglishName(english.encode('cp932'))
1002         boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
1003         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
1004         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
1005         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
1006         boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
1007         boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
1008         boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
1009         for i, b in enumerate(self.builder.bones):
1010             if i==0:
1011                 continue
1012             if b.type in [6, 7]:
1013                 continue
1014             io.addBoneDisplay(i, getBoneDisplayGroup(b))
1015
1016         # English
1017         io.english_name="blender export"
1018         io.english_coment="blender export"
1019
1020         # toon
1021         for i in range(10):
1022             io.getToonTexture(i).name="toon%02d.bmp\n" % i
1023
1024         # rigid body
1025         rigidNameMap={}
1026         for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1027             rigidBody=io.addRigidBody()
1028             rigidBody.setName(obj.name.encode('cp932'))
1029             rigidNameMap[obj.name]=i
1030             boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1031             if boneIndex==0:
1032                 boneIndex=0xFFFF
1033                 bone=self.builder.bones[0]
1034             else:
1035                 bone=self.builder.bones[boneIndex]
1036             rigidBody.boneIndex=boneIndex
1037             #rigidBody.position.x=obj[RIGID_LOCATION][0]
1038             #rigidBody.position.y=obj[RIGID_LOCATION][1]
1039             #rigidBody.position.z=obj[RIGID_LOCATION][2]
1040             rigidBody.position.x=obj.location.x-bone.pos[0]
1041             rigidBody.position.y=obj.location.z-bone.pos[2]
1042             rigidBody.position.z=obj.location.y-bone.pos[1]
1043             rigidBody.rotation.x=-obj.rotation_euler[0]
1044             rigidBody.rotation.y=-obj.rotation_euler[2]
1045             rigidBody.rotation.z=-obj.rotation_euler[1]
1046             rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1047             rigidBody.group=obj[RIGID_GROUP]
1048             rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1049             rigidBody.weight=obj[RIGID_WEIGHT]
1050             rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1051             rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1052             rigidBody.restitution=obj[RIGID_RESTITUTION]
1053             rigidBody.friction=obj[RIGID_FRICTION]
1054             if obj[RIGID_SHAPE_TYPE]==0:
1055                 rigidBody.shapeType=pmd.SHAPE_SPHERE
1056                 rigidBody.w=obj.scale[0]
1057             elif obj[RIGID_SHAPE_TYPE]==1:
1058                 rigidBody.shapeType=pmd.SHAPE_BOX
1059                 rigidBody.w=obj.scale[0]
1060                 rigidBody.d=obj.scale[1]
1061                 rigidBody.h=obj.scale[2]
1062             elif obj[RIGID_SHAPE_TYPE]==2:
1063                 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1064                 rigidBody.w=obj.scale[0]
1065                 rigidBody.h=obj.scale[2]
1066
1067         # constraint
1068         for obj in self.oneSkinMesh.constraints:
1069             constraint=io.addConstraint()
1070             constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1071             constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1072             constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1073             constraint.pos.x=obj.location[0]
1074             constraint.pos.y=obj.location[2]
1075             constraint.pos.z=obj.location[1]
1076             constraint.rot.x=-obj.rotation_euler[0]
1077             constraint.rot.y=-obj.rotation_euler[2]
1078             constraint.rot.z=-obj.rotation_euler[1]
1079             constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1080             constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1081             constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1082             constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1083             constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1084             constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1085             constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1086             constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1087             constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1088             constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1089             constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1090             constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1091             constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1092             constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1093             constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1094             constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1095             constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1096             constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1097
1098         # 書き込み
1099         print('write', path)
1100         return io.write(path)
1101
1102
1103 def getBoneDisplayGroup(bone):
1104     boneGroups=[
1105             [ # IK
1106                 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
1107                 "toe IK_L", "toe IK_R", 
1108                 ],
1109             [ # 体(上)
1110                 "upper body", "neck", "head", "eye_L", "eye_R",
1111                 "necktie1", "necktie2", "necktie3", "eyes", 
1112                 "eyelight_L", "eyelight_R",
1113                 ],
1114             [ # 髪
1115                 "front hair1", "front hair2", "front hair3",
1116                 "hair1_L", "hair2_L", "hair3_L", 
1117                 "hair4_L", "hair5_L", "hair6_L",
1118                 "hair1_R", "hair2_R", "hair3_R", 
1119                 "hair4_R", "hair5_R", "hair6_R",
1120                 ],
1121             [ # 腕
1122                 "shoulder_L", "arm_L", "arm twist_L", "elbow_L", 
1123                 "wrist twist_L", "wrist_L", "sleeve_L", 
1124                 "shoulder_R", "arm_R", "arm twist_R", "elbow_R", 
1125                 "wrist twist_R", "wrist_R", "sleeve_R", 
1126                 ],
1127             [ # 指
1128                 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
1129                 "middle1_L", "middle2_L", "middle3_L",
1130                 "third1_L", "third2_L", "third3_L",
1131                 "little1_L", "little2_L", "little3_L",
1132                 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
1133                 "middle1_R", "middle2_R", "middle3_R",
1134                 "third1_R", "third2_R", "third3_R",
1135                 "little1_R", "little2_R", "little3_R",
1136                 ],
1137             [ # 体(下)
1138                 "lower body",  "waist accessory", 
1139                 "front skirt_L", "back skirt_L",
1140                 "front skirt_R", "back skirt_R",
1141                 ],
1142             [ # 足
1143                 "leg_L", "knee_L", "ankle_L",
1144                 "leg_R", "knee_R", "ankle_R",
1145                 ],
1146             ]
1147     index=1
1148     for g in boneGroups:
1149         if bone.name in g:
1150             return index
1151         index+=1
1152     print(bone)
1153     return 0
1154
1155
1156 def __execute(filename, scene):
1157     if not scene.objects.active:
1158         print("abort. no active object.")
1159         return
1160
1161     active=bl.object.getActive()
1162     exporter=PmdExporter()
1163     exporter.setup(scene)
1164     exporter.write(filename)
1165     bl.object.activate(active)
1166
1167
1168 if isBlender24():
1169     # for 2.4
1170     def execute_24(filename):
1171         scene = bpy.data.scenes.active
1172         bl.initialize('pmd_export', scene)
1173         __execute(filename.decode(bl.INTERNAL_ENCODING), scene)
1174         bl.finalize()
1175
1176     Blender.Window.FileSelector(
1177              execute_24,
1178              'Export Metasequoia PMD',
1179              Blender.sys.makename(ext='.pmd'))
1180
1181 else:
1182     # for 2.5
1183     def execute_25(filename, scene):
1184         bl.initialize('pmd_export', scene)
1185         __execute(filename, scene)
1186         bl.finalize()
1187
1188     # operator
1189     class EXPORT_OT_pmd(bpy.types.Operator):
1190         '''Save a Metasequoia PMD file.'''
1191         bl_idname = "export_scene.pmd"
1192         bl_label = 'Export PMD'
1193
1194         # List of operator properties, the attributes will be assigned
1195         # to the class instance from the operator settings before calling.
1196
1197         path = StringProperty(
1198                 name="File Path",
1199                 description="File path used for exporting the PMD file",
1200                 maxlen= 1024,
1201                 default= ""
1202                 )
1203         filename = StringProperty(
1204                 name="File Name", 
1205                 description="Name of the file.")
1206         directory = StringProperty(
1207                 name="Directory", 
1208                 description="Directory of the file.")
1209
1210         check_existing = BoolProperty(
1211                 name="Check Existing",
1212                 description="Check and warn on overwriting existing files",
1213                 default=True,
1214                 options=set('HIDDEN'))
1215
1216         def execute(self, context):
1217             execute_25(
1218                     self.properties.path, 
1219                     context.scene
1220                     )
1221             return 'FINISHED'
1222
1223         def invoke(self, context, event):
1224             wm=context.manager
1225             wm.add_fileselect(self)
1226             return 'RUNNING_MODAL'
1227
1228     # register menu
1229     def menu_func(self, context): 
1230         #default_path=bpy.data.filename.replace(".blend", ".pmd")
1231         self.layout.operator(
1232                 EXPORT_OT_pmd.bl_idname, 
1233                 text="Miku Miku Dance Model(.pmd)")#.path=default_path
1234
1235     def register():
1236         bpy.types.register(EXPORT_OT_pmd)
1237         bpy.types.INFO_MT_file_export.append(menu_func)
1238
1239     def unregister():
1240         bpy.types.unregister(EXPORT_OT_pmd)
1241         bpy.types.INFO_MT_file_export.remove(menu_func)
1242
1243     if __name__ == "__main__":
1244         register()
1245