OSDN Git Service

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