OSDN Git Service

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