OSDN Git Service

998e76c517341f0196f9e2fe951ec9f49995bfbc
[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.0"
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 """
22
23 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
24 BASE_SHAPE_NAME='Basis'
25
26
27 ###############################################################################
28 # import
29 ###############################################################################
30 import os
31 import sys
32 import re
33 import math
34
35 # C extension
36 from meshio import pmd, englishmap
37
38 def isBlender24():
39     return sys.version_info[0]<3
40
41 if isBlender24():
42     # for 2.4
43     import Blender
44     from Blender import Mathutils
45     import bpy
46
47     # wrapper
48     import bl24 as bl
49 else:
50     # for 2.5
51     import bpy
52     from bpy.props import *
53     import mathutils
54
55     # wrapper
56     import bl25 as bl
57
58     xrange=range
59
60
61 class Node(object):
62     __slots__=['o', 'children']
63     def __init__(self, o):
64         self.o=o
65         self.children=[]
66
67
68 ###############################################################################
69 # Blenderのメッシュをワンスキンメッシュ化する
70 ###############################################################################
71 def near(x, y, EPSILON=1e-5):
72     d=x-y
73     return d>=-EPSILON and d<=EPSILON
74
75
76 class VertexKey(object):
77     """
78     重複頂点の検索キー
79     """
80     __slots__=[
81             'obj', 'index',
82             'x', 'y', 'z', # 位置
83             'nx', 'ny', 'nz', # 法線
84             'u', 'v', # uv
85             ]
86
87     def __init__(self, obj, index, x, y, z, nx, ny, nz, u, v):
88         self.obj=obj
89         self.index=index
90         self.x=x
91         self.y=y
92         self.z=z
93         self.nx=nx
94         self.ny=ny
95         self.nz=nz
96         self.u=u
97         self.v=v
98
99     def __str__(self):
100         return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
101                 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
102
103     def __hash__(self):
104         #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
105         return int((self.x+self.y+self.z)*100)
106
107     def __eq__(self, rhs):
108         #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)
109         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
110         #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
111         return self.obj==rhs.obj and self.index==rhs.index
112
113
114 class VertexArray(object):
115     """
116     頂点配列
117     """
118     def __init__(self):
119         # マテリアル毎に分割したインデックス配列
120         self.indexArrays={}
121         # 頂点属性
122         self.vertices=[]
123         self.normals=[]
124         self.uvs=[]
125         # skinning属性
126         self.b0=[]
127         self.b1=[]
128         self.weight=[]
129
130         self.vertexMap={}
131         self.indexMap={}
132
133     def __str__(self):
134         return "<VertexArray %d vertices, %d indexArrays>" % (
135                 len(self.vertices), len(self.indexArrays))
136
137     def zip(self):
138         return zip(
139                 self.vertices, self.normals, self.uvs,
140                 self.b0, self.b1, self.weight)
141
142     def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
143         """
144         頂点属性からその頂点のインデックスを得る
145         """
146         key=VertexKey(
147                 obj, base_index,
148                 pos[0], pos[1], pos[2],
149                 normal[0], normal[1], normal[2],
150                 uv[0], uv[1])
151         if key in self.vertexMap:
152             # 同じ頂点を登録済み
153             index=self.vertexMap[key]
154         else:
155             index=len(self.vertices)
156             # 新規頂点
157             self.vertexMap[key]=index
158             # append...
159             self.vertices.append((pos.x, pos.y, pos.z))
160             self.normals.append((normal.x, normal.y, normal.z))
161             self.uvs.append((uv[0], uv[1]))
162             self.b0.append(b0)
163             self.b1.append(b1)
164             self.weight.append(weight0)
165             
166         # indexのマッピングを保存する
167         if not base_index in self.indexMap:
168             self.indexMap[base_index]=set()
169         self.indexMap[base_index].add(index)
170
171         assert(index<=65535)
172         return index
173
174     def getMappedIndices(self, base_index):
175         return self.indexMap[base_index]
176
177     def addTriangle(self,
178             obj, material,
179             base_index0, base_index1, base_index2,
180             pos0, pos1, pos2,
181             n0, n1, n2,
182             uv0, uv1, uv2,
183             b0_0, b0_1, b0_2,
184             b1_0, b1_1, b1_2,
185             weight0, weight1, weight2
186             ):
187         if not material in self.indexArrays:
188             self.indexArrays[material]=[]
189
190         index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
191         index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
192         index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
193
194         self.indexArrays[material]+=[index0, index1, index2]
195
196
197 class Morph(object):
198     __slots__=['name', 'type', 'offsets']
199     def __init__(self, name, type):
200         self.name=name
201         self.type=type
202         self.offsets=[]
203
204     def add(self, index, offset):
205         self.offsets.append((index, offset))
206
207     def sort(self):
208         if isBlender24():
209             self.offsets.sort(lambda l, r: l[0]-r[0])
210         else:
211             self.offsets.sort(key=lambda e: e[0])
212
213     def __str__(self):
214         return "<Morph %s>" % self.name
215
216 class IKSolver(object):
217     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
218     def __init__(self, target, effector, length, iterations, weight):
219         self.target=target
220         self.effector=effector
221         self.length=length
222         self.iterations=iterations
223         self.weight=weight
224
225
226 class OneSkinMesh(object):
227     __slots__=['obj_index', 'scene', 'vertexArray', 'morphList']
228     def __init__(self, scene):
229         self.vertexArray=VertexArray()
230         self.morphList=[]
231         self.scene=scene
232         self.obj_index=0
233
234     def __str__(self):
235         return "<OneSkinMesh %s, morph:%d>" % (
236                 self.vertexArray,
237                 len(self.morphList))
238
239     def addMesh(self, obj):
240         if bl.objectIsVisible(obj):
241             # 非表示
242             return
243
244         print("export", obj.name)
245
246         # bone weight
247         weightMap=self.__mesh(obj)
248
249         # skin
250         self.__skin(obj)
251
252     def __mesh(self, obj):
253         mesh=bl.objectGetData(obj)
254         weightMap={}
255         secondWeightMap={}
256         def setWeight(i, name, w):
257             if w>0:
258                 if i in weightMap:
259                     if i in secondWeightMap:
260                         # 上位2つのweightを採用する
261                         if w<secondWeightMap[i]:
262                             pass
263                         elif w<weightMap[i]:
264                             # 2つ目を入れ替え
265                             secondWeightMap[i]=(name, w)
266                         else:
267                             # 1つ目を入れ替え
268                             weightMap[i]=(name, w)
269                     else:
270                         if w>weightMap[i][1]:
271                             # 多い方をweightMapに
272                             secondWeightMap[i]=weightMap[i]
273                             weightMap[i]=(name, w)
274                         else:
275                             secondWeightMap[i]=(name, w)
276                 else:
277                     weightMap[i]=(name, w)
278
279         if isBlender24():
280             for name in bl.meshVertexGroupNames(obj):
281                 for i, w in mesh.getVertsFromGroup(name, 1):
282                     setWeight(i, name, w)
283         else:
284             for i, v in enumerate(mesh.verts):
285                 for g in v.groups:
286                     setWeight(i, obj.vertex_groups[g.group].name, g.weight)
287
288         # 合計値が1になるようにする
289         for i in xrange(len(mesh.verts)):
290         #for i, name_weight in weightMap.items():
291             if i in secondWeightMap:
292                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
293             elif i in weightMap:
294                 weightMap[i]=(weightMap[i][0], 1.0)
295                 secondWeightMap[i]=("", 0)
296             else:
297                 print("no weight vertex")
298                 weightMap[i]=("", 0)
299                 secondWeightMap[i]=("", 0)
300
301         # メッシュのコピーを生成してオブジェクトの行列を適用する
302         copyMesh, copyObj=bl.objectDuplicate(self.scene, obj)
303         if len(copyMesh.verts)==0:
304             return
305
306         for i, face in enumerate(copyMesh.faces):
307             faceVertexCount=bl.faceVertexCount(face)
308             material=copyMesh.materials[bl.faceMaterialIndex(face)]
309             v=[copyMesh.verts[index] for index in bl.faceVertices(face)]
310             uv=bl.meshFaceUv(copyMesh, i, face)
311             if faceVertexCount==3:
312                 # triangle
313                 self.vertexArray.addTriangle(
314                         self.obj_index, material.name,
315                         v[0].index, v[1].index, v[2].index,
316                         v[0].co, v[1].co, v[2].co,
317                         # ToDo vertex normal
318                         #v0.no, v1.no, v2.no,
319                         bl.faceNormal(face), 
320                         bl.faceNormal(face), 
321                         bl.faceNormal(face),
322                         uv[0], uv[1], uv[2],
323                         weightMap[v[0].index][0],
324                         weightMap[v[1].index][0],
325                         weightMap[v[2].index][0],
326                         secondWeightMap[v[0].index][0],
327                         secondWeightMap[v[1].index][0],
328                         secondWeightMap[v[2].index][0],
329                         weightMap[v[0].index][1],
330                         weightMap[v[1].index][1],
331                         weightMap[v[2].index][1]
332                         )
333             elif faceVertexCount==4:
334                 # quadrangle
335                 self.vertexArray.addTriangle(
336                         self.obj_index, material.name,
337                         v[0].index, v[1].index, v[2].index,
338                         v[0].co, v[1].co, v[2].co,
339                         #v0.no, v1.no, v2.no,
340                         bl.faceNormal(face), 
341                         bl.faceNormal(face), 
342                         bl.faceNormal(face), 
343                         uv[0], uv[1], uv[2],
344                         weightMap[v[0].index][0],
345                         weightMap[v[1].index][0],
346                         weightMap[v[2].index][0],
347                         secondWeightMap[v[0].index][0],
348                         secondWeightMap[v[1].index][0],
349                         secondWeightMap[v[2].index][0],
350                         weightMap[v[0].index][1],
351                         weightMap[v[1].index][1],
352                         weightMap[v[2].index][1]
353                         )
354                 self.vertexArray.addTriangle(
355                         self.obj_index, material.name,
356                         v[2].index, v[3].index, v[0].index,
357                         v[2].co, v[3].co, v[0].co,
358                         #v2.no, v3.no, v0.no,
359                         bl.faceNormal(face), 
360                         bl.faceNormal(face), 
361                         bl.faceNormal(face), 
362                         uv[2], uv[3], uv[0],
363                         weightMap[v[2].index][0],
364                         weightMap[v[3].index][0],
365                         weightMap[v[0].index][0],
366                         secondWeightMap[v[2].index][0],
367                         secondWeightMap[v[3].index][0],
368                         secondWeightMap[v[0].index][0],
369                         weightMap[v[2].index][1],
370                         weightMap[v[3].index][1],
371                         weightMap[v[0].index][1]
372                         )
373         bl.objectDelete(self.scene, copyObj)
374         self.obj_index+=1
375
376     def __skin(self, obj):
377         if not bl.objectHasShapeKey(obj):
378             return
379
380         indexRelativeMap={}
381         blenderMesh=bl.objectGetData(obj)
382         baseMorph=None
383
384         # shape keys
385         vg=bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
386
387         # base
388         used=set()
389         for b in bl.objectShapeKeys(obj):
390             if b.name==BASE_SHAPE_NAME:
391                 baseMorph=self.__getOrCreateMorph('base', 0)
392                 basis=b
393
394                 relativeIndex=0
395                 for index in vg:
396                     v=bl.shapeKeyGet(b, index)
397                     pos=[v[0], v[1], v[2]]
398                     indices=self.vertexArray.getMappedIndices(index)
399                     for i in indices:
400                         if i in used:
401                             continue
402                         used.add(i)
403
404                         baseMorph.add(i, pos)
405                         indexRelativeMap[i]=relativeIndex
406                         relativeIndex+=1
407
408                 break
409         assert(basis)
410         print(basis.name, len(baseMorph.offsets))
411
412         if len(baseMorph.offsets)==0:
413             return
414
415         # shape keys
416         for b in bl.objectShapeKeys(obj):
417             if b.name==BASE_SHAPE_NAME:
418                 continue
419
420             print(b.name)
421             morph=self.__getOrCreateMorph(b.name, 4)
422             used=set()
423             for index, src, dst in zip(
424                     xrange(len(blenderMesh.verts)),
425                     bl.shapeKeys(basis),
426                     bl.shapeKeys(b)):
427                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
428                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
429                     continue
430                 if index in vg:
431                     indices=self.vertexArray.getMappedIndices(index)
432                     for i in indices:
433                         if i in used:
434                             continue
435                         used.add(i) 
436                         morph.add(indexRelativeMap[i], offset)
437
438         # sort skinmap
439         original=self.morphList[:]
440         def getIndex(morph):
441             for i, v in enumerate(englishmap.skinMap):
442                 if v[0]==morph.name:
443                     return i
444             print(morph)
445         if isBlender24():
446             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
447         else:
448             self.morphList.sort(key=getIndex)
449
450     def __getOrCreateMorph(self, name, type):
451         for m in self.morphList:
452             if m.name==name:
453                 return m
454         m=Morph(name, type)
455         self.morphList.append(m)
456         return m
457
458     def getVertexCount(self):
459         return len(self.vertexArray.vertices)
460
461
462 class Bone(object):
463     __slots__=['index', 'name', 'ik_index',
464             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
465     def __init__(self, name, pos, tail):
466         self.index=-1
467         self.name=name
468         self.pos=pos
469         self.tail=tail
470         self.parent_index=None
471         self.tail_index=None
472         self.type=0
473         self.isConnect=False
474         self.ik_index=0
475
476     def __eq__(self, rhs):
477         return self.index==rhs.index
478
479     def __str__(self):
480         return "<Bone %s %d>" % (self.name, self.type)
481
482 class BoneBuilder(object):
483     __slots__=['bones', 'boneMap', 'ik_list']
484     def __init__(self):
485         self.bones=[]
486         self.boneMap={}
487         self.ik_list=[]
488
489     def build(self, armatureObj):
490         if not armatureObj:
491             return
492
493         print("gather bones")
494         armature=bl.objectGetData(armatureObj)
495         for b in armature.bones.values():
496             if b.name=='center':
497                 # root bone
498                 bone=Bone(b.name, 
499                         bl.boneHeadLocal(b),
500                         bl.boneTailLocal(b))
501                 self.__addBone(bone)
502                 self.__getBone(bone, b)
503
504         for b in armature.bones.values():
505             if not b.parent and b.name!='center':
506                 # root bone
507                 bone=Bone(b.name, 
508                         bl.boneHeadLocal(b),
509                         bl.boneTailLocal(b))
510                 self.__addBone(bone)
511                 self.__getBone(bone, b)
512
513         print("check connection")
514         for b in armature.bones.values():
515             if not b.parent:
516                 self.__checkConnection(b, None)
517
518         print("gather ik")
519         pose = bl.objectGetPose(armatureObj)
520         for b in pose.bones.values():
521             for c in b.constraints:
522                 if bl.constraintIsIKSolver(c):
523                     ####################
524                     # IK target
525                     ####################
526                     target=self.__boneByName(bl.ikTarget(c))
527                     target.type=2
528
529                     ####################
530                     # IK effector
531                     ####################
532                     # IK 接続先
533                     link=self.__boneByName(b.name)
534                     link.type=6
535
536                     # IK chain
537                     e=b.parent
538                     chainLength=bl.ikChainLen(c)
539                     for i in range(chainLength):
540                         # IK影響下
541                         chainBone=self.__boneByName(e.name)
542                         chainBone.type=4
543                         chainBone.ik_index=target.index
544                         e=e.parent
545                     self.ik_list.append(
546                             IKSolver(target, link, chainLength, 
547                                 int(bl.ikItration(c) * 0.1), 
548                                 bl.ikRotationWeight(c)
549                                 ))
550
551     def __checkConnection(self, b, p):
552         if bl.boneIsConnected(b):
553             parent=self.__boneByName(p.name)
554             parent.isConnect=True
555
556         for c in b.children:
557             self.__checkConnection(c, b)
558
559     def sortBy(self, boneMap):
560         """
561         boneMap順に並べ替える
562         """
563         original=self.bones[:]
564         def getIndex(bone):
565             for i, k_v in enumerate(boneMap):
566                 if k_v[0]==bone.name:
567                     return i
568             print(bone)
569
570         if isBlender24():
571             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
572         else:
573             self.bones.sort(key=getIndex)
574
575         sortMap={}
576         for i, b in enumerate(self.bones):
577             src=original.index(b)
578             sortMap[src]=i
579         for b in self.bones:
580             b.index=sortMap[b.index]
581             if b.parent_index:
582                 b.parent_index=sortMap[b.parent_index]
583             if b.tail_index:
584                 b.tail_index=sortMap[b.tail_index]
585             if b.ik_index>0:
586                 b.ik_index=sortMap[b.ik_index]
587
588     def getIndex(self, bone):
589         for i, b in enumerate(self.bones):
590             if b==bone:
591                 return i
592         assert(false)
593
594     def indexByName(self, name):
595         return self.getIndex(self.__boneByName(name))
596
597     def __boneByName(self, name):
598         return self.bones[self.boneMap[name]]
599                     
600     def __getBone(self, parent, b):
601         if len(b.children)==0:
602             parent.type=7
603             return
604
605         for i, c in enumerate(b.children):
606             bone=Bone(c.name, 
607                     bl.boneHeadLocal(c),
608                     bl.boneTailLocal(c))
609             self.__addBone(bone)
610             if parent:
611                 bone.parent_index=parent.index
612                 if i==0:
613                     parent.tail_index=bone.index
614             self.__getBone(bone, c)
615
616     def __addBone(self, bone):
617         bone.index=len(self.bones)
618         self.bones.append(bone)
619         self.boneMap[bone.name]=bone.index
620
621
622 class PmdExporter(object):
623
624     def setup(self, scene):
625         self.armatureObj=None
626         self.scene=scene
627
628         # 木構造を構築する
629         object_node_map={}
630         for o in scene.objects:
631             object_node_map[o]=Node(o)
632         for node in object_node_map.values():
633             if node.o.parent:
634                 object_node_map[node.o.parent].children.append(node)
635
636         # ルートを得る
637         root=object_node_map[scene.objects.active]
638
639         # ワンスキンメッシュを作る
640         self.oneSkinMesh=OneSkinMesh(scene)
641         self.__createOneSkinMesh(root)
642         print(self.oneSkinMesh)
643         self.name=root.o.name
644
645         # skeleton
646         self.builder=BoneBuilder()
647         self.builder.build(self.armatureObj)
648         self.builder.sortBy(englishmap.boneMap)
649         def getIndex(ik):
650             for i, v in enumerate(englishmap.boneMap):
651                 if v[0]==ik.target.name:
652                     return i
653             return len(englishmap.boneMap)
654         if isBlender24():
655             self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
656         else:
657             self.builder.ik_list.sort(key=getIndex)
658
659     def __createOneSkinMesh(self, node):
660         print(node)
661         ############################################################
662         # search armature modifier
663         ############################################################
664         for m in node.o.modifiers:
665             if bl.modifierIsArmature(m):
666                 armatureObj=bl.armatureModifierGetObject(m)
667                 if not self.armatureObj:
668                     self.armatureObj=armatureObj
669                 elif self.armatureObj!=armatureObj:
670                     print("warning! found multiple armature. ignored.", armatureObj.name)
671
672         if node.o.type.upper()=='MESH':
673             self.oneSkinMesh.addMesh(node.o)
674
675         for child in node.children:
676             self.__createOneSkinMesh(child)
677
678     def write(self, path):
679         io=pmd.IO()
680         io.name=self.name
681         io.comment="blender export"
682         io.version=1.0
683
684         # 頂点
685         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
686             # convert right-handed z-up to left-handed y-up
687             v=io.addVertex()
688             v.pos.x=pos[0]
689             v.pos.y=pos[2]
690             v.pos.z=pos[1]
691             v.normal.x=normal[0]
692             v.normal.y=normal[2]
693             v.normal.z=normal[1]
694             v.uv.x=uv[0]
695             v.uv.y=uv[1]
696             v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
697             v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
698             v.weight0=int(100*weight)
699             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
700
701         # 面とマテリアル
702         vertexCount=self.oneSkinMesh.getVertexCount()
703         for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
704             m=bl.materialGet(self.scene, material_name)
705             # マテリアル
706             material=io.addMaterial()
707             if isBlender24():
708                 material.diffuse.r=m.R
709                 material.diffuse.g=m.G
710                 material.diffuse.b=m.B
711                 material.diffuse.a=m.alpha
712                 material.sinness=0 if m.spec<1e-5 else m.spec*10
713                 material.specular.r=m.specR
714                 material.specular.g=m.specG
715                 material.specular.b=m.specB
716                 material.ambient.r=m.mirR
717                 material.ambient.g=m.mirG
718                 material.ambient.b=m.mirB
719                 material.flag=1 if m.enableSSS else 0
720             else:
721                 material.diffuse.r=m.diffuse_color[0]
722                 material.diffuse.g=m.diffuse_color[1]
723                 material.diffuse.b=m.diffuse_color[2]
724                 material.diffuse.a=m.alpha
725                 material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
726                 material.specular.r=m.specular_color[0]
727                 material.specular.g=m.specular_color[1]
728                 material.specular.b=m.specular_color[2]
729                 material.ambient.r=m.mirror_color[0]
730                 material.ambient.g=m.mirror_color[1]
731                 material.ambient.b=m.mirror_color[2]
732                 material.flag=1 if m.subsurface_scattering.enabled else 0
733
734             material.vertex_count=len(indices)
735             material.toon_index=0
736             # ToDo
737             material.texture=""
738             # 面
739             for i in indices:
740                 assert(i<vertexCount)
741             for i in xrange(0, len(indices), 3):
742                 # reverse triangle
743                 io.indices.append(indices[i])
744                 io.indices.append(indices[i+1])
745                 io.indices.append(indices[i+2])
746
747         # bones
748         for b in self.builder.bones:
749             if b.name.endswith("_t"):
750                 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
751                     # skip
752                     print("skip %s" % b.name)
753                     continue
754
755             bone=io.addBone()
756
757             # name
758             v=englishmap.getUnicodeBoneName(b.name)
759             assert(v)
760             cp932=v[1].encode('cp932')
761             assert(len(cp932)<20)
762             bone.setName(cp932)
763
764             # english name
765             bone_english_name=b.name
766             assert(len(bone_english_name)<20)
767             bone.english_name=bone_english_name
768
769             if len(v)>=3:
770                 # has type
771                 if v[2]==5:
772                     b.ik_index=self.builder.indexByName('eyes')
773                 bone.type=v[2]
774             else:
775                 bone.type=b.type
776
777             # parent index
778             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
779
780             # tail index
781             if b.tail_index!=None:
782                 if bone.type==9:
783                     bone.tail_index=0
784                 else:
785                     bone.tail_index=b.tail_index
786             else:
787                 bone.tail_index=0
788
789             bone.ik_index=b.ik_index
790
791             # convert right-handed z-up to left-handed y-up
792             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
793             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
794             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
795
796         # IK
797         for ik in self.builder.ik_list:
798             solver=io.addIK()
799             solver.index=self.builder.getIndex(ik.target)
800             solver.target=self.builder.getIndex(ik.effector)
801             solver.length=ik.length
802             b=self.builder.bones[ik.effector.parent_index]
803             for i in xrange(solver.length):
804                 solver.children.append(self.builder.getIndex(b))
805                 b=self.builder.bones[b.parent_index]
806             solver.iterations=ik.iterations
807             solver.weight=ik.weight
808
809         # 表情
810         for i, m in enumerate(self.oneSkinMesh.morphList):
811             # morph
812             morph=io.addMorph()
813
814             v=englishmap.getUnicodeSkinName(m.name)
815             assert(v)
816             cp932=v[1].encode('cp932')
817             morph.setName(cp932)
818             morph.setEnglishName(m.name.encode('cp932'))
819             m.type=v[2]
820             morph.type=v[2]
821             for index, offset in m.offsets:
822                 # convert right-handed z-up to left-handed y-up
823                 morph.append(index, offset[0], offset[2], offset[1])
824             morph.vertex_count=len(m.offsets)
825
826         # 表情枠
827         # type==0はbase
828         for i, m in enumerate(self.oneSkinMesh.morphList):
829             if m.type==3:
830                 io.face_list.append(i)
831         for i, m in enumerate(self.oneSkinMesh.morphList):
832             if m.type==2:
833                 io.face_list.append(i)
834         for i, m in enumerate(self.oneSkinMesh.morphList):
835             if m.type==1:
836                 io.face_list.append(i)
837         for i, m in enumerate(self.oneSkinMesh.morphList):
838             if m.type==4:
839                 io.face_list.append(i)
840
841         # ボーン表示枠
842         def createBoneDisplayName(name, english):
843             boneDisplayName=io.addBoneDisplayName()
844             if isBlender24():
845                 boneDisplayName.name=name.decode('utf-8').encode('cp932')
846                 boneDisplayName.english_name=english
847             else:
848                 boneDisplayName.setName(name.encode('cp932'))
849                 boneDisplayName.setEnglishName(english.encode('cp932'))
850         boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
851         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
852         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
853         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
854         boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
855         boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
856         boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
857         for i, b in enumerate(self.builder.bones):
858             if i==0:
859                 continue
860             if b.type in [6, 7]:
861                 continue
862             io.addBoneDisplay(i, getBoneDisplayGroup(b))
863
864         # English
865         io.english_name="blender export"
866         io.english_coment="blender export"
867
868         for i in range(10):
869             io.getToonTexture(i).name="toon%02d.bmp\n" % i
870
871         # 書き込み
872         return io.write(path)
873
874
875 def getBoneDisplayGroup(bone):
876     boneGroups=[
877             [ # IK
878                 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
879                 "toe IK_L", "toe IK_R", 
880                 ],
881             [ # 体(上)
882                 "upper body", "neck", "head", "eye_L", "eye_R",
883                 "necktie1", "necktie2", "necktie3", "eyes", 
884                 "eyelight_L", "eyelight_R",
885                 ],
886             [ # 髪
887                 "front hair1", "front hair2", "front hair3",
888                 "hair1_L", "hair2_L", "hair3_L", 
889                 "hair4_L", "hair5_L", "hair6_L",
890                 "hair1_R", "hair2_R", "hair3_R", 
891                 "hair4_R", "hair5_R", "hair6_R",
892                 ],
893             [ # 腕
894                 "shoulder_L", "arm_L", "arm twist_L", "elbow_L", 
895                 "wrist twist_L", "wrist_L", "sleeve_L", 
896                 "shoulder_R", "arm_R", "arm twist_R", "elbow_R", 
897                 "wrist twist_R", "wrist_R", "sleeve_R", 
898                 ],
899             [ # 指
900                 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
901                 "middle1_L", "middle2_L", "middle3_L",
902                 "third1_L", "third2_L", "third3_L",
903                 "little1_L", "little2_L", "little3_L",
904                 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
905                 "middle1_R", "middle2_R", "middle3_R",
906                 "third1_R", "third2_R", "third3_R",
907                 "little1_R", "little2_R", "little3_R",
908                 ],
909             [ # 体(下)
910                 "lower body",  "waist accessory", 
911                 "front skirt_L", "back skirt_L",
912                 "front skirt_R", "back skirt_R",
913                 ],
914             [ # 足
915                 "leg_L", "knee_L", "ankle_L",
916                 "leg_R", "knee_R", "ankle_R",
917                 ],
918             ]
919     index=1
920     for g in boneGroups:
921         if bone.name in g:
922             return index
923         index+=1
924     print(bone)
925     return -1
926
927
928 def __execute(filename, scene):
929     if not scene.objects.active:
930         print("abort. no active object.")
931         return
932
933     exporter=PmdExporter()
934     exporter.setup(scene)
935     exporter.write(filename)
936
937
938 if isBlender24():
939     # for 2.4
940     def execute_24(filename):
941         filename=filename.decode(bl.INTERNAL_ENCODING)
942         print("pmd exporter: %s" % filename)
943
944         Blender.Window.WaitCursor(1) 
945         t = Blender.sys.time() 
946
947         scene = bpy.data.scenes.active
948         __execute(filename, scene)
949
950         print('finished in %.2f seconds' % (Blender.sys.time()-t))
951         Blender.Redraw()
952         Blender.Window.WaitCursor(0) 
953
954     Blender.Window.FileSelector(
955              execute_24,
956              'Export Metasequoia PMD',
957              Blender.sys.makename(ext='.pmd'))
958
959 else:
960     # for 2.5
961     def execute_25(*args):
962         __execute(*args)
963
964     # operator
965     class EXPORT_OT_pmd(bpy.types.Operator):
966         '''Save a Metasequoia PMD file.'''
967         bl_idname = "export_scene.pmd"
968         bl_label = 'Export PMD'
969
970         # List of operator properties, the attributes will be assigned
971         # to the class instance from the operator settings before calling.
972
973         path = StringProperty(
974                 name="File Path",
975                 description="File path used for exporting the PMD file",
976                 maxlen= 1024,
977                 default= ""
978                 )
979         filename = StringProperty(
980                 name="File Name", 
981                 description="Name of the file.")
982         directory = StringProperty(
983                 name="Directory", 
984                 description="Directory of the file.")
985
986         check_existing = BoolProperty(
987                 name="Check Existing",
988                 description="Check and warn on overwriting existing files",
989                 default=True,
990                 options=set('HIDDEN'))
991
992         def execute(self, context):
993             execute_25(
994                     self.properties.path, 
995                     context.scene
996                     )
997             return 'FINISHED'
998
999         def invoke(self, context, event):
1000             wm=context.manager
1001             wm.add_fileselect(self)
1002             return 'RUNNING_MODAL'
1003
1004     # register menu
1005     def menu_func(self, context): 
1006         #default_path=bpy.data.filename.replace(".blend", ".pmd")
1007         self.layout.operator(
1008                 EXPORT_OT_pmd.bl_idname, 
1009                 text="Miku Miku Dance Model(.pmd)")#.path=default_path
1010
1011     def register():
1012         bpy.types.register(EXPORT_OT_pmd)
1013         bpy.types.INFO_MT_file_export.append(menu_func)
1014
1015     def unregister():
1016         bpy.types.unregister(EXPORT_OT_pmd)
1017         bpy.types.INFO_MT_file_export.remove(menu_func)
1018
1019     if __name__ == "__main__":
1020         register()
1021