OSDN Git Service

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