OSDN Git Service

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