OSDN Git Service

62d01232bb0e13d2a6172a043db42b7b43c57f66
[meshio/meshio.git] / swig / blender24 / pmd_export.py
1 #!BPY
2 # coding: utf-8
3 """
4  Name: 'MikuMikuDance model (.pmd)...'
5  Blender: 248
6  Group: 'Export'
7  Tooltip: 'Export PMD file for MikuMikuDance.'
8 """
9 __author__= ["ousttrue"]
10 __version__= "1.0"
11 __url__=()
12 __bpydoc__="""
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
15 1.0 20100530 implement, basic features.
16 """
17 import Blender
18 import os
19 import sys
20
21 from meshio import pmd, englishmap
22
23
24 # ファイルシステムの文字コード
25 # 改造版との共用のため
26 FS_ENCODING=sys.getfilesystemencoding()
27 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
28     INTERNAL_ENCODING='utf-8'
29 else:
30     INTERNAL_ENCODING=FS_ENCODING
31
32
33 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
34 EXTENSION = u'.pmd'
35
36
37 class Node(object):
38     __slots__=['o', 'children']
39     def __init__(self, o):
40         self.o=o
41         self.children=[]
42
43
44 ###############################################################################
45 # Blenderのメッシュをワンスキンメッシュ化する
46 ###############################################################################
47 def near(x, y, EPSILON=1e-5):
48     d=x-y
49     return d>=-EPSILON and d<=EPSILON
50
51
52 class VertexKey(object):
53     """
54     重複頂点の検索キー
55     """
56     __slots__=[
57             'x', 'y', 'z', # 位置
58             'nx', 'ny', 'nz', # 法線
59             'u', 'v', # uv
60             ]
61
62     def __init__(self, x, y, z, nx, ny, nz, u, v):
63         self.x=x
64         self.y=y
65         self.z=z
66         self.nx=nx
67         self.ny=ny
68         self.nz=nz
69         self.u=u
70         self.v=v
71
72     def __str__(self):
73         return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
74                 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
75
76     def __hash__(self):
77         #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
78         return int((self.x+self.y+self.z)*100)
79
80     def __eq__(self, rhs):
81         #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)
82         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
83         return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
84
85
86 class VertexArray(object):
87     """
88     頂点配列
89     """
90     def __init__(self):
91         # マテリアル毎に分割したインデックス配列
92         self.indexArrays={}
93         # 頂点属性
94         self.vertices=[]
95         self.normals=[]
96         self.uvs=[]
97         # skinning属性
98         self.b0=[]
99         self.b1=[]
100         self.weight=[]
101
102         self.vertexMap={}
103         self.indexMap={}
104
105     def __str__(self):
106         return "<VertexArray %d vertices, %d indexArrays>" % (
107                 len(self.vertices), len(self.indexArrays))
108
109     def zip(self):
110         return zip(
111                 self.vertices, self.normals, self.uvs,
112                 self.b0, self.b1, self.weight)
113
114     def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
115         """
116         頂点属性からその頂点のインデックスを得る
117         """
118         key=VertexKey(
119                 pos[0], pos[1], pos[2],
120                 normal[0], normal[1], normal[2],
121                 uv[0], uv[1])
122         if key in self.vertexMap:
123             # 同じ頂点を登録済み
124             index=self.vertexMap[key]
125         else:
126             index=len(self.vertices)
127             # 新規頂点
128             self.vertexMap[key]=index
129             # append...
130             self.vertices.append((pos.x, pos.y, pos.z))
131             self.normals.append((normal.x, normal.y, normal.z))
132             self.uvs.append((uv.x, uv.y))
133             self.b0.append(b0)
134             self.b1.append(b1)
135             self.weight.append(weight0)
136             
137         # indexのマッピングを保存する
138         if not base_index in self.indexMap:
139             self.indexMap[base_index]=set()
140         self.indexMap[base_index].add(index)
141
142         assert(index<=65535)
143         return index
144
145     def getMappedIndices(self, base_index):
146         return self.indexMap[base_index]
147
148     def addTriangle(self,
149             material,
150             base_index0, base_index1, base_index2,
151             pos0, pos1, pos2,
152             n0, n1, n2,
153             uv0, uv1, uv2,
154             b0_0, b0_1, b0_2,
155             b1_0, b1_1, b1_2,
156             weight0, weight1, weight2
157             ):
158         if not material in self.indexArrays:
159             self.indexArrays[material]=[]
160
161         index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
162         index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
163         index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
164
165         self.indexArrays[material]+=[index0, index1, index2]
166
167
168 class Morph(object):
169     __slots__=['name', 'type', 'offsets']
170     def __init__(self, name, type):
171         self.name=name
172         self.type=type
173         self.offsets=[]
174
175     def add(self, index, offset):
176         self.offsets.append((index, offset))
177
178     def sort(self):
179         self.offsets.sort(lambda l, r: l[0]-r[0])
180
181     def __str__(self):
182         return "<Morph %s>" % self.name
183
184 class IKSolver(object):
185     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
186     def __init__(self, target, effector, length, iterations, weight):
187         self.target=target
188         self.effector=effector
189         self.length=length
190         self.iterations=iterations
191         self.weight=weight
192
193
194 class OneSkinMesh(object):
195     __slots__=['vertexArray', 'morphList']
196     def __init__(self):
197         self.vertexArray=VertexArray()
198         self.morphList=[]
199
200     def __str__(self):
201         return "<OneSkinMesh %s, morph:%d>" % (
202                 self.vertexArray,
203                 len(self.morphList))
204
205     def addMesh(self, obj):
206         if obj.restrictDisplay:
207             # 非表示
208             return
209
210         print("export", obj.name)
211
212         ############################################################
213         # bone weight
214         ############################################################
215         mesh=obj.getData(mesh=True)
216         weightMap={}
217         secondWeightMap={}
218         for name in mesh.getVertGroupNames():
219             for i, w in mesh.getVertsFromGroup(name, 1):
220                 if w>0:
221                     if i in weightMap:
222                         if i in secondWeightMap:
223                             # 上位2つのweightを採用する
224                             if w<secondWeightMap[i]:
225                                 pass
226                             elif w<weightMap[i]:
227                                 # 2つ目を入れ替え
228                                 secondWeightMap[i]=(name, w)
229                             else:
230                                 # 1つ目を入れ替え
231                                 weightMap[i]=(name, w)
232                         else:
233                             if w>weightMap[i][1]:
234                                 # 多い方をweightMapに
235                                 secondWeightMap[i]=weightMap[i]
236                                 weightMap[i]=(name, w)
237                             else:
238                                 secondWeightMap[i]=(name, w)
239                     else:
240                         weightMap[i]=(name, w)
241
242         # 合計値が1になるようにする
243         for i in xrange(len(mesh.verts)):
244         #for i, name_weight in weightMap.items():
245             if i in secondWeightMap:
246                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
247             elif i in weightMap:
248                 weightMap[i]=(weightMap[i][0], 1.0)
249                 secondWeightMap[i]=("", 0)
250             else:
251                 print "no weight vertex"
252                 weightMap[i]=("", 0)
253                 secondWeightMap[i]=("", 0)
254                 
255
256         ############################################################
257         # faces
258         # 新たにメッシュを生成する
259         ############################################################
260         mesh=Blender.Mesh.New()
261         # not applied modifiers
262         mesh.getFromObject(obj.name, 1)
263         # apply object transform
264         mesh.transform(obj.getMatrix())
265         if len(mesh.verts)==0:
266             return
267
268         for face in mesh.faces:
269             faceVertexCount=len(face.v)
270             material=mesh.materials[face.mat]
271             if faceVertexCount==3:
272                 v0=face.v[0]
273                 v1=face.v[1]
274                 v2=face.v[2]
275                 # triangle
276                 self.vertexArray.addTriangle(
277                         material.name,
278                         v0.index, v1.index, v2.index,
279                         v0.co, v1.co, v2.co,
280                         # ToDo vertex normal
281                         #v0.no, v1.no, v2.no,
282                         face.no, face.no, face.no,
283                         face.uv[0], face.uv[1], face.uv[2],
284                         weightMap[v0.index][0],
285                         weightMap[v1.index][0],
286                         weightMap[v2.index][0],
287                         secondWeightMap[v0.index][0],
288                         secondWeightMap[v1.index][0],
289                         secondWeightMap[v2.index][0],
290                         weightMap[v0.index][1],
291                         weightMap[v1.index][1],
292                         weightMap[v2.index][1]
293                         )
294             elif faceVertexCount==4:
295                 v0=face.v[0]
296                 v1=face.v[1]
297                 v2=face.v[2]
298                 v3=face.v[3]
299                 # quadrangle
300                 self.vertexArray.addTriangle(
301                         material.name,
302                         v0.index, v1.index, v2.index,
303                         v0.co, v1.co, v2.co,
304                         #v0.no, v1.no, v2.no,
305                         face.no, face.no, face.no,
306                         face.uv[0], face.uv[1], face.uv[2],
307                         weightMap[v0.index][0],
308                         weightMap[v1.index][0],
309                         weightMap[v2.index][0],
310                         secondWeightMap[v0.index][0],
311                         secondWeightMap[v1.index][0],
312                         secondWeightMap[v2.index][0],
313                         weightMap[v0.index][1],
314                         weightMap[v1.index][1],
315                         weightMap[v2.index][1]
316                         )
317                 self.vertexArray.addTriangle(
318                         material.name,
319                         v2.index, v3.index, v0.index,
320                         v2.co, v3.co, v0.co,
321                         #v2.no, v3.no, v0.no,
322                         face.no, face.no, face.no,
323                         face.uv[2], face.uv[3], face.uv[0],
324                         weightMap[v2.index][0],
325                         weightMap[v3.index][0],
326                         weightMap[v0.index][0],
327                         secondWeightMap[v2.index][0],
328                         secondWeightMap[v3.index][0],
329                         secondWeightMap[v0.index][0],
330                         weightMap[v2.index][1],
331                         weightMap[v3.index][1],
332                         weightMap[v0.index][1]
333                         )
334
335         ############################################################
336         # skin
337         ############################################################
338         # base
339         indexRelativeMap={}
340         blenderMesh=obj.getData(mesh=True)
341         baseMorph=None
342         if blenderMesh.key:
343             for b in blenderMesh.key.blocks:
344                 if b.name=='Basis':
345                     print(b.name)
346                     baseMorph=self.__getOrCreateMorph('base', 0)
347                     relativeIndex=0
348                     basis=b
349                     for index in blenderMesh.getVertsFromGroup(
350                             MMD_SHAPE_GROUP_NAME):
351                         v=b.data[index]
352                         pos=[v[0], v[1], v[2]]
353                         indices=self.vertexArray.getMappedIndices(index)
354                         for i in indices:
355                             baseMorph.add(i, pos)
356                             indexRelativeMap[i]=relativeIndex
357                             relativeIndex+=1
358                     break
359             print(len(baseMorph.offsets))
360             baseMorph.sort()
361             assert(basis)
362
363             # shape keys
364             vg=obj.getData(mesh=True).getVertsFromGroup(
365                         MMD_SHAPE_GROUP_NAME)
366             for b in obj.getData(mesh=True).key.blocks:
367                 if b.name=='Basis':
368                     continue
369
370                 print(b.name)
371                 morph=self.__getOrCreateMorph(b.name, 4)
372                 for index, src, dst in zip(
373                         xrange(len(blenderMesh.verts)),
374                         basis.data,
375                         b.data):
376                     offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
377                     if index in vg:
378                         indices=self.vertexArray.getMappedIndices(index)
379                         for i in indices:
380                             morph.add(indexRelativeMap[i], offset)
381                 assert(len(morph.offsets)==len(baseMorph.offsets))
382
383         # sort skinmap
384         original=self.morphList[:]
385         def getIndex(morph):
386             for i, v in enumerate(englishmap.skinMap):
387                 if v[0]==morph.name:
388                     return i
389             print(morph)
390         self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
391
392     def __getOrCreateMorph(self, name, type):
393         for m in self.morphList:
394             if m.name==name:
395                 return m
396         m=Morph(name, type)
397         self.morphList.append(m)
398         return m
399
400     def getVertexCount(self):
401         return len(self.vertexArray.vertices)
402
403
404 class Bone(object):
405     __slots__=['index', 'name', 'ik_index',
406             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
407     def __init__(self, name, pos, tail):
408         self.index=-1
409         self.name=name
410         self.pos=pos
411         self.tail=tail
412         self.parent_index=None
413         self.tail_index=None
414         self.type=0
415         self.isConnect=False
416         self.ik_index=0
417
418     def __eq__(self, rhs):
419         return self.index==rhs.index
420
421     def __str__(self):
422         return "<Bone %s %d>" % (self.name, self.type)
423
424 class BoneBuilder(object):
425     __slots__=['bones', 'boneMap', 'ik_list']
426     def __init__(self):
427         self.bones=[]
428         self.boneMap={}
429         self.ik_list=[]
430
431     def build(self, armatureObj):
432         if not armatureObj:
433             return
434
435         print("gather bones")
436         armature=armatureObj.getData()
437         for b in armature.bones.values():
438             if b.name=='center':
439                 # root bone
440                 bone=Bone(b.name, 
441                         b.head['ARMATURESPACE'][0:3], 
442                         b.tail['ARMATURESPACE'][0:3])
443                 self.__addBone(bone)
444                 self.__getBone(bone, b)
445
446         for b in armature.bones.values():
447             if not b.parent and b.name!='center':
448                 # root bone
449                 bone=Bone(b.name, 
450                         b.head['ARMATURESPACE'][0:3], 
451                         b.tail['ARMATURESPACE'][0:3])
452                 self.__addBone(bone)
453                 self.__getBone(bone, b)
454
455         print("check connection")
456         for b in armature.bones.values():
457             if not b.parent:
458                 self.__checkConnection(b, None)
459
460         print("gather ik")
461         pose = armatureObj.getPose()
462         cSetting=Blender.Constraint.Settings
463         for b in pose.bones.values():
464             for c in b.constraints:
465                 if c.type==Blender.Constraint.Type.IKSOLVER:
466                     ####################
467                     # IK target
468                     ####################
469                     assert(c[cSetting.TARGET]==armatureObj)
470                     target=self.__boneByName(
471                             c[Blender.Constraint.Settings.BONE])
472                     target.type=2
473
474                     ####################
475                     # IK effector
476                     ####################
477                     # IK 接続先
478                     link=self.__boneByName(b.name)
479                     link.type=6
480
481                     # IK chain
482                     e=b.parent
483                     chainLength=c[cSetting.CHAINLEN]
484                     for i in range(chainLength):
485                         # IK影響下
486                         chainBone=self.__boneByName(e.name)
487                         chainBone.type=4
488                         chainBone.ik_index=target.index
489                         e=e.parent
490                     self.ik_list.append(
491                             IKSolver(target, link, chainLength, 
492                                 int(c[cSetting.ITERATIONS] * 0.1), 
493                                 c[cSetting.ROTWEIGHT]
494                                 ))
495
496     def __checkConnection(self, b, p):
497         if Blender.Armature.CONNECTED in b.options:
498             parent=self.__boneByName(p.name)
499             parent.isConnect=True
500
501         for c in b.children:
502             self.__checkConnection(c, b)
503
504     def sortBy(self, boneMap):
505         """
506         boneMap順に並べ替える
507         """
508         original=self.bones[:]
509         def getIndex(bone):
510             for i, k_v in enumerate(boneMap):
511                 if k_v[0]==bone.name:
512                     return i
513             print(bone)
514
515         self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
516         sortMap={}
517         for i, b in enumerate(self.bones):
518             src=original.index(b)
519             sortMap[src]=i
520         for b in self.bones:
521             b.index=sortMap[b.index]
522             if b.parent_index:
523                 b.parent_index=sortMap[b.parent_index]
524             if b.tail_index:
525                 b.tail_index=sortMap[b.tail_index]
526             if b.ik_index>0:
527                 b.ik_index=sortMap[b.ik_index]
528
529     def getIndex(self, bone):
530         for i, b in enumerate(self.bones):
531             if b==bone:
532                 return i
533         assert(false)
534
535     def indexByName(self, name):
536         return self.getIndex(self.__boneByName(name))
537
538     def __boneByName(self, name):
539         return self.bones[self.boneMap[name]]
540                     
541     def __getBone(self, parent, b):
542         if len(b.children)==0:
543             parent.type=7
544             return
545
546         for i, c in enumerate(b.children):
547             bone=Bone(c.name, 
548                     c.head['ARMATURESPACE'][0:3], 
549                     c.tail['ARMATURESPACE'][0:3])
550             self.__addBone(bone)
551             if parent:
552                 bone.parent_index=parent.index
553                 if i==0:
554                     parent.tail_index=bone.index
555             self.__getBone(bone, c)
556
557     def __addBone(self, bone):
558         bone.index=len(self.bones)
559         self.bones.append(bone)
560         self.boneMap[bone.name]=bone.index
561
562
563 class PmdExporter(object):
564
565     def __init__(self):
566         self.armatureObj=None
567
568     def setup(self, scene):
569         # 木構造を構築する
570         object_node_map={}
571         for o in scene.objects:
572             object_node_map[o]=Node(o)
573         for node in object_node_map.values():
574             if node.o.parent:
575                 object_node_map[node.o.parent].children.append(node)
576         # ルートを得る
577         root=object_node_map[scene.objects.active]
578
579         # ワンスキンメッシュを作る
580         self.oneSkinMesh=OneSkinMesh()
581         self.__createOneSkinMesh(root)
582         print(self.oneSkinMesh)
583         self.name=root.o.name
584
585         # skeleton
586         self.builder=BoneBuilder()
587         self.builder.build(self.armatureObj)
588         self.builder.sortBy(englishmap.boneMap)
589         def getIndex(ik):
590             for i, v in enumerate(englishmap.boneMap):
591                 if v[0]==ik.target.name:
592                     return i
593             return len(englishmap.boneMap)
594         self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
595
596     def __createOneSkinMesh(self, node):
597         ############################################################
598         # search armature modifier
599         ############################################################
600         for m in node.o.modifiers:
601             if m.name=="Armature":
602                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
603                 if not self.armatureObj:
604                     self.armatureObj=armatureObj
605                 elif self.armatureObj!=armatureObj:
606                     print "warning! found multiple armature. ignored.", armatureObj.name
607
608         if node.o.getType()=='Mesh':
609             self.oneSkinMesh.addMesh(node.o)
610
611         for child in node.children:
612             self.__createOneSkinMesh(child)
613
614     def write(self, path):
615         io=pmd.IO()
616         io.name=self.name
617         io.comment="blender export"
618         io.version=1.0
619
620         # 頂点
621         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
622             # convert right-handed z-up to left-handed y-up
623             v=io.addVertex()
624             v.pos.x=pos[0]
625             v.pos.y=pos[2]
626             v.pos.z=pos[1]
627             v.normal.x=normal[0]
628             v.normal.y=normal[2]
629             v.normal.z=normal[1]
630             v.uv.x=uv[0]
631             v.uv.y=uv[1]
632             v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
633             v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
634             v.weight0=int(100*weight)
635             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
636
637         # 面とマテリアル
638         vertexCount=self.oneSkinMesh.getVertexCount()
639         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
640             m=Blender.Material.Get(m)
641             # マテリアル
642             material=io.addMaterial()
643             material.diffuse.r=m.R
644             material.diffuse.g=m.G
645             material.diffuse.b=m.B
646             material.diffuse.a=m.alpha
647             material.sinness=0 if m.spec<1e-5 else m.spec*10
648             material.specular.r=m.specR
649             material.specular.g=m.specG
650             material.specular.b=m.specB
651             material.ambient.r=m.mirR
652             material.ambient.g=m.mirG
653             material.ambient.b=m.mirB
654             material.vertex_count=len(indices)
655             material.toon_index=0
656             material.flag=1 if m.enableSSS else 0
657             # ToDo
658             material.texture=""
659             # 面
660             for i in indices:
661                 assert(i<vertexCount)
662             for i in xrange(0, len(indices), 3):
663                 # reverse triangle
664                 io.indices.append(indices[i+2])
665                 io.indices.append(indices[i+1])
666                 io.indices.append(indices[i])
667
668                 #io.indices.append(indices[i])
669                 #io.indices.append(indices[i+1])
670                 #io.indices.append(indices[i+2])
671
672         # bones
673         for b in self.builder.bones:
674             if b.name.endswith("_t"):
675                 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
676                     # skip
677                     print "skip %s" % b.name
678                     continue
679
680             bone=io.addBone()
681
682             v=englishmap.getUnicodeBoneName(b.name)
683             assert(v)
684             cp932=v[1].encode('cp932')
685             bone_name="%s" % cp932
686             assert(len(bone_name)<20)
687             bone.name=bone_name
688
689             bone_english_name="%s" % b.name
690             assert(len(bone_english_name)<20)
691             bone.english_name=bone_english_name
692
693             if len(v)>=3:
694                 # has type
695                 if v[2]==5:
696                     b.ik_index=self.builder.indexByName('eyes')
697                 bone.type=v[2]
698             else:
699                 bone.type=b.type
700
701             # parent index
702             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
703
704             # tail index
705             if b.tail_index!=None:
706                 if bone.type==9:
707                     bone.tail_index=0
708                 else:
709                     bone.tail_index=b.tail_index
710             else:
711                 bone.tail_index=0
712
713             bone.ik_index=b.ik_index
714
715             # convert right-handed z-up to left-handed y-up
716             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
717             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
718             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
719
720         # IK
721         for ik in self.builder.ik_list:
722             solver=io.addIK()
723             solver.index=self.builder.getIndex(ik.target)
724             solver.target=self.builder.getIndex(ik.effector)
725             solver.length=ik.length
726             b=self.builder.bones[ik.effector.parent_index]
727             for i in xrange(solver.length):
728                 solver.children.append(self.builder.getIndex(b))
729                 b=self.builder.bones[b.parent_index]
730             solver.iterations=ik.iterations
731             solver.weight=ik.weight
732
733         # 表情
734         for i, m in enumerate(self.oneSkinMesh.morphList):
735             # morph
736             morph=io.addMorph()
737
738             v=englishmap.getUnicodeSkinName(m.name)
739             assert(v)
740             cp932=v[1].encode('cp932')
741             morph.name="%s\n" % cp932
742
743             morph.english_name="%s\n" % m.name
744             m.type=v[2]
745             morph.type=v[2]
746             for index, offset in m.offsets:
747                 # convert right-handed z-up to left-handed y-up
748                 morph.append(index, offset[0], offset[2], offset[1])
749             morph.vertex_count=len(m.offsets)
750
751         # 表情枠
752         # type==0はbase
753         for i, m in enumerate(self.oneSkinMesh.morphList):
754             if m.type==3:
755                 io.face_list.append(i)
756         for i, m in enumerate(self.oneSkinMesh.morphList):
757             if m.type==2:
758                 io.face_list.append(i)
759         for i, m in enumerate(self.oneSkinMesh.morphList):
760             if m.type==1:
761                 io.face_list.append(i)
762         for i, m in enumerate(self.oneSkinMesh.morphList):
763             if m.type==4:
764                 io.face_list.append(i)
765
766         # ボーン表示枠
767         def createBoneDisplayName(name, english):
768             boneDisplayName=io.addBoneDisplayName()
769             boneDisplayName.name=name.decode('utf-8').encode('cp932')
770             boneDisplayName.english_name=english
771         boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
772         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
773         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
774         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
775         boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
776         boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
777         boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
778         for i, b in enumerate(self.builder.bones):
779             if i==0:
780                 continue
781             if b.type in [6, 7]:
782                 continue
783             io.addBoneDisplay(i, getBoneDisplayGroup(b))
784
785         # English
786         io.english_name="blender export"
787         io.english_coment="blender export"
788
789         for i in range(10):
790             io.getToonTexture(i).name="toon%02d.bmp\n" % i
791
792         # 書き込み
793         return io.write(path.encode(FS_ENCODING))
794
795
796 def getBoneDisplayGroup(bone):
797     boneGroups=[
798             [ # IK
799                 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
800                 "toe IK_L", "toe IK_R", 
801                 ],
802             [ # 体(上)
803                 "upper body", "neck", "head", "eye_L", "eye_R",
804                 "necktie1", "necktie2", "necktie3", "eyes", 
805                 "eyelight_L", "eyelight_R",
806                 ],
807             [ # 髪
808                 "front hair1", "front hair2", "front hair3",
809                 "hair1_L", "hair2_L", "hair3_L", 
810                 "hair4_L", "hair5_L", "hair6_L",
811                 "hair1_R", "hair2_R", "hair3_R", 
812                 "hair4_R", "hair5_R", "hair6_R",
813                 ],
814             [ # 腕
815                 "shoulder_L", "arm_L", "arm twist_L", "elbow_L", 
816                 "wrist twist_L", "wrist_L", "sleeve_L", 
817                 "shoulder_R", "arm_R", "arm twist_R", "elbow_R", 
818                 "wrist twist_R", "wrist_R", "sleeve_R", 
819                 ],
820             [ # 指
821                 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
822                 "middle1_L", "middle2_L", "middle3_L",
823                 "third1_L", "third2_L", "third3_L",
824                 "little1_L", "little2_L", "little3_L",
825                 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
826                 "middle1_R", "middle2_R", "middle3_R",
827                 "third1_R", "third2_R", "third3_R",
828                 "little1_R", "little2_R", "little3_R",
829                 ],
830             [ # 体(下)
831                 "lower body",  "waist accessory", 
832                 "front skirt_L", "back skirt_L",
833                 "front skirt_R", "back skirt_R",
834                 ],
835             [ # 足
836                 "leg_L", "knee_L", "ankle_L",
837                 "leg_R", "knee_R", "ankle_R",
838                 ],
839             ]
840     index=1
841     for g in boneGroups:
842         if bone.name in g:
843             return index
844         index+=1
845     print(bone)
846     return -1
847
848 def export_pmd(filename):
849     filename=filename.decode(INTERNAL_ENCODING)
850
851     Blender.Window.WaitCursor(1) 
852     t = Blender.sys.time() 
853
854     if not filename.lower().endswith(EXTENSION):
855         filename += EXTENSION
856     print "pmd exporter: %s" % filename
857
858     exporter=PmdExporter()
859
860     # 情報収集
861     exporter.setup(Blender.Scene.GetCurrent())
862
863     # 出力
864     exporter.write(filename)
865
866     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
867     Blender.Redraw()
868     Blender.Window.WaitCursor(0) 
869  
870
871 Blender.Window.FileSelector(
872         export_pmd,
873         'Export Metasequoia PMD',
874         Blender.sys.makename(ext=EXTENSION))
875