OSDN Git Service

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