OSDN Git Service

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