OSDN Git Service

update bone group export.
[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         bl.message("export: %s" % 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             elif m.type=='ARMATURE':
498                 continue
499             elif m.type=='MIRROR':
500                 bpy.ops.object.modifier_apply(modifier=m.name)
501             else:
502                 print(m.tpye)
503
504         weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
505         self.__processFaces(copyMesh, weightMap, secondWeightMap)
506
507         bl.object.delete(copyObj)
508         self.obj_index+=1
509
510     def createEmptyBasicSkin(self):
511         self.__getOrCreateMorph('base', 0)
512
513     def __skin(self, obj):
514         if not bl.object.hasShapeKey(obj):
515             return
516
517         indexRelativeMap={}
518         blenderMesh=bl.object.getData(obj)
519         baseMorph=None
520
521         # shape keys
522         vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
523
524         # base
525         used=set()
526         for b in bl.object.getShapeKeys(obj):
527             if b.name==BASE_SHAPE_NAME:
528                 baseMorph=self.__getOrCreateMorph('base', 0)
529                 basis=b
530
531                 relativeIndex=0
532                 for index in vg:
533                     v=bl.shapekey.getByIndex(b, index)
534                     pos=[v[0], v[1], v[2]]
535                     indices=self.vertexArray.getMappedIndices(index)
536                     for i in indices:
537                         if i in used:
538                             continue
539                         used.add(i)
540
541                         baseMorph.add(i, pos)
542                         indexRelativeMap[i]=relativeIndex
543                         relativeIndex+=1
544
545                 break
546         assert(basis)
547         print(basis.name, len(baseMorph.offsets))
548
549         if len(baseMorph.offsets)==0:
550             return
551
552         # shape keys
553         for b in bl.object.getShapeKeys(obj):
554             if b.name==BASE_SHAPE_NAME:
555                 continue
556
557             print(b.name)
558             morph=self.__getOrCreateMorph(b.name, 4)
559             used=set()
560             for index, src, dst in zip(
561                     xrange(len(blenderMesh.verts)),
562                     bl.shapekey.get(basis),
563                     bl.shapekey.get(b)):
564                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
565                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
566                     continue
567                 if index in vg:
568                     indices=self.vertexArray.getMappedIndices(index)
569                     for i in indices:
570                         if i in used:
571                             continue
572                         used.add(i) 
573                         morph.add(indexRelativeMap[i], offset)
574
575         # sort skinmap
576         original=self.morphList[:]
577         def getIndex(morph):
578             for i, v in enumerate(englishmap.skinMap):
579                 if v[0]==morph.name:
580                     return i
581             print(morph)
582             return len(englishmap.skinMap)
583         if isBlender24():
584             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
585         else:
586             self.morphList.sort(key=getIndex)
587
588     def __rigidbody(self, obj):
589         if isBlender24():
590             return
591         if not RIGID_SHAPE_TYPE in obj:
592             return
593         self.rigidbodies.append(obj)
594
595     def __constraint(self, obj):
596         if isBlender24():
597             return
598         if not CONSTRAINT_A in obj:
599             return
600         self.constraints.append(obj)
601
602     def __getOrCreateMorph(self, name, type):
603         for m in self.morphList:
604             if m.name==name:
605                 return m
606         m=Morph(name, type)
607         self.morphList.append(m)
608         return m
609
610     def getVertexCount(self):
611         return len(self.vertexArray.vertices)
612
613
614 class Bone(object):
615     __slots__=['index', 'name', 'ik_index',
616             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
617     def __init__(self, name, pos, tail):
618         self.index=-1
619         self.name=name
620         self.pos=pos
621         self.tail=tail
622         self.parent_index=None
623         self.tail_index=None
624         self.type=0
625         self.isConnect=False
626         self.ik_index=0
627
628     def __eq__(self, rhs):
629         return self.index==rhs.index
630
631     def __str__(self):
632         return "<Bone %s %d>" % (self.name, self.type)
633
634 class BoneBuilder(object):
635     __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
636     def __init__(self):
637         self.bones=[]
638         self.boneMap={}
639         self.ik_list=[]
640         self.bone_groups=[]
641
642     def getBoneGroup(self, bone):
643         for i, g in enumerate(self.bone_groups):
644             for b in g[1]:
645                 if b==bone.name:
646                     return i
647         print('no gorup', bone)
648         return 0
649
650     def build(self, armatureObj):
651         if not armatureObj:
652             return
653
654         bl.message("build skeleton")
655         armature=bl.object.getData(armatureObj)
656
657         ####################
658         # bone group
659         ####################
660         for g in bl.object.boneGroups(armatureObj):
661             self.bone_groups.append((g.name, []))
662
663         ####################
664         # get bones
665         ####################
666         for b in armature.bones.values():
667             if b.name=='center':
668                 # root bone
669                 bone=Bone(b.name, 
670                         bl.bone.getHeadLocal(b),
671                         bl.bone.getTailLocal(b))
672                 self.__addBone(bone)
673                 self.__getBone(bone, b)
674
675         for b in armature.bones.values():
676             if not b.parent and b.name!='center':
677                 # root bone
678                 bone=Bone(b.name, 
679                         bl.bone.getHeadLocal(b),
680                         bl.bone.getTailLocal(b))
681                 self.__addBone(bone)
682                 self.__getBone(bone, b)
683
684         for b in armature.bones.values():
685             if not b.parent:
686                 self.__checkConnection(b, None)
687
688         ####################
689         # get IK
690         ####################
691         pose = bl.object.getPose(armatureObj)
692         for b in pose.bones.values():
693             ####################
694             # assing bone group
695             ####################
696             self.__assignBoneGroup(b, b.bone_group)
697             for c in b.constraints:
698                 if bl.constraint.isIKSolver(c):
699                     ####################
700                     # IK target
701                     ####################
702                     target=self.__boneByName(bl.constraint.ikTarget(c))
703                     target.type=2
704
705                     ####################
706                     # IK effector
707                     ####################
708                     # IK 接続先
709                     link=self.__boneByName(b.name)
710                     link.type=6
711
712                     # IK chain
713                     e=b.parent
714                     chainLength=bl.constraint.ikChainLen(c)
715                     for i in range(chainLength):
716                         # IK影響下
717                         chainBone=self.__boneByName(e.name)
718                         chainBone.type=4
719                         chainBone.ik_index=target.index
720                         e=e.parent
721                     self.ik_list.append(
722                             IKSolver(target, link, chainLength, 
723                                 int(bl.constraint.ikItration(c) * 0.1), 
724                                 bl.constraint.ikRotationWeight(c)
725                                 ))
726
727         ####################
728
729         # boneのsort
730         self._sortBy()
731         self._fix()
732         # IKのsort
733         def getIndex(ik):
734             for i, v in enumerate(englishmap.boneMap):
735                 if v[0]==ik.target.name:
736                     return i
737             return len(englishmap.boneMap)
738         if isBlender24():
739             self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
740         else:
741             self.ik_list.sort(key=getIndex)
742
743     def __assignBoneGroup(self, poseBone, boneGroup):
744         if boneGroup:
745             for g in self.bone_groups:
746                 if g[0]==boneGroup.name:
747                     g[1].append(poseBone.name)
748
749     def __checkConnection(self, b, p):
750         if bl.bone.isConnected(b):
751             parent=self.__boneByName(p.name)
752             parent.isConnect=True
753
754         for c in b.children:
755             self.__checkConnection(c, b)
756
757     def _sortBy(self):
758         """
759         boneMap順に並べ替える
760         """
761         boneMap=englishmap.boneMap
762         original=self.bones[:]
763         def getIndex(bone):
764             for i, k_v in enumerate(boneMap):
765                 if k_v[0]==bone.name:
766                     return i
767             print(bone)
768             return len(boneMap)
769
770         if isBlender24():
771             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
772         else:
773             self.bones.sort(key=getIndex)
774
775         sortMap={}
776         for i, b in enumerate(self.bones):
777             src=original.index(b)
778             sortMap[src]=i
779         for b in self.bones:
780             b.index=sortMap[b.index]
781             if b.parent_index:
782                 b.parent_index=sortMap[b.parent_index]
783             if b.tail_index:
784                 b.tail_index=sortMap[b.tail_index]
785             if b.ik_index>0:
786                 b.ik_index=sortMap[b.ik_index]
787
788     def _fix(self):
789         """
790         調整
791         """
792         for b in self.bones:
793             # parent index
794             if b.parent_index==None:
795                 b.parent_index=0xFFFF
796             else:
797                 if b.type==6 or b.type==7:
798                     # fix tail bone
799                     parent=self.bones[b.parent_index]
800                     parent.tail_index=b.index
801
802         for b in self.bones:
803             if b.tail_index==None:
804                 b.tail_index=0
805             elif b.type==9:
806                 b.tail_index==0
807
808     def getIndex(self, bone):
809         for i, b in enumerate(self.bones):
810             if b==bone:
811                 return i
812         assert(false)
813
814     def indexByName(self, name):
815         if name=='':
816             return 0
817         else:
818             return self.getIndex(self.__boneByName(name))
819
820     def __boneByName(self, name):
821         return self.boneMap[name]
822                     
823     def __getBone(self, parent, b):
824         if len(b.children)==0:
825             parent.type=7
826             return
827
828         for i, c in enumerate(b.children):
829             bone=Bone(c.name, 
830                     bl.bone.getHeadLocal(c),
831                     bl.bone.getTailLocal(c))
832             self.__addBone(bone)
833             if parent:
834                 bone.parent_index=parent.index
835                 if i==0:
836                     parent.tail_index=bone.index
837             self.__getBone(bone, c)
838
839     def __addBone(self, bone):
840         bone.index=len(self.bones)
841         self.bones.append(bone)
842         self.boneMap[bone.name]=bone
843
844
845 class PmdExporter(object):
846
847     def setup(self, scene):
848         self.armatureObj=None
849         self.scene=scene
850
851         # 木構造を構築する
852         object_node_map={}
853         for o in scene.objects:
854             object_node_map[o]=Node(o)
855         for o in scene.objects:
856         #for node in object_node_map.values():
857             node=object_node_map[o]
858             if node.o.parent:
859                 object_node_map[node.o.parent].children.append(node)
860
861         # ルートを得る
862         root=object_node_map[scene.objects.active]
863
864         # ワンスキンメッシュを作る
865         self.oneSkinMesh=OneSkinMesh(scene)
866         self.__createOneSkinMesh(root)
867         bl.message(self.oneSkinMesh)
868         if len(self.oneSkinMesh.morphList)==0:
869             # create emtpy skin
870             self.oneSkinMesh.createEmptyBasicSkin()
871
872         self.name=root.o.name
873
874         # skeleton
875         self.skeleton=BoneBuilder()
876         self.skeleton.build(self.armatureObj)
877
878     def __createOneSkinMesh(self, node):
879         ############################################################
880         # search armature modifier
881         ############################################################
882         for m in node.o.modifiers:
883             if bl.modifier.isType(m, 'ARMATURE'):
884                 armatureObj=bl.modifier.getArmatureObject(m)
885                 if not self.armatureObj:
886                     self.armatureObj=armatureObj
887                 elif self.armatureObj!=armatureObj:
888                     print("warning! found multiple armature. ignored.", 
889                             armatureObj.name)
890
891         if node.o.type.upper()=='MESH':
892             self.oneSkinMesh.addMesh(node.o)
893
894         for child in node.children:
895             self.__createOneSkinMesh(child)
896
897     def write(self, path):
898         io=pmd.IO()
899         io.name=self.name
900         io.comment="blender export"
901         io.version=1.0
902
903         # 頂点
904         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
905             # convert right-handed z-up to left-handed y-up
906             v=io.addVertex()
907             v.pos.x=pos[0]
908             v.pos.y=pos[2]
909             v.pos.z=pos[1]
910             v.normal.x=normal[0]
911             v.normal.y=normal[2]
912             v.normal.z=normal[1]
913             v.uv.x=uv[0]
914             v.uv.y=1.0-uv[1] # reverse vertical
915             v.bone0=self.skeleton.indexByName(b0)
916             v.bone1=self.skeleton.indexByName(b1)
917             v.weight0=int(100*weight)
918             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
919
920         # 面とマテリアル
921         vertexCount=self.oneSkinMesh.getVertexCount()
922         for material_name, indices in self.oneSkinMesh.vertexArray.each():
923             #print('material:', material_name)
924             m=bl.material.get(material_name)
925             # マテリアル
926             material=io.addMaterial()
927             setMaterialParams(material, m)
928
929             material.vertex_count=len(indices)
930             material.toon_index=0
931             textures=[os.path.basename(path) 
932                 for path in bl.material.eachTexturePath(m)]
933             if len(textures)>0:
934                 material.setTexture(toCP932('*'.join(textures)))
935             else:
936                 material.setTexture(toCP932(""))
937             # 面
938             for i in indices:
939                 assert(i<vertexCount)
940             for i in xrange(0, len(indices), 3):
941                 # reverse triangle
942                 io.indices.append(indices[i])
943                 io.indices.append(indices[i+1])
944                 io.indices.append(indices[i+2])
945
946         # bones
947         boneNameMap={}
948         for i, b in enumerate(self.skeleton.bones):
949             bone=io.addBone()
950
951             # name
952             boneNameMap[b.name]=i
953             v=englishmap.getUnicodeBoneName(b.name)
954             if not v:
955                 v=[b.name, b.name]
956             assert(v)
957             cp932=v[1].encode('cp932')
958             assert(len(cp932)<20)
959             bone.setName(cp932)
960
961             # english name
962             bone_english_name=toCP932(b.name)
963             assert(len(bone_english_name)<20)
964             bone.setEnglishName(bone_english_name)
965
966             if len(v)>=3:
967                 # has type
968                 if v[2]==5:
969                     b.ik_index=self.skeleton.indexByName('eyes')
970                 bone.type=v[2]
971             else:
972                 bone.type=b.type
973
974             bone.parent_index=b.parent_index
975             bone.tail_index=b.tail_index
976             bone.ik_index=b.ik_index
977
978             # convert right-handed z-up to left-handed y-up
979             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
980             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
981             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
982
983         # IK
984         for ik in self.skeleton.ik_list:
985             solver=io.addIK()
986             solver.index=self.skeleton.getIndex(ik.target)
987             solver.target=self.skeleton.getIndex(ik.effector)
988             solver.length=ik.length
989             b=self.skeleton.bones[ik.effector.parent_index]
990             for i in xrange(solver.length):
991                 solver.children.append(self.skeleton.getIndex(b))
992                 b=self.skeleton.bones[b.parent_index]
993             solver.iterations=ik.iterations
994             solver.weight=ik.weight
995
996         # 表情
997         for i, m in enumerate(self.oneSkinMesh.morphList):
998             # morph
999             morph=io.addMorph()
1000
1001             v=englishmap.getUnicodeSkinName(m.name)
1002             if not v:
1003                 v=[m.name, m.name, 0]
1004             assert(v)
1005             cp932=v[1].encode('cp932')
1006             morph.setName(cp932)
1007             morph.setEnglishName(m.name.encode('cp932'))
1008             m.type=v[2]
1009             morph.type=v[2]
1010             for index, offset in m.offsets:
1011                 # convert right-handed z-up to left-handed y-up
1012                 morph.append(index, offset[0], offset[2], offset[1])
1013             morph.vertex_count=len(m.offsets)
1014
1015         # 表情枠
1016         # type==0はbase
1017         for i, m in enumerate(self.oneSkinMesh.morphList):
1018             if m.type==3:
1019                 io.face_list.append(i)
1020         for i, m in enumerate(self.oneSkinMesh.morphList):
1021             if m.type==2:
1022                 io.face_list.append(i)
1023         for i, m in enumerate(self.oneSkinMesh.morphList):
1024             if m.type==1:
1025                 io.face_list.append(i)
1026         for i, m in enumerate(self.oneSkinMesh.morphList):
1027             if m.type==4:
1028                 io.face_list.append(i)
1029
1030         # ボーングループ
1031         for g in self.skeleton.bone_groups:
1032             boneDisplayName=io.addBoneGroup()
1033             # name
1034             name=englishmap.getUnicodeBoneGroupName(g[0])
1035             if not name:
1036                 name=g[0]
1037             boneDisplayName.setName(toCP932(name+'\n'))
1038             # english
1039             englishName=g[0]
1040             boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1041
1042         # ボーングループメンバー
1043         for i, b in enumerate(self.skeleton.bones):
1044             if i==0:
1045                 continue
1046             if b.type in [6, 7]:
1047                 continue
1048             io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1049
1050         # English
1051         io.english_name="blender export"
1052         io.english_coment="blender export"
1053
1054         # toon
1055         for i in range(10):
1056             io.getToonTexture(i).name="toon%02d.bmp\n" % i
1057
1058         # rigid body
1059         rigidNameMap={}
1060         for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1061             rigidBody=io.addRigidBody()
1062             rigidBody.setName(obj.name.encode('cp932'))
1063             rigidNameMap[obj.name]=i
1064             boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1065             if boneIndex==0:
1066                 boneIndex=0xFFFF
1067                 bone=self.skeleton.bones[0]
1068             else:
1069                 bone=self.skeleton.bones[boneIndex]
1070             rigidBody.boneIndex=boneIndex
1071             #rigidBody.position.x=obj[RIGID_LOCATION][0]
1072             #rigidBody.position.y=obj[RIGID_LOCATION][1]
1073             #rigidBody.position.z=obj[RIGID_LOCATION][2]
1074             rigidBody.position.x=obj.location.x-bone.pos[0]
1075             rigidBody.position.y=obj.location.z-bone.pos[2]
1076             rigidBody.position.z=obj.location.y-bone.pos[1]
1077             rigidBody.rotation.x=-obj.rotation_euler[0]
1078             rigidBody.rotation.y=-obj.rotation_euler[2]
1079             rigidBody.rotation.z=-obj.rotation_euler[1]
1080             rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1081             rigidBody.group=obj[RIGID_GROUP]
1082             rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1083             rigidBody.weight=obj[RIGID_WEIGHT]
1084             rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1085             rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1086             rigidBody.restitution=obj[RIGID_RESTITUTION]
1087             rigidBody.friction=obj[RIGID_FRICTION]
1088             if obj[RIGID_SHAPE_TYPE]==0:
1089                 rigidBody.shapeType=pmd.SHAPE_SPHERE
1090                 rigidBody.w=obj.scale[0]
1091             elif obj[RIGID_SHAPE_TYPE]==1:
1092                 rigidBody.shapeType=pmd.SHAPE_BOX
1093                 rigidBody.w=obj.scale[0]
1094                 rigidBody.d=obj.scale[1]
1095                 rigidBody.h=obj.scale[2]
1096             elif obj[RIGID_SHAPE_TYPE]==2:
1097                 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1098                 rigidBody.w=obj.scale[0]
1099                 rigidBody.h=obj.scale[2]
1100
1101         # constraint
1102         for obj in self.oneSkinMesh.constraints:
1103             constraint=io.addConstraint()
1104             constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1105             constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1106             constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1107             constraint.pos.x=obj.location[0]
1108             constraint.pos.y=obj.location[2]
1109             constraint.pos.z=obj.location[1]
1110             constraint.rot.x=-obj.rotation_euler[0]
1111             constraint.rot.y=-obj.rotation_euler[2]
1112             constraint.rot.z=-obj.rotation_euler[1]
1113             constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1114             constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1115             constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1116             constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1117             constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1118             constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1119             constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1120             constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1121             constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1122             constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1123             constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1124             constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1125             constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1126             constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1127             constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1128             constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1129             constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1130             constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1131
1132         # 書き込み
1133         bl.message('write %s' % path)
1134         return io.write(path)
1135
1136
1137 def __execute(filename, scene):
1138     if not scene.objects.active:
1139         print("abort. no active object.")
1140         return
1141
1142     active=bl.object.getActive()
1143     exporter=PmdExporter()
1144     exporter.setup(scene)
1145     exporter.write(filename)
1146     bl.object.activate(active)
1147
1148
1149 if isBlender24():
1150     # for 2.4
1151     def execute_24(filename):
1152         scene = bpy.data.scenes.active
1153         bl.initialize('pmd_export', scene)
1154         __execute(filename.decode(bl.INTERNAL_ENCODING), scene)
1155         bl.finalize()
1156
1157     Blender.Window.FileSelector(
1158              execute_24,
1159              'Export Metasequoia PMD',
1160              Blender.sys.makename(ext='.pmd'))
1161
1162 else:
1163     # for 2.5
1164     def execute_25(filename, scene):
1165         bl.initialize('pmd_export', scene)
1166         __execute(filename, scene)
1167         bl.finalize()
1168
1169     # operator
1170     class EXPORT_OT_pmd(bpy.types.Operator):
1171         '''Save a Metasequoia PMD file.'''
1172         bl_idname = "export_scene.pmd"
1173         bl_label = 'Export PMD'
1174
1175         # List of operator properties, the attributes will be assigned
1176         # to the class instance from the operator settings before calling.
1177
1178         path = StringProperty(
1179                 name="File Path",
1180                 description="File path used for exporting the PMD file",
1181                 maxlen= 1024,
1182                 default= ""
1183                 )
1184         filename = StringProperty(
1185                 name="File Name", 
1186                 description="Name of the file.")
1187         directory = StringProperty(
1188                 name="Directory", 
1189                 description="Directory of the file.")
1190
1191         check_existing = BoolProperty(
1192                 name="Check Existing",
1193                 description="Check and warn on overwriting existing files",
1194                 default=True,
1195                 options=set('HIDDEN'))
1196
1197         def execute(self, context):
1198             execute_25(
1199                     self.properties.path, 
1200                     context.scene
1201                     )
1202             return 'FINISHED'
1203
1204         def invoke(self, context, event):
1205             wm=context.manager
1206             wm.add_fileselect(self)
1207             return 'RUNNING_MODAL'
1208
1209     # register menu
1210     def menu_func(self, context): 
1211         #default_path=bpy.data.filename.replace(".blend", ".pmd")
1212         self.layout.operator(
1213                 EXPORT_OT_pmd.bl_idname, 
1214                 text="Miku Miku Dance Model(.pmd)")#.path=default_path
1215
1216     def register():
1217         bpy.types.register(EXPORT_OT_pmd)
1218         bpy.types.INFO_MT_file_export.append(menu_func)
1219
1220     def unregister():
1221         bpy.types.unregister(EXPORT_OT_pmd)
1222         bpy.types.INFO_MT_file_export.remove(menu_func)
1223
1224     if __name__ == "__main__":
1225         register()
1226