OSDN Git Service

Merge branch 'master' of git.sourceforge.jp:/gitroot/meshio/MeshIO
[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__= "2.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 1.3 20100619: fix rigid body, bone weight.
23 1.4 20100626: refactoring.
24 1.5 20100629: sphere map.
25 1.6 20100710: toon texture & bone group.
26 1.7 20100711: separate vertex with normal or uv.
27 2.0 20100724: update for Blender2.53.
28 2.1 20100731: add full python module.
29 2.2 20101005: update for Blender2.54.
30 """
31
32 bl_addon_info = {
33         'category': 'Import/Export',
34         'name': 'Export: MikuMikuDance Model Format (.pmd)',
35         'author': 'ousttrue',
36         'version': (2, 2),
37         'blender': (2, 5, 3),
38         'location': 'File > Export',
39         'description': 'Export to the MikuMikuDance Model Format (.pmd)',
40         'warning': '', # used for warning icon and text in addons panel
41         'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
42         'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
43         }
44
45 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
46 MMD_MB_NAME='mb_name'
47 MMD_MB_COMMENT='mb_comment'
48 MMD_COMMENT='comment'
49 BASE_SHAPE_NAME='Basis'
50 RIGID_NAME='rigid_name'
51 RIGID_SHAPE_TYPE='rigid_shape_type'
52 RIGID_PROCESS_TYPE='rigid_process_type'
53 RIGID_BONE_NAME='rigid_bone_name'
54 #RIGID_LOCATION='rigid_loation'
55 RIGID_GROUP='ribid_group'
56 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
57 RIGID_WEIGHT='rigid_weight'
58 RIGID_LINEAR_DAMPING='rigid_linear_damping'
59 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
60 RIGID_RESTITUTION='rigid_restitution'
61 RIGID_FRICTION='rigid_friction'
62 CONSTRAINT_NAME='constraint_name'
63 CONSTRAINT_A='const_a'
64 CONSTRAINT_B='const_b'
65 CONSTRAINT_POS_MIN='const_pos_min'
66 CONSTRAINT_POS_MAX='const_pos_max'
67 CONSTRAINT_ROT_MIN='const_rot_min'
68 CONSTRAINT_ROT_MAX='const_rot_max'
69 CONSTRAINT_SPRING_POS='const_spring_pos'
70 CONSTRAINT_SPRING_ROT='const_spring_rot'
71 TOON_TEXTURE_OBJECT='ToonTextures'
72
73
74 ###############################################################################
75 # import
76 ###############################################################################
77 import os
78 import sys
79
80 try:
81     # C extension
82     from meshio import pmd, englishmap
83     print('use meshio C module')
84 except ImportError:
85     # full python
86     from pymeshio import englishmap
87     from pymeshio import mmd as pmd
88     pmd.IO=pmd.PMDLoader
89
90 def isBlender24():
91     return sys.version_info[0]<3
92
93 if isBlender24():
94     # for 2.4
95     import Blender
96     from Blender import Mathutils
97     import bpy
98
99     # wrapper
100     import bl24 as bl
101
102     def setMaterialParams(material, m):
103         # diffuse
104         material.diffuse.r=m.R
105         material.diffuse.g=m.G
106         material.diffuse.b=m.B
107         material.diffuse.a=m.alpha
108         # specular
109         material.shinness=0 if m.spec<1e-5 else m.spec*10
110         material.specular.r=m.specR
111         material.specular.g=m.specG
112         material.specular.b=m.specB
113         # ambient
114         material.ambient.r=m.mirR
115         material.ambient.g=m.mirG
116         material.ambient.b=m.mirB
117         # flag
118         material.flag=1 if m.enableSSS else 0
119
120     def toCP932(s):
121         return s
122
123
124 else:
125     # for 2.5
126     import bpy
127     import mathutils
128
129     # wrapper
130     import bl25 as bl
131
132     xrange=range
133
134     def setMaterialParams(material, m):
135         # diffuse
136         material.diffuse.r=m.diffuse_color[0]
137         material.diffuse.g=m.diffuse_color[1]
138         material.diffuse.b=m.diffuse_color[2]
139         material.diffuse.a=m.alpha
140         # specular
141         material.shinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
142         material.specular.r=m.specular_color[0]
143         material.specular.g=m.specular_color[1]
144         material.specular.b=m.specular_color[2]
145         # ambient
146         material.ambient.r=m.mirror_color[0]
147         material.ambient.g=m.mirror_color[1]
148         material.ambient.b=m.mirror_color[2]
149         # flag
150         material.flag=1 if m.subsurface_scattering.enabled else 0
151         # toon
152         material.toon_index=7
153
154     def toCP932(s):
155         return s.encode('cp932')
156
157
158 class Node(object):
159     __slots__=['o', 'children']
160     def __init__(self, o):
161         self.o=o
162         self.children=[]
163
164
165 ###############################################################################
166 # Blenderのメッシュをワンスキンメッシュ化する
167 ###############################################################################
168 def near(x, y, EPSILON=1e-5):
169     d=x-y
170     return d>=-EPSILON and d<=EPSILON
171
172
173 class VertexAttribute(object):
174     __slots__=[
175             'nx', 'ny', 'nz', # normal
176             'u', 'v', # uv
177             ]
178     def __init__(self, nx, ny, nz, u, v):
179         self.nx=nx
180         self.ny=ny
181         self.nz=nz
182         self.u=u
183         self.v=v
184
185     def __str__(self):
186         return "<vkey: %f, %f, %f, %f, %f>" % (
187                 self.nx, self.ny, self.nz, self.u, self.v)
188
189     def __hash__(self):
190         return self.nx + self.ny + self.nz + self.u + self.v
191
192     def __eq__(self, rhs):
193         return self.nx==rhs.nx and self.ny==rhs.ny and self.nz==rhs.nz and self.u==rhs.u and self.v==rhs.v
194
195
196 class VertexKey(object):
197     __slots__=[
198             'obj_index', 'index',
199             ]
200
201     def __init__(self, obj_index, index):
202         self.obj_index=obj_index
203         self.index=index
204
205     def __str__(self):
206         return "<vkey: %d, %d>" % (self.obj_index, self.index)
207
208     def __hash__(self):
209         return self.index*100+self.obj_index
210
211     def __eq__(self, rhs):
212         return self.obj_index==rhs.obj_index and self.index==rhs.index
213
214
215 class VertexArray(object):
216     """
217     頂点配列
218     """
219     __slots__=[
220             'indexArrays',
221             'positions',
222             'attributes', # normal and uv
223             'b0', 'b1', 'weight',
224             'vertexMap',
225             'objectMap',
226             ]
227     def __init__(self):
228         # indexArrays split with each material
229         self.indexArrays={}
230
231         self.positions=[]
232         self.attributes=[]
233         self.b0=[]
234         self.b1=[]
235         self.weight=[]
236
237         self.vertexMap={}
238         self.objectMap={}
239
240     def __str__(self):
241         return "<VertexArray %d positions, %d indexArrays>" % (
242                 len(self.positions), len(self.indexArrays))
243
244     def zip(self):
245         return zip(
246                 self.positions, self.attributes,
247                 self.b0, self.b1, self.weight)
248
249     def each(self):
250         keys=[key for key in self.indexArrays.keys()]
251         keys.sort()
252         for key in keys:
253             yield(key, self.indexArrays[key])
254
255     def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
256         key=VertexKey(obj_index, base_index)
257         attribute=VertexAttribute( 
258                 normal[0], normal[1], normal[2],
259                 uv[0], uv[1])
260         if key in self.vertexMap:
261             if attribute in self.vertexMap[key]:
262                 return self.vertexMap[key][attribute]
263             else:
264                 return self.__addVertex(self.vertexMap[key],
265                         pos, attribute, b0, b1, weight0)
266         else:
267             vertexMapKey={}
268             self.vertexMap[key]=vertexMapKey
269             return self.__addVertex(vertexMapKey,
270                     pos, attribute, b0, b1, weight0)
271
272     def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
273         index=len(self.positions)
274         vertexMapKey[attribute]=index
275         # position
276         self.positions.append((pos.x, pos.y, pos.z))
277         # unique attribute
278         self.attributes.append(attribute)
279         # shared attribute
280         self.b0.append(b0)
281         self.b1.append(b1)
282         self.weight.append(weight0)
283         assert(index<=65535)
284         return index
285             
286     def getMappedIndex(self, obj_name, base_index):
287         return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
288
289     def addTriangle(self,
290             object_name, material,
291             base_index0, base_index1, base_index2,
292             pos0, pos1, pos2,
293             n0, n1, n2,
294             uv0, uv1, uv2,
295             b0_0, b0_1, b0_2,
296             b1_0, b1_1, b1_2,
297             weight0, weight1, weight2
298             ):
299         if object_name in self.objectMap:
300             obj_index=self.objectMap[object_name]
301         else:
302             obj_index=len(self.objectMap)
303             self.objectMap[object_name]=obj_index
304         index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
305         index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
306         index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
307
308         if not material in self.indexArrays:
309             self.indexArrays[material]=[]
310         self.indexArrays[material]+=[index0, index1, index2]
311
312
313 class Morph(object):
314     __slots__=['name', 'type', 'offsets']
315     def __init__(self, name, type):
316         self.name=name
317         self.type=type
318         self.offsets=[]
319
320     def add(self, index, offset):
321         self.offsets.append((index, offset))
322
323     def sort(self):
324         if isBlender24():
325             self.offsets.sort(lambda l, r: l[0]-r[0])
326         else:
327             self.offsets.sort(key=lambda e: e[0])
328
329     def __str__(self):
330         return "<Morph %s>" % self.name
331
332 class IKSolver(object):
333     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
334     def __init__(self, target, effector, length, iterations, weight):
335         self.target=target
336         self.effector=effector
337         self.length=length
338         self.iterations=iterations
339         self.weight=weight
340
341
342 class OneSkinMesh(object):
343     __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
344     def __init__(self):
345         self.vertexArray=VertexArray()
346         self.morphList=[]
347         self.rigidbodies=[]
348         self.constraints=[]
349
350     def __str__(self):
351         return "<OneSkinMesh %s, morph:%d>" % (
352                 self.vertexArray,
353                 len(self.morphList))
354
355     def addMesh(self, obj):
356         if not bl.object.isVisible(obj):
357             return
358         self.__mesh(obj)
359         self.__skin(obj)
360         self.__rigidbody(obj)
361         self.__constraint(obj)
362
363     def __getWeightMap(self, obj, mesh):
364         # bone weight
365         weightMap={}
366         secondWeightMap={}
367         def setWeight(i, name, w):
368             if w>0:
369                 if i in weightMap:
370                     if i in secondWeightMap:
371                         # 上位2つのweightを採用する
372                         if w<secondWeightMap[i][1]:
373                             pass
374                         elif w<weightMap[i][1]:
375                             # 2つ目を入れ替え
376                             secondWeightMap[i]=(name, w)
377                         else:
378                             # 1つ目を入れ替え
379                             weightMap[i]=(name, w)
380                     else:
381                         if w>weightMap[i][1]:
382                             # 多い方をweightMapに
383                             secondWeightMap[i]=weightMap[i]
384                             weightMap[i]=(name, w)
385                         else:
386                             secondWeightMap[i]=(name, w)
387                 else:
388                     weightMap[i]=(name, w)
389
390         # ToDo bone weightと関係ないvertex groupを除外する
391         if isBlender24():
392             for name in bl.object.getVertexGroupNames(obj):
393                 for i, w in mesh.getVertsFromGroup(name, 1):
394                     setWeight(i, name, w)
395         else:
396             for i, v in enumerate(mesh.verts):
397                 if len(v.groups)>0:
398                     for g in v.groups:
399                         setWeight(i, obj.vertex_groups[g.group].name, g.weight)
400                 else:
401                     setWeight(i, obj.vertex_groups[0].name, 1)
402
403         # 合計値が1になるようにする
404         for i in xrange(len(mesh.verts)):
405             if i in secondWeightMap:
406                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
407             elif i in weightMap:
408                 weightMap[i]=(weightMap[i][0], 1.0)
409                 secondWeightMap[i]=("", 0)
410             else:
411                 print("no weight vertex")
412                 weightMap[i]=("", 0)
413                 secondWeightMap[i]=("", 0)
414
415         return weightMap, secondWeightMap
416
417     def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
418         # 各面の処理
419         for i, face in enumerate(mesh.faces):
420             faceVertexCount=bl.face.getVertexCount(face)
421             material=mesh.materials[bl.face.getMaterialIndex(face)]
422             v=[mesh.verts[index] for index in bl.face.getVertices(face)]
423             uv=bl.mesh.getFaceUV(
424                     mesh, i, face, bl.face.getVertexCount(face))
425             # flip triangle
426             if faceVertexCount==3:
427                 # triangle
428                 self.vertexArray.addTriangle(
429                         obj_name, material.name,
430                         v[2].index, 
431                         v[1].index, 
432                         v[0].index,
433                         v[2].co, 
434                         v[1].co, 
435                         v[0].co,
436                         bl.vertex.getNormal(v[2]), 
437                         bl.vertex.getNormal(v[1]), 
438                         bl.vertex.getNormal(v[0]),
439                         uv[2], 
440                         uv[1], 
441                         uv[0],
442                         weightMap[v[2].index][0],
443                         weightMap[v[1].index][0],
444                         weightMap[v[0].index][0],
445                         secondWeightMap[v[2].index][0],
446                         secondWeightMap[v[1].index][0],
447                         secondWeightMap[v[0].index][0],
448                         weightMap[v[2].index][1],
449                         weightMap[v[1].index][1],
450                         weightMap[v[0].index][1]
451                         )
452             elif faceVertexCount==4:
453                 # quadrangle
454                 self.vertexArray.addTriangle(
455                         obj_name, material.name,
456                         v[2].index, 
457                         v[1].index, 
458                         v[0].index,
459                         v[2].co, 
460                         v[1].co, 
461                         v[0].co,
462                         bl.vertex.getNormal(v[2]), 
463                         bl.vertex.getNormal(v[1]), 
464                         bl.vertex.getNormal(v[0]), 
465                         uv[2], 
466                         uv[1], 
467                         uv[0],
468                         weightMap[v[2].index][0],
469                         weightMap[v[1].index][0],
470                         weightMap[v[0].index][0],
471                         secondWeightMap[v[2].index][0],
472                         secondWeightMap[v[1].index][0],
473                         secondWeightMap[v[0].index][0],
474                         weightMap[v[2].index][1],
475                         weightMap[v[1].index][1],
476                         weightMap[v[0].index][1]
477                         )
478                 self.vertexArray.addTriangle(
479                         obj_name, material.name,
480                         v[0].index, 
481                         v[3].index, 
482                         v[2].index,
483                         v[0].co, 
484                         v[3].co, 
485                         v[2].co,
486                         bl.vertex.getNormal(v[0]), 
487                         bl.vertex.getNormal(v[3]), 
488                         bl.vertex.getNormal(v[2]), 
489                         uv[0], 
490                         uv[3], 
491                         uv[2],
492                         weightMap[v[0].index][0],
493                         weightMap[v[3].index][0],
494                         weightMap[v[2].index][0],
495                         secondWeightMap[v[0].index][0],
496                         secondWeightMap[v[3].index][0],
497                         secondWeightMap[v[2].index][0],
498                         weightMap[v[0].index][1],
499                         weightMap[v[3].index][1],
500                         weightMap[v[2].index][1]
501                         )
502
503     def __mesh(self, obj):
504         if isBlender24():
505             pass
506         else:
507             if RIGID_SHAPE_TYPE in obj:
508                 return
509             if CONSTRAINT_A in obj:
510                 return
511
512         #if not bl.modifier.hasType(obj, 'ARMATURE'):
513         #    return
514
515         bl.message("export: %s" % obj.name)
516
517         # メッシュのコピーを生成してオブジェクトの行列を適用する
518         copyMesh, copyObj=bl.object.duplicate(obj)
519         if len(copyMesh.verts)>0:
520             # apply transform
521             copyObj.scale=obj.scale
522             bpy.ops.object.scale_apply()
523             copyObj.rotation_euler=obj.rotation_euler
524             bpy.ops.object.rotation_apply()
525             copyObj.location=obj.location
526             bpy.ops.object.location_apply()
527             # apply modifier
528             for m in [m for m in copyObj.modifiers]:
529                 if m.type=='SOLIDFY':
530                     continue
531                 elif m.type=='ARMATURE':
532                     continue
533                 elif m.type=='MIRROR':
534                     bpy.ops.object.modifier_apply(modifier=m.name)
535                 else:
536                     print(m.type)
537
538             weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
539             self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
540         bl.object.delete(copyObj)
541
542     def createEmptyBasicSkin(self):
543         self.__getOrCreateMorph('base', 0)
544
545     def __skin(self, obj):
546         if not bl.object.hasShapeKey(obj):
547             return
548
549         indexRelativeMap={}
550         blenderMesh=bl.object.getData(obj)
551         baseMorph=None
552
553         # shape keys
554         vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
555
556         # base
557         used=set()
558         for b in bl.object.getShapeKeys(obj):
559             if b.name==BASE_SHAPE_NAME:
560                 baseMorph=self.__getOrCreateMorph('base', 0)
561                 basis=b
562
563                 relativeIndex=0
564                 for index in vg:
565                     v=bl.shapekey.getByIndex(b, index)
566                     pos=[v[0], v[1], v[2]]
567
568                     indices=self.vertexArray.getMappedIndex(obj.name, index)
569                     for attribute, i in indices.items():
570                         if i in used:
571                             continue
572                         used.add(i)
573
574                         baseMorph.add(i, pos)
575                         indexRelativeMap[i]=relativeIndex
576                         relativeIndex+=1
577
578                 break
579         assert(basis)
580         print(basis.name, len(baseMorph.offsets))
581
582         if len(baseMorph.offsets)==0:
583             return
584
585         # shape keys
586         for b in bl.object.getShapeKeys(obj):
587             if b.name==BASE_SHAPE_NAME:
588                 continue
589
590             print(b.name)
591             morph=self.__getOrCreateMorph(b.name, 4)
592             used=set()
593             for index, src, dst in zip(
594                     xrange(len(blenderMesh.verts)),
595                     bl.shapekey.get(basis),
596                     bl.shapekey.get(b)):
597                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
598                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
599                     continue
600                 if index in vg:
601                     indices=self.vertexArray.getMappedIndex(obj.name, index)
602                     for attribute, i in indices.items():
603                         if i in used:
604                             continue
605                         used.add(i) 
606                         morph.add(indexRelativeMap[i], offset)
607             assert(len(morph.offsets)<len(baseMorph.offsets))
608
609         # sort skinmap
610         original=self.morphList[:]
611         def getIndex(morph):
612             for i, v in enumerate(englishmap.skinMap):
613                 if v[0]==morph.name:
614                     return i
615             print(morph)
616             return len(englishmap.skinMap)
617         if isBlender24():
618             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
619         else:
620             self.morphList.sort(key=getIndex)
621
622     def __rigidbody(self, obj):
623         if isBlender24():
624             return
625         if not RIGID_SHAPE_TYPE in obj:
626             return
627         self.rigidbodies.append(obj)
628
629     def __constraint(self, obj):
630         if isBlender24():
631             return
632         if not CONSTRAINT_A in obj:
633             return
634         self.constraints.append(obj)
635
636     def __getOrCreateMorph(self, name, type):
637         for m in self.morphList:
638             if m.name==name:
639                 return m
640         m=Morph(name, type)
641         self.morphList.append(m)
642         return m
643
644     def getVertexCount(self):
645         return len(self.vertexArray.positions)
646
647
648 class Bone(object):
649     __slots__=['index', 'name', 'ik_index',
650             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
651     def __init__(self, name, pos, tail, isConnect):
652         self.index=-1
653         self.name=name
654         self.pos=pos
655         self.tail=tail
656         self.parent_index=None
657         self.tail_index=None
658         self.type=0
659         self.isConnect=isConnect
660         self.ik_index=0
661
662     def __eq__(self, rhs):
663         return self.index==rhs.index
664
665     def __str__(self):
666         return "<Bone %s %d>" % (self.name, self.type)
667
668 class BoneBuilder(object):
669     __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
670     def __init__(self):
671         self.bones=[]
672         self.boneMap={}
673         self.ik_list=[]
674         self.bone_groups=[]
675
676     def getBoneGroup(self, bone):
677         for i, g in enumerate(self.bone_groups):
678             for b in g[1]:
679                 if b==bone.name:
680                     return i+1
681         print('no gorup', bone)
682         return 0
683
684     def build(self, armatureObj):
685         if not armatureObj:
686             return
687
688         bl.message("build skeleton")
689         armature=bl.object.getData(armatureObj)
690
691         ####################
692         # bone group
693         ####################
694         for g in bl.object.boneGroups(armatureObj):
695             self.bone_groups.append((g.name, []))
696
697         ####################
698         # get bones
699         ####################
700         for b in armature.bones.values():
701             if not b.parent:
702                 # root bone
703                 bone=Bone(b.name, 
704                         bl.bone.getHeadLocal(b),
705                         bl.bone.getTailLocal(b),
706                         False)
707                 self.__addBone(bone)
708                 self.__getBone(bone, b)
709
710         for b in armature.bones.values():
711             if not b.parent:
712                 self.__checkConnection(b, None)
713
714         ####################
715         # get IK
716         ####################
717         pose = bl.object.getPose(armatureObj)
718         for b in pose.bones.values():
719             ####################
720             # assing bone group
721             ####################
722             self.__assignBoneGroup(b, b.bone_group)
723             for c in b.constraints:
724                 if bl.constraint.isIKSolver(c):
725                     ####################
726                     # IK target
727                     ####################
728                     target=self.__boneByName(bl.constraint.ikTarget(c))
729                     target.type=2
730
731                     ####################
732                     # IK effector
733                     ####################
734                     # IK 接続先
735                     link=self.__boneByName(b.name)
736                     link.type=6
737
738                     # IK chain
739                     e=b.parent
740                     chainLength=bl.constraint.ikChainLen(c)
741                     for i in range(chainLength):
742                         # IK影響下
743                         chainBone=self.__boneByName(e.name)
744                         chainBone.type=4
745                         chainBone.ik_index=target.index
746                         e=e.parent
747                     self.ik_list.append(
748                             IKSolver(target, link, chainLength, 
749                                 int(bl.constraint.ikItration(c) * 0.1), 
750                                 bl.constraint.ikRotationWeight(c)
751                                 ))
752
753         ####################
754
755         # boneのsort
756         self._sortBy()
757         self._fix()
758         # IKのsort
759         def getIndex(ik):
760             for i, v in enumerate(englishmap.boneMap):
761                 if v[0]==ik.target.name:
762                     return i
763             return len(englishmap.boneMap)
764         if isBlender24():
765             self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
766         else:
767             self.ik_list.sort(key=getIndex)
768
769     def __assignBoneGroup(self, poseBone, boneGroup):
770         if boneGroup:
771             for g in self.bone_groups:
772                 if g[0]==boneGroup.name:
773                     g[1].append(poseBone.name)
774
775     def __checkConnection(self, b, p):
776         if bl.bone.isConnected(b):
777             parent=self.__boneByName(p.name)
778             parent.isConnect=True
779
780         for c in b.children:
781             self.__checkConnection(c, b)
782
783     def _sortBy(self):
784         """
785         boneMap順に並べ替える
786         """
787         boneMap=englishmap.boneMap
788         original=self.bones[:]
789         def getIndex(bone):
790             for i, k_v in enumerate(boneMap):
791                 if k_v[0]==bone.name:
792                     return i
793             print(bone)
794             return len(boneMap)
795
796         if isBlender24():
797             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
798         else:
799             self.bones.sort(key=getIndex)
800
801         sortMap={}
802         for i, b in enumerate(self.bones):
803             src=original.index(b)
804             sortMap[src]=i
805         for b in self.bones:
806             b.index=sortMap[b.index]
807             if b.parent_index:
808                 b.parent_index=sortMap[b.parent_index]
809             if b.tail_index:
810                 b.tail_index=sortMap[b.tail_index]
811             if b.ik_index>0:
812                 b.ik_index=sortMap[b.ik_index]
813
814     def _fix(self):
815         """
816         調整
817         """
818         for b in self.bones:
819             # parent index
820             if b.parent_index==None:
821                 b.parent_index=0xFFFF
822             else:
823                 if b.type==6 or b.type==7:
824                     # fix tail bone
825                     parent=self.bones[b.parent_index]
826                     #print('parnet', parent.name)
827                     parent.tail_index=b.index
828
829         for b in self.bones:
830             if b.tail_index==None:
831                 b.tail_index=0
832             elif b.type==9:
833                 b.tail_index==0
834
835     def getIndex(self, bone):
836         for i, b in enumerate(self.bones):
837             if b==bone:
838                 return i
839         assert(false)
840
841     def indexByName(self, name):
842         if name=='':
843             return 0
844         else:
845             return self.getIndex(self.__boneByName(name))
846
847     def __boneByName(self, name):
848         return self.boneMap[name]
849                     
850     def __getBone(self, parent, b):
851         if len(b.children)==0:
852             parent.type=7
853             return
854
855         for i, c in enumerate(b.children):
856             bone=Bone(c.name, 
857                     bl.bone.getHeadLocal(c),
858                     bl.bone.getTailLocal(c),
859                     bl.bone.isConnected(c))
860             self.__addBone(bone)
861             if parent:
862                 bone.parent_index=parent.index
863                 #if i==0:
864                 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
865                     parent.tail_index=bone.index
866             self.__getBone(bone, c)
867
868     def __addBone(self, bone):
869         bone.index=len(self.bones)
870         self.bones.append(bone)
871         self.boneMap[bone.name]=bone
872
873
874 class PmdExporter(object):
875
876     __slots__=[
877             'armatureObj',
878             'oneSkinMesh',
879             'englishName',
880             'englishComment',
881             'name',
882             'comment',
883             'skeleton',
884             ]
885     def setup(self):
886         self.armatureObj=None
887
888         # 木構造を構築する
889         object_node_map={}
890         for o in bl.object.each():
891             object_node_map[o]=Node(o)
892         for o in bl.object.each():
893             node=object_node_map[o]
894             if node.o.parent:
895                 object_node_map[node.o.parent].children.append(node)
896
897         # ルートを得る
898         root=object_node_map[bl.object.getActive()]
899         o=root.o
900         self.englishName=o.name
901         self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
902         self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
903         self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
904
905         # ワンスキンメッシュを作る
906         self.oneSkinMesh=OneSkinMesh()
907         self.__createOneSkinMesh(root)
908         bl.message(self.oneSkinMesh)
909         if len(self.oneSkinMesh.morphList)==0:
910             # create emtpy skin
911             self.oneSkinMesh.createEmptyBasicSkin()
912
913         # skeleton
914         self.skeleton=BoneBuilder()
915         self.skeleton.build(self.armatureObj)
916
917     def __createOneSkinMesh(self, node):
918         ############################################################
919         # search armature modifier
920         ############################################################
921         for m in node.o.modifiers:
922             if bl.modifier.isType(m, 'ARMATURE'):
923                 armatureObj=bl.modifier.getArmatureObject(m)
924                 if not self.armatureObj:
925                     self.armatureObj=armatureObj
926                 elif self.armatureObj!=armatureObj:
927                     print("warning! found multiple armature. ignored.", 
928                             armatureObj.name)
929
930         if node.o.type.upper()=='MESH':
931             self.oneSkinMesh.addMesh(node.o)
932
933         for child in node.children:
934             self.__createOneSkinMesh(child)
935
936     def write(self, path):
937         io=pmd.IO()
938         io.setName(toCP932(self.name))
939         io.setComment(toCP932(self.comment))
940         io.version=1.0
941
942         # 頂点
943         for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
944             # convert right-handed z-up to left-handed y-up
945             v=io.addVertex()
946             v.pos.x=pos[0]
947             v.pos.y=pos[2]
948             v.pos.z=pos[1]
949             v.normal.x=attribute.nx
950             v.normal.y=attribute.ny
951             v.normal.z=attribute.nz
952             v.uv.x=attribute.u
953             v.uv.y=1.0-attribute.v # reverse vertical
954             v.bone0=self.skeleton.indexByName(b0)
955             v.bone1=self.skeleton.indexByName(b1)
956             v.weight0=int(100*weight)
957             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
958
959         # 面とマテリアル
960         vertexCount=self.oneSkinMesh.getVertexCount()
961         for material_name, indices in self.oneSkinMesh.vertexArray.each():
962             #print('material:', material_name)
963             m=bl.material.get(material_name)
964             # マテリアル
965             material=io.addMaterial()
966             setMaterialParams(material, m)
967
968             material.vertex_count=len(indices)
969             material.toon_index=0
970             textures=[os.path.basename(path) 
971                 for path in bl.material.eachEnalbeTexturePath(m)]
972             if len(textures)>0:
973                 material.setTexture(toCP932('*'.join(textures)))
974             else:
975                 material.setTexture(toCP932(""))
976             # 面
977             for i in indices:
978                 assert(i<vertexCount)
979             for i in xrange(0, len(indices), 3):
980                 # reverse triangle
981                 io.indices.append(indices[i])
982                 io.indices.append(indices[i+1])
983                 io.indices.append(indices[i+2])
984
985         # bones
986         boneNameMap={}
987         for i, b in enumerate(self.skeleton.bones):
988             bone=io.addBone()
989
990             # name
991             boneNameMap[b.name]=i
992             v=englishmap.getUnicodeBoneName(b.name)
993             if not v:
994                 v=[b.name, b.name]
995             assert(v)
996             cp932=v[1].encode('cp932')
997             assert(len(cp932)<20)
998             bone.setName(cp932)
999
1000             # english name
1001             bone_english_name=toCP932(b.name)
1002             assert(len(bone_english_name)<20)
1003             bone.setEnglishName(bone_english_name)
1004
1005             if len(v)>=3:
1006                 # has type
1007                 if v[2]==5:
1008                     b.ik_index=self.skeleton.indexByName('eyes')
1009                 bone.type=v[2]
1010             else:
1011                 bone.type=b.type
1012
1013             bone.parent_index=b.parent_index
1014             bone.tail_index=b.tail_index
1015             bone.ik_index=b.ik_index
1016
1017             # convert right-handed z-up to left-handed y-up
1018             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
1019             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
1020             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
1021
1022         # IK
1023         for ik in self.skeleton.ik_list:
1024             solver=io.addIK()
1025             solver.index=self.skeleton.getIndex(ik.target)
1026             solver.target=self.skeleton.getIndex(ik.effector)
1027             solver.length=ik.length
1028             b=self.skeleton.bones[ik.effector.parent_index]
1029             for i in xrange(solver.length):
1030                 solver.children.append(self.skeleton.getIndex(b))
1031                 b=self.skeleton.bones[b.parent_index]
1032             solver.iterations=ik.iterations
1033             solver.weight=ik.weight
1034
1035         # 表情
1036         for i, m in enumerate(self.oneSkinMesh.morphList):
1037             # morph
1038             morph=io.addMorph()
1039
1040             v=englishmap.getUnicodeSkinName(m.name)
1041             if not v:
1042                 v=[m.name, m.name, 0]
1043             assert(v)
1044             cp932=v[1].encode('cp932')
1045             morph.setName(cp932)
1046             morph.setEnglishName(m.name.encode('cp932'))
1047             m.type=v[2]
1048             morph.type=v[2]
1049             for index, offset in m.offsets:
1050                 # convert right-handed z-up to left-handed y-up
1051                 morph.append(index, offset[0], offset[2], offset[1])
1052             morph.vertex_count=len(m.offsets)
1053
1054         # 表情枠
1055         # type==0はbase
1056         for i, m in enumerate(self.oneSkinMesh.morphList):
1057             if m.type==3:
1058                 io.face_list.append(i)
1059         for i, m in enumerate(self.oneSkinMesh.morphList):
1060             if m.type==2:
1061                 io.face_list.append(i)
1062         for i, m in enumerate(self.oneSkinMesh.morphList):
1063             if m.type==1:
1064                 io.face_list.append(i)
1065         for i, m in enumerate(self.oneSkinMesh.morphList):
1066             if m.type==4:
1067                 io.face_list.append(i)
1068
1069         # ボーングループ
1070         for g in self.skeleton.bone_groups:
1071             boneDisplayName=io.addBoneGroup()
1072             # name
1073             name=englishmap.getUnicodeBoneGroupName(g[0])
1074             if not name:
1075                 name=g[0]
1076             boneDisplayName.setName(toCP932(name+'\n'))
1077             # english
1078             englishName=g[0]
1079             boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1080
1081         # ボーングループメンバー
1082         for i, b in enumerate(self.skeleton.bones):
1083             if i==0:
1084                continue
1085             if b.type in [6, 7]:
1086                continue
1087             io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1088
1089         #assert(len(io.bones)==len(io.bone_display_list)+1)
1090
1091         # English
1092         io.setEnglishName(toCP932(self.englishName))
1093         io.setEnglishComment(toCP932(self.englishComment))
1094
1095         # toon
1096         toonMeshObject=None
1097         for o in bl.object.each():
1098             try:
1099                 if o.name.startswith(TOON_TEXTURE_OBJECT):
1100                     toonMeshObject=o
1101             except:
1102                 p(o.name)
1103             break
1104         if toonMeshObject:
1105             toonMesh=bl.object.getData(toonMeshObject)
1106             toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1107             for i in range(10):
1108                 t=bl.material.getTexture(toonMaterial, i)
1109                 if t:
1110                     io.getToonTexture(i).setName(toCP932(t.name))
1111                 else:
1112                     io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1113         else:
1114             for i in range(10):
1115                 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1116
1117         # rigid body
1118         rigidNameMap={}
1119         for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1120             name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
1121             print(name)
1122             rigidBody=io.addRigidBody()
1123             rigidBody.setName(name.encode('cp932'))
1124             rigidNameMap[name]=i
1125             boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1126             if boneIndex==0:
1127                 boneIndex=0xFFFF
1128                 bone=self.skeleton.bones[0]
1129             else:
1130                 bone=self.skeleton.bones[boneIndex]
1131             rigidBody.boneIndex=boneIndex
1132             #rigidBody.position.x=obj[RIGID_LOCATION][0]
1133             #rigidBody.position.y=obj[RIGID_LOCATION][1]
1134             #rigidBody.position.z=obj[RIGID_LOCATION][2]
1135             rigidBody.position.x=obj.location.x-bone.pos[0]
1136             rigidBody.position.y=obj.location.z-bone.pos[2]
1137             rigidBody.position.z=obj.location.y-bone.pos[1]
1138             rigidBody.rotation.x=-obj.rotation_euler[0]
1139             rigidBody.rotation.y=-obj.rotation_euler[2]
1140             rigidBody.rotation.z=-obj.rotation_euler[1]
1141             rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1142             rigidBody.group=obj[RIGID_GROUP]
1143             rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1144             rigidBody.weight=obj[RIGID_WEIGHT]
1145             rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1146             rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1147             rigidBody.restitution=obj[RIGID_RESTITUTION]
1148             rigidBody.friction=obj[RIGID_FRICTION]
1149             if obj[RIGID_SHAPE_TYPE]==0:
1150                 rigidBody.shapeType=pmd.SHAPE_SPHERE
1151                 rigidBody.w=obj.scale[0]
1152             elif obj[RIGID_SHAPE_TYPE]==1:
1153                 rigidBody.shapeType=pmd.SHAPE_BOX
1154                 rigidBody.w=obj.scale[0]
1155                 rigidBody.d=obj.scale[1]
1156                 rigidBody.h=obj.scale[2]
1157             elif obj[RIGID_SHAPE_TYPE]==2:
1158                 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1159                 rigidBody.w=obj.scale[0]
1160                 rigidBody.h=obj.scale[2]
1161
1162         # constraint
1163         for obj in self.oneSkinMesh.constraints:
1164             constraint=io.addConstraint()
1165             constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1166             constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1167             constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1168             constraint.pos.x=obj.location[0]
1169             constraint.pos.y=obj.location[2]
1170             constraint.pos.z=obj.location[1]
1171             constraint.rot.x=-obj.rotation_euler[0]
1172             constraint.rot.y=-obj.rotation_euler[2]
1173             constraint.rot.z=-obj.rotation_euler[1]
1174             constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1175             constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1176             constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1177             constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1178             constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1179             constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1180             constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1181             constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1182             constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1183             constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1184             constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1185             constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1186             constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1187             constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1188             constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1189             constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1190             constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1191             constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1192
1193         # 書き込み
1194         bl.message('write: %s' % path)
1195         return io.write(path)
1196
1197
1198 def __execute(filename):
1199     active=bl.object.getActive()
1200     if not active:
1201         print("abort. no active object.")
1202         return
1203     exporter=PmdExporter()
1204     exporter.setup()
1205     print(exporter)
1206     exporter.write(filename)
1207     bl.object.activate(active)
1208
1209
1210 if isBlender24():
1211     # for 2.4
1212     def execute_24(filename):
1213         bl.initialize('pmd_export', bpy.data.scenes.active)
1214         __execute(filename.decode(bl.INTERNAL_ENCODING))
1215         bl.finalize()
1216
1217     Blender.Window.FileSelector(
1218              execute_24,
1219              'Export Metasequoia PMD',
1220              Blender.sys.makename(ext='.pmd'))
1221
1222 else:
1223     # for 2.5
1224     def execute_25(filename, scene):
1225         bl.initialize('pmd_export', scene)
1226         __execute(filename)
1227         bl.finalize()
1228
1229     # operator
1230     class EXPORT_OT_pmd(bpy.types.Operator):
1231         '''Save a Metasequoia PMD file.'''
1232         bl_idname = "export_scene.pmd"
1233         bl_label = 'Export PMD'
1234
1235         # List of operator properties, the attributes will be assigned
1236         # to the class instance from the operator settings before calling.
1237         filepath = bpy.props.StringProperty()
1238         filename = bpy.props.StringProperty()
1239         directory = bpy.props.StringProperty()
1240
1241         def execute(self, context):
1242             execute_25(
1243                     self.properties.filepath, 
1244                     context.scene
1245                     )
1246             return 'FINISHED'
1247
1248         def invoke(self, context, event):
1249             wm=context.window_manager
1250             wm.add_fileselect(self)
1251             return 'RUNNING_MODAL'
1252
1253     # register menu
1254     def menu_func(self, context): 
1255         default_path=bpy.data.filepath.replace(".blend", ".pmd")
1256         self.layout.operator(
1257                 EXPORT_OT_pmd.bl_idname, 
1258                 text="Miku Miku Dance Model(.pmd)",
1259                 icon='PLUGIN'
1260                 ).filepath=default_path
1261
1262     def register():
1263         bpy.types.INFO_MT_file_export.append(menu_func)
1264
1265     def unregister():
1266         bpy.types.INFO_MT_file_export.remove(menu_func)
1267
1268     if __name__ == "__main__":
1269         register()
1270