OSDN Git Service

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