OSDN Git Service

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