OSDN Git Service

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