OSDN Git Service

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