OSDN Git Service

update for blender2.59
[meshio/pymeshio.git] / blender25-meshio / export_pmd.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__= "2.5"
11 __url__=()
12 __bpydoc__="""
13 pmd Importer
14
15 This script exports a pmd model.
16
17 0.1 20100318: first implementation.
18 0.2 20100519: refactoring. use C extension.
19 1.0 20100530: implement basic features.
20 1.1 20100612: integrate 2.4 and 2.5.
21 1.2 20100616: implement rigid body.
22 1.3 20100619: fix rigid body, bone weight.
23 1.4 20100626: refactoring.
24 1.5 20100629: sphere map.
25 1.6 20100710: toon texture & bone group.
26 1.7 20100711: separate vertex with normal or uv.
27 2.0 20100724: update for Blender2.53.
28 2.1 20100731: add full python module.
29 2.2 20101005: update for Blender2.54.
30 2.3 20101228: update for Blender2.55.
31 2.4 20110429: update for Blender2.57b.
32 2.5 20110522: implement RigidBody and Constraint.
33 """
34
35 bl_addon_info = {
36         'category': 'Import/Export',
37         'name': 'Export: MikuMikuDance Model Format (.pmd)',
38         'author': 'ousttrue',
39         'version': (2, 2),
40         'blender': (2, 5, 3),
41         'location': 'File > Export',
42         'description': 'Export to the MikuMikuDance Model Format (.pmd)',
43         'warning': '', # used for warning icon and text in addons panel
44         'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
45         'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
46         }
47
48
49 ###############################################################################
50 # import
51 ###############################################################################
52 import os
53 import sys
54
55 try:
56     # C extension
57     from meshio import pmd, englishmap
58     print('use meshio C module')
59 except ImportError:
60     # full python
61     from pymeshio import englishmap
62     from pymeshio import pmd
63
64
65 # for 2.5
66 import bpy
67 import mathutils
68
69 # wrapper
70 import bl25 as bl
71
72 xrange=range
73
74 def setMaterialParams(material, m):
75     # diffuse
76     material.diffuse.r=m.diffuse_color[0]
77     material.diffuse.g=m.diffuse_color[1]
78     material.diffuse.b=m.diffuse_color[2]
79     material.diffuse.a=m.alpha
80     # specular
81     material.shinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
82     material.specular.r=m.specular_color[0]
83     material.specular.g=m.specular_color[1]
84     material.specular.b=m.specular_color[2]
85     # ambient
86     material.ambient.r=m.mirror_color[0]
87     material.ambient.g=m.mirror_color[1]
88     material.ambient.b=m.mirror_color[2]
89     # flag
90     material.flag=1 if m.subsurface_scattering.use else 0
91     # toon
92     material.toon_index=0
93
94 def toCP932(s):
95     return s.encode('cp932')
96
97
98 class Node(object):
99     __slots__=['o', 'children']
100     def __init__(self, o):
101         self.o=o
102         self.children=[]
103
104
105 ###############################################################################
106 # Blenderのメッシュをワンスキンメッシュ化する
107 ###############################################################################
108 def near(x, y, EPSILON=1e-5):
109     d=x-y
110     return d>=-EPSILON and d<=EPSILON
111
112
113 class VertexAttribute(object):
114     __slots__=[
115             'nx', 'ny', 'nz', # normal
116             'u', 'v', # uv
117             ]
118     def __init__(self, nx, ny, nz, u, v):
119         self.nx=nx
120         self.ny=ny
121         self.nz=nz
122         self.u=u
123         self.v=v
124
125     def __str__(self):
126         return "<vkey: %f, %f, %f, %f, %f>" % (
127                 self.nx, self.ny, self.nz, self.u, self.v)
128
129     def __hash__(self):
130         return int(100*(self.nx + self.ny + self.nz + self.u + self.v))
131
132     def __eq__(self, rhs):
133         return self.nx==rhs.nx and self.ny==rhs.ny and self.nz==rhs.nz and self.u==rhs.u and self.v==rhs.v
134
135
136 class VertexKey(object):
137     __slots__=[
138             'obj_index', 'index',
139             ]
140
141     def __init__(self, obj_index, index):
142         self.obj_index=obj_index
143         self.index=index
144
145     def __str__(self):
146         return "<vkey: %d, %d>" % (self.obj_index, self.index)
147
148     def __hash__(self):
149         return self.index*100+self.obj_index
150
151     def __eq__(self, rhs):
152         return self.obj_index==rhs.obj_index and self.index==rhs.index
153
154
155 class VertexArray(object):
156     """
157     頂点配列
158     """
159     __slots__=[
160             'indexArrays',
161             'positions',
162             'attributes', # normal and uv
163             'b0', 'b1', 'weight',
164             'vertexMap',
165             'objectMap',
166             ]
167     def __init__(self):
168         # indexArrays split with each material
169         self.indexArrays={}
170
171         self.positions=[]
172         self.attributes=[]
173         self.b0=[]
174         self.b1=[]
175         self.weight=[]
176
177         self.vertexMap={}
178         self.objectMap={}
179
180     def __str__(self):
181         return "<VertexArray %d positions, %d indexArrays>" % (
182                 len(self.positions), len(self.indexArrays))
183
184     def zip(self):
185         return zip(
186                 self.positions, self.attributes,
187                 self.b0, self.b1, self.weight)
188
189     def each(self):
190         keys=[key for key in self.indexArrays.keys()]
191         keys.sort()
192         for key in keys:
193             yield(key, self.indexArrays[key])
194
195     def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
196         key=VertexKey(obj_index, base_index)
197         attribute=VertexAttribute( 
198                 normal[0], normal[1], normal[2],
199                 uv[0], uv[1])
200         if key in self.vertexMap:
201             if attribute in self.vertexMap[key]:
202                 return self.vertexMap[key][attribute]
203             else:
204                 return self.__addVertex(self.vertexMap[key],
205                         pos, attribute, b0, b1, weight0)
206         else:
207             vertexMapKey={}
208             self.vertexMap[key]=vertexMapKey
209             return self.__addVertex(vertexMapKey,
210                     pos, attribute, b0, b1, weight0)
211
212     def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
213         index=len(self.positions)
214         vertexMapKey[attribute]=index
215         # position
216         self.positions.append((pos.x, pos.y, pos.z))
217         # unique attribute
218         self.attributes.append(attribute)
219         # shared attribute
220         self.b0.append(b0)
221         self.b1.append(b1)
222         self.weight.append(weight0)
223         assert(index<=65535)
224         return index
225             
226     def getMappedIndex(self, obj_name, base_index):
227         return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
228
229     def addTriangle(self,
230             object_name, material,
231             base_index0, base_index1, base_index2,
232             pos0, pos1, pos2,
233             n0, n1, n2,
234             uv0, uv1, uv2,
235             b0_0, b0_1, b0_2,
236             b1_0, b1_1, b1_2,
237             weight0, weight1, weight2
238             ):
239         if object_name in self.objectMap:
240             obj_index=self.objectMap[object_name]
241         else:
242             obj_index=len(self.objectMap)
243             self.objectMap[object_name]=obj_index
244         index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
245         index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
246         index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
247
248         if not material in self.indexArrays:
249             self.indexArrays[material]=[]
250         self.indexArrays[material]+=[index0, index1, index2]
251
252
253 class Morph(object):
254     __slots__=['name', 'type', 'offsets']
255     def __init__(self, name, type):
256         self.name=name
257         self.type=type
258         self.offsets=[]
259
260     def add(self, index, offset):
261         self.offsets.append((index, offset))
262
263     def sort(self):
264         self.offsets.sort(key=lambda e: e[0])
265
266     def __str__(self):
267         return "<Morph %s>" % self.name
268
269 class IKSolver(object):
270     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
271     def __init__(self, target, effector, length, iterations, weight):
272         self.target=target
273         self.effector=effector
274         self.length=length
275         self.iterations=iterations
276         self.weight=weight
277
278
279 class SSS(object):
280     def __init__(self):
281         self.use=1
282
283
284 class DefaultMatrial(object):
285     def __init__(self):
286         self.name='default'
287         # diffuse
288         self.diffuse_color=[1, 1, 1]
289         self.alpha=1
290         # specular
291         self.specular_toon_size=0
292         self.specular_hardness=5
293         self.specular_color=[1, 1, 1]
294         # ambient
295         self.mirror_color=[1, 1, 1]
296         # flag
297         self.subsurface_scattering=SSS()
298         # texture
299         self.texture_slots=[]
300
301
302 class OneSkinMesh(object):
303     __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
304     def __init__(self):
305         self.vertexArray=VertexArray()
306         self.morphList=[]
307         self.rigidbodies=[]
308         self.constraints=[]
309
310     def __str__(self):
311         return "<OneSkinMesh %s, morph:%d>" % (
312                 self.vertexArray,
313                 len(self.morphList))
314
315     def addMesh(self, obj):
316         if not bl.object.isVisible(obj):
317             return
318         self.__mesh(obj)
319         self.__skin(obj)
320         self.__rigidbody(obj)
321         self.__constraint(obj)
322
323     def __getWeightMap(self, obj, mesh):
324         # bone weight
325         weightMap={}
326         secondWeightMap={}
327         def setWeight(i, name, w):
328             if w>0:
329                 if i in weightMap:
330                     if i in secondWeightMap:
331                         # 上位2つのweightを採用する
332                         if w<secondWeightMap[i][1]:
333                             pass
334                         elif w<weightMap[i][1]:
335                             # 2つ目を入れ替え
336                             secondWeightMap[i]=(name, w)
337                         else:
338                             # 1つ目を入れ替え
339                             weightMap[i]=(name, w)
340                     else:
341                         if w>weightMap[i][1]:
342                             # 多い方をweightMapに
343                             secondWeightMap[i]=weightMap[i]
344                             weightMap[i]=(name, w)
345                         else:
346                             secondWeightMap[i]=(name, w)
347                 else:
348                     weightMap[i]=(name, w)
349
350         # ToDo bone weightと関係ないvertex groupを除外する
351         for i, v in enumerate(mesh.vertices):
352             if len(v.groups)>0:
353                 for g in v.groups:
354                     setWeight(i, obj.vertex_groups[g.group].name, g.weight)
355             else:
356                 try:
357                     setWeight(i, obj.vertex_groups[0].name, 1)
358                 except:
359                     # no vertex_groups
360                     pass
361
362         # 合計値が1になるようにする
363         for i in xrange(len(mesh.vertices)):
364             if i in secondWeightMap:
365                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
366             elif i in weightMap:
367                 weightMap[i]=(weightMap[i][0], 1.0)
368                 secondWeightMap[i]=("", 0)
369             else:
370                 print("no weight vertex")
371                 weightMap[i]=("", 0)
372                 secondWeightMap[i]=("", 0)
373
374         return weightMap, secondWeightMap
375
376     def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
377         default_material=DefaultMatrial()
378         # 各面の処理
379         for i, face in enumerate(mesh.faces):
380             faceVertexCount=bl.face.getVertexCount(face)
381             try:
382                 material=mesh.materials[bl.face.getMaterialIndex(face)]
383             except IndexError as e:
384                 material=default_material
385             v=[mesh.vertices[index] for index in bl.face.getVertices(face)]
386             uv=bl.mesh.getFaceUV(
387                     mesh, i, face, bl.face.getVertexCount(face))
388             # flip triangle
389             if faceVertexCount==3:
390                 # triangle
391                 self.vertexArray.addTriangle(
392                         obj_name, material.name,
393                         v[2].index, 
394                         v[1].index, 
395                         v[0].index,
396                         v[2].co, 
397                         v[1].co, 
398                         v[0].co,
399                         bl.vertex.getNormal(v[2]), 
400                         bl.vertex.getNormal(v[1]), 
401                         bl.vertex.getNormal(v[0]),
402                         uv[2], 
403                         uv[1], 
404                         uv[0],
405                         weightMap[v[2].index][0],
406                         weightMap[v[1].index][0],
407                         weightMap[v[0].index][0],
408                         secondWeightMap[v[2].index][0],
409                         secondWeightMap[v[1].index][0],
410                         secondWeightMap[v[0].index][0],
411                         weightMap[v[2].index][1],
412                         weightMap[v[1].index][1],
413                         weightMap[v[0].index][1]
414                         )
415             elif faceVertexCount==4:
416                 # quadrangle
417                 self.vertexArray.addTriangle(
418                         obj_name, material.name,
419                         v[2].index, 
420                         v[1].index, 
421                         v[0].index,
422                         v[2].co, 
423                         v[1].co, 
424                         v[0].co,
425                         bl.vertex.getNormal(v[2]), 
426                         bl.vertex.getNormal(v[1]), 
427                         bl.vertex.getNormal(v[0]), 
428                         uv[2], 
429                         uv[1], 
430                         uv[0],
431                         weightMap[v[2].index][0],
432                         weightMap[v[1].index][0],
433                         weightMap[v[0].index][0],
434                         secondWeightMap[v[2].index][0],
435                         secondWeightMap[v[1].index][0],
436                         secondWeightMap[v[0].index][0],
437                         weightMap[v[2].index][1],
438                         weightMap[v[1].index][1],
439                         weightMap[v[0].index][1]
440                         )
441                 self.vertexArray.addTriangle(
442                         obj_name, material.name,
443                         v[0].index, 
444                         v[3].index, 
445                         v[2].index,
446                         v[0].co, 
447                         v[3].co, 
448                         v[2].co,
449                         bl.vertex.getNormal(v[0]), 
450                         bl.vertex.getNormal(v[3]), 
451                         bl.vertex.getNormal(v[2]), 
452                         uv[0], 
453                         uv[3], 
454                         uv[2],
455                         weightMap[v[0].index][0],
456                         weightMap[v[3].index][0],
457                         weightMap[v[2].index][0],
458                         secondWeightMap[v[0].index][0],
459                         secondWeightMap[v[3].index][0],
460                         secondWeightMap[v[2].index][0],
461                         weightMap[v[0].index][1],
462                         weightMap[v[3].index][1],
463                         weightMap[v[2].index][1]
464                         )
465
466     def __mesh(self, obj):
467         if bl.RIGID_SHAPE_TYPE in obj:
468             return
469         if bl.CONSTRAINT_A in obj:
470             return
471
472         bl.message("export: %s" % obj.name)
473
474         # メッシュのコピーを生成してオブジェクトの行列を適用する
475         copyMesh, copyObj=bl.object.duplicate(obj)
476         if len(copyMesh.vertices)>0:
477             # apply transform
478             """
479             try:
480                 # svn 36722
481                 copyObj.scale=obj.scale
482                 bpy.ops.object.transform_apply(scale=True)
483                 copyObj.rotation_euler=obj.rotation_euler
484                 bpy.ops.object.transform_apply(rotation=True)
485                 copyObj.location=obj.location
486                 bpy.ops.object.transform_apply(location=True)
487             except AttributeError as e:
488                 # 2.57b
489                 copyObj.scale=obj.scale
490                 bpy.ops.object.scale_apply()
491                 copyObj.rotation_euler=obj.rotation_euler
492                 bpy.ops.object.rotation_apply()
493                 copyObj.location=obj.location
494                 bpy.ops.object.location_apply()
495             """
496             copyMesh.transform(obj.matrix_world)
497
498             # apply modifier
499             for m in [m for m in copyObj.modifiers]:
500                 if m.type=='SOLIDFY':
501                     continue
502                 elif m.type=='ARMATURE':
503                     continue
504                 elif m.type=='MIRROR':
505                     bpy.ops.object.modifier_apply(modifier=m.name)
506                 else:
507                     print(m.type)
508
509             weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
510             self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
511         bl.object.delete(copyObj)
512
513     def createEmptyBasicSkin(self):
514         self.__getOrCreateMorph('base', 0)
515
516     def __skin(self, obj):
517         if not bl.object.hasShapeKey(obj):
518             return
519
520         indexRelativeMap={}
521         blenderMesh=bl.object.getData(obj)
522         baseMorph=None
523
524         # shape keys
525         vg=bl.object.getVertexGroup(obj, bl.MMD_SHAPE_GROUP_NAME)
526
527         # base
528         used=set()
529         for b in bl.object.getShapeKeys(obj):
530             if b.name==bl.BASE_SHAPE_NAME:
531                 baseMorph=self.__getOrCreateMorph('base', 0)
532                 basis=b
533
534                 relativeIndex=0
535                 for index in vg:
536                     v=bl.shapekey.getByIndex(b, index)
537                     pos=[v[0], v[1], v[2]]
538
539                     indices=self.vertexArray.getMappedIndex(obj.name, index)
540                     for attribute, i in indices.items():
541                         if i in used:
542                             continue
543                         used.add(i)
544
545                         baseMorph.add(i, pos)
546                         indexRelativeMap[i]=relativeIndex
547                         relativeIndex+=1
548
549                 break
550         assert(basis)
551         #print(basis.name, len(baseMorph.offsets))
552
553         if len(baseMorph.offsets)==0:
554             return
555
556         # shape keys
557         for b in bl.object.getShapeKeys(obj):
558             if b.name==bl.BASE_SHAPE_NAME:
559                 continue
560
561             #print(b.name)
562             morph=self.__getOrCreateMorph(b.name, 4)
563             used=set()
564             for index, src, dst in zip(
565                     xrange(len(blenderMesh.vertices)),
566                     bl.shapekey.get(basis),
567                     bl.shapekey.get(b)):
568                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
569                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
570                     continue
571                 if index in vg:
572                     indices=self.vertexArray.getMappedIndex(obj.name, index)
573                     for attribute, i in indices.items():
574                         if i in used:
575                             continue
576                         used.add(i) 
577                         morph.add(indexRelativeMap[i], offset)
578             assert(len(morph.offsets)<len(baseMorph.offsets))
579
580         # sort skinmap
581         original=self.morphList[:]
582         def getIndex(morph):
583             for i, v in enumerate(englishmap.skinMap):
584                 if v[0]==morph.name:
585                     return i
586             #print(morph)
587             return len(englishmap.skinMap)
588         self.morphList.sort(key=getIndex)
589
590     def __rigidbody(self, obj):
591         if not bl.RIGID_SHAPE_TYPE in obj:
592             return
593         self.rigidbodies.append(obj)
594
595     def __constraint(self, obj):
596         if not bl.CONSTRAINT_A in obj:
597             return
598         self.constraints.append(obj)
599
600     def __getOrCreateMorph(self, name, type):
601         for m in self.morphList:
602             if m.name==name:
603                 return m
604         m=Morph(name, type)
605         self.morphList.append(m)
606         return m
607
608     def getVertexCount(self):
609         return len(self.vertexArray.positions)
610
611
612 class Bone(object):
613     __slots__=['index', 'name', 'ik_index',
614             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
615     def __init__(self, name, pos, tail, isConnect):
616         self.index=-1
617         self.name=name
618         self.pos=pos
619         self.tail=tail
620         self.parent_index=None
621         self.tail_index=None
622         self.type=0
623         self.isConnect=isConnect
624         self.ik_index=0
625
626     def __eq__(self, rhs):
627         return self.index==rhs.index
628
629     def __str__(self):
630         return "<Bone %s %d>" % (self.name, self.type)
631
632 class BoneBuilder(object):
633     __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
634     def __init__(self):
635         self.bones=[]
636         self.boneMap={}
637         self.ik_list=[]
638         self.bone_groups=[]
639
640     def getBoneGroup(self, bone):
641         for i, g in enumerate(self.bone_groups):
642             for b in g[1]:
643                 if b==bone.name:
644                     return i+1
645         print('no gorup', bone)
646         return 0
647
648     def build(self, armatureObj):
649         if not armatureObj:
650             return
651
652         bl.message("build skeleton")
653         armature=bl.object.getData(armatureObj)
654
655         ####################
656         # bone group
657         ####################
658         for g in bl.object.boneGroups(armatureObj):
659             self.bone_groups.append((g.name, []))
660
661         ####################
662         # get bones
663         ####################
664         for b in armature.bones.values():
665             if not b.parent:
666                 # root bone
667                 bone=Bone(b.name, 
668                         bl.bone.getHeadLocal(b),
669                         bl.bone.getTailLocal(b),
670                         False)
671                 self.__addBone(bone)
672                 self.__getBone(bone, b)
673
674         for b in armature.bones.values():
675             if not b.parent:
676                 self.__checkConnection(b, None)
677
678         ####################
679         # get IK
680         ####################
681         pose = bl.object.getPose(armatureObj)
682         for b in pose.bones.values():
683             ####################
684             # assing bone group
685             ####################
686             self.__assignBoneGroup(b, b.bone_group)
687             for c in b.constraints:
688                 if bl.constraint.isIKSolver(c):
689                     ####################
690                     # IK target
691                     ####################
692                     target=self.__boneByName(bl.constraint.ikTarget(c))
693                     target.type=2
694
695                     ####################
696                     # IK effector
697                     ####################
698                     # IK 接続先
699                     link=self.__boneByName(b.name)
700                     link.type=6
701
702                     # IK chain
703                     e=b.parent
704                     chainLength=bl.constraint.ikChainLen(c)
705                     for i in range(chainLength):
706                         # IK影響下
707                         chainBone=self.__boneByName(e.name)
708                         chainBone.type=4
709                         chainBone.ik_index=target.index
710                         e=e.parent
711                     self.ik_list.append(
712                             IKSolver(target, link, chainLength, 
713                                 int(bl.constraint.ikItration(c) * 0.1), 
714                                 bl.constraint.ikRotationWeight(c)
715                                 ))
716
717         ####################
718
719         # boneのsort
720         self._sortBy()
721         self._fix()
722         # IKのsort
723         def getIndex(ik):
724             for i, v in enumerate(englishmap.boneMap):
725                 if v[0]==ik.target.name:
726                     return i
727             return len(englishmap.boneMap)
728         self.ik_list.sort(key=getIndex)
729
730     def __assignBoneGroup(self, poseBone, boneGroup):
731         if boneGroup:
732             for g in self.bone_groups:
733                 if g[0]==boneGroup.name:
734                     g[1].append(poseBone.name)
735
736     def __checkConnection(self, b, p):
737         if bl.bone.isConnected(b):
738             parent=self.__boneByName(p.name)
739             parent.isConnect=True
740
741         for c in b.children:
742             self.__checkConnection(c, b)
743
744     def _sortBy(self):
745         """
746         boneMap順に並べ替える
747         """
748         boneMap=englishmap.boneMap
749         original=self.bones[:]
750         def getIndex(bone):
751             for i, k_v in enumerate(boneMap):
752                 if k_v[0]==bone.name:
753                     return i
754             print(bone)
755             return len(boneMap)
756
757         self.bones.sort(key=getIndex)
758
759         sortMap={}
760         for i, b in enumerate(self.bones):
761             src=original.index(b)
762             sortMap[src]=i
763         for b in self.bones:
764             b.index=sortMap[b.index]
765             if b.parent_index:
766                 b.parent_index=sortMap[b.parent_index]
767             if b.tail_index:
768                 b.tail_index=sortMap[b.tail_index]
769             if b.ik_index>0:
770                 b.ik_index=sortMap[b.ik_index]
771
772     def _fix(self):
773         """
774         調整
775         """
776         for b in self.bones:
777             # parent index
778             if b.parent_index==None:
779                 b.parent_index=0xFFFF
780             else:
781                 if b.type==6 or b.type==7:
782                     # fix tail bone
783                     parent=self.bones[b.parent_index]
784                     #print('parnet', parent.name)
785                     parent.tail_index=b.index
786
787         for b in self.bones:
788             if b.tail_index==None:
789                 b.tail_index=0
790             elif b.type==9:
791                 b.tail_index==0
792
793     def getIndex(self, bone):
794         for i, b in enumerate(self.bones):
795             if b==bone:
796                 return i
797         assert(false)
798
799     def indexByName(self, name):
800         if name=='':
801             return 0
802         else:
803             try:
804                 return self.getIndex(self.__boneByName(name))
805             except:
806                 return 0
807
808     def __boneByName(self, name):
809         return self.boneMap[name]
810
811     def __getBone(self, parent, b):
812         if len(b.children)==0:
813             parent.type=7
814             return
815
816         for i, c in enumerate(b.children):
817             bone=Bone(c.name, 
818                     bl.bone.getHeadLocal(c),
819                     bl.bone.getTailLocal(c),
820                     bl.bone.isConnected(c))
821             self.__addBone(bone)
822             if parent:
823                 bone.parent_index=parent.index
824                 #if i==0:
825                 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
826                     parent.tail_index=bone.index
827             self.__getBone(bone, c)
828
829     def __addBone(self, bone):
830         bone.index=len(self.bones)
831         self.bones.append(bone)
832         self.boneMap[bone.name]=bone
833
834
835 class PmdExporter(object):
836
837     __slots__=[
838             'armatureObj',
839             'oneSkinMesh',
840             'englishName',
841             'englishComment',
842             'name',
843             'comment',
844             'skeleton',
845             ]
846     def setup(self):
847         self.armatureObj=None
848
849         # 木構造を構築する
850         object_node_map={}
851         for o in bl.object.each():
852             object_node_map[o]=Node(o)
853         for o in bl.object.each():
854             node=object_node_map[o]
855             if node.o.parent:
856                 object_node_map[node.o.parent].children.append(node)
857
858         # ルートを得る
859         root=object_node_map[bl.object.getActive()]
860         o=root.o
861         self.englishName=o.name
862         self.englishComment=o[bl.MMD_COMMENT] if bl.MMD_COMMENT in o else 'blender export\n'
863         self.name=o[bl.MMD_MB_NAME] if bl.MMD_MB_NAME in o else 'Blenderエクスポート'
864         self.comment=o[bl.MMD_MB_COMMENT] if bl.MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
865
866         # ワンスキンメッシュを作る
867         self.oneSkinMesh=OneSkinMesh()
868         self.__createOneSkinMesh(root)
869         bl.message(self.oneSkinMesh)
870         if len(self.oneSkinMesh.morphList)==0:
871             # create emtpy skin
872             self.oneSkinMesh.createEmptyBasicSkin()
873
874         # skeleton
875         self.skeleton=BoneBuilder()
876         self.skeleton.build(self.armatureObj)
877
878     def __createOneSkinMesh(self, node):
879         ############################################################
880         # search armature modifier
881         ############################################################
882         for m in node.o.modifiers:
883             if bl.modifier.isType(m, 'ARMATURE'):
884                 armatureObj=bl.modifier.getArmatureObject(m)
885                 if not self.armatureObj:
886                     self.armatureObj=armatureObj
887                 elif self.armatureObj!=armatureObj:
888                     print("warning! found multiple armature. ignored.", 
889                             armatureObj.name)
890
891         if node.o.type.upper()=='MESH':
892             self.oneSkinMesh.addMesh(node.o)
893
894         for child in node.children:
895             self.__createOneSkinMesh(child)
896
897     def write(self, path):
898         io=pmd.IO()
899         io.name=self.name
900         io.comment=self.comment
901         io.version=1.0
902
903         # 頂点
904         for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
905             # convert right-handed z-up to left-handed y-up
906             v=io.addVertex()
907             v.pos.x=pos[0]
908             v.pos.y=pos[2]
909             v.pos.z=pos[1]
910             # convert right-handed z-up to left-handed y-up
911             v.normal.x=attribute.nx
912             v.normal.y=attribute.nz
913             v.normal.z=attribute.ny
914             v.uv.x=attribute.u
915             v.uv.y=1.0-attribute.v # reverse vertical
916             v.bone0=self.skeleton.indexByName(b0)
917             v.bone1=self.skeleton.indexByName(b1)
918             v.weight0=int(100*weight)
919             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
920
921         # 面とマテリアル
922         vertexCount=self.oneSkinMesh.getVertexCount()
923         for material_name, indices in self.oneSkinMesh.vertexArray.each():
924             #print('material:', material_name)
925             try:
926                 m=bl.material.get(material_name)
927             except KeyError as e:
928                 m=DefaultMatrial()
929             # マテリアル
930             material=io.addMaterial()
931             setMaterialParams(material, m)
932
933             material.vertex_count=len(indices)
934             def get_texture_name(texture):
935                 pos=texture.replace("\\", "/").rfind("/")
936                 if pos==-1:
937                     return texture
938                 else:
939                     return texture[pos+1:]
940             textures=[get_texture_name(path)
941                 for path in bl.material.eachEnalbeTexturePath(m)]
942             print(textures)
943             if len(textures)>0:
944                 material.texture='*'.join(textures)
945             else:
946                 material.texture=""
947             # 面
948             for i in indices:
949                 assert(i<vertexCount)
950             for i in xrange(0, len(indices), 3):
951                 # reverse triangle
952                 io.indices.append(indices[i])
953                 io.indices.append(indices[i+1])
954                 io.indices.append(indices[i+2])
955
956         # bones
957         boneNameMap={}
958         for i, b in enumerate(self.skeleton.bones):
959             bone=io.addBone()
960
961             # name
962             boneNameMap[b.name]=i
963             v=englishmap.getUnicodeBoneName(b.name)
964             if not v:
965                 v=[b.name, b.name]
966             assert(v)
967             bone.name=v[1]
968
969             # english name
970             bone_english_name=toCP932(b.name)
971             if len(bone_english_name)>=20:
972                 print(bone_english_name)
973                 #assert(len(bone_english_name)<20)
974             bone.english_name=bone_english_name
975
976             if len(v)>=3:
977                 # has type
978                 if v[2]==5:
979                     b.ik_index=self.skeleton.indexByName('eyes')
980                 bone.type=v[2]
981             else:
982                 bone.type=b.type
983
984             bone.parent_index=b.parent_index
985             bone.tail_index=b.tail_index
986             bone.ik_index=b.ik_index
987
988             # convert right-handed z-up to left-handed y-up
989             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
990             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
991             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
992
993         # IK
994         for ik in self.skeleton.ik_list:
995             solver=io.addIK()
996             solver.index=self.skeleton.getIndex(ik.target)
997             solver.target=self.skeleton.getIndex(ik.effector)
998             solver.length=ik.length
999             b=self.skeleton.bones[ik.effector.parent_index]
1000             for i in xrange(solver.length):
1001                 solver.children.append(self.skeleton.getIndex(b))
1002                 b=self.skeleton.bones[b.parent_index]
1003             solver.iterations=ik.iterations
1004             solver.weight=ik.weight
1005
1006         # 表情
1007         for i, m in enumerate(self.oneSkinMesh.morphList):
1008             # morph
1009             morph=io.addMorph()
1010
1011             v=englishmap.getUnicodeSkinName(m.name)
1012             if not v:
1013                 v=[m.name, m.name, 0]
1014             assert(v)
1015             morph.name=v[1]
1016             morph.english_name=m.name
1017             m.type=v[2]
1018             morph.type=v[2]
1019             for index, offset in m.offsets:
1020                 # convert right-handed z-up to left-handed y-up
1021                 morph.append(index, offset[0], offset[2], offset[1])
1022             morph.vertex_count=len(m.offsets)
1023
1024         # 表情枠
1025         # type==0はbase
1026         for i, m in enumerate(self.oneSkinMesh.morphList):
1027             if m.type==3:
1028                 io.face_list.append(i)
1029         for i, m in enumerate(self.oneSkinMesh.morphList):
1030             if m.type==2:
1031                 io.face_list.append(i)
1032         for i, m in enumerate(self.oneSkinMesh.morphList):
1033             if m.type==1:
1034                 io.face_list.append(i)
1035         for i, m in enumerate(self.oneSkinMesh.morphList):
1036             if m.type==4:
1037                 io.face_list.append(i)
1038
1039         # ボーングループ
1040         for g in self.skeleton.bone_groups:
1041             boneDisplayName=io.addBoneGroup()
1042             # name
1043             name=englishmap.getUnicodeBoneGroupName(g[0])
1044             if not name:
1045                 name=g[0]
1046             boneDisplayName.name=name+'\n'
1047             # english
1048             englishName=g[0]
1049             boneDisplayName.english_name=englishName+'\n'
1050
1051         # ボーングループメンバー
1052         for i, b in enumerate(self.skeleton.bones):
1053             if i==0:
1054                continue
1055             if b.type in [6, 7]:
1056                continue
1057             io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1058
1059         #assert(len(io.bones)==len(io.bone_display_list)+1)
1060
1061         # English
1062         io.english_name=self.englishName
1063         io.english_comment=self.englishComment
1064
1065         # toon
1066         toonMeshObject=None
1067         for o in bl.object.each():
1068             try:
1069                 if o.name.startswith(bl.TOON_TEXTURE_OBJECT):
1070                     toonMeshObject=o
1071             except:
1072                 p(o.name)
1073             break
1074         if toonMeshObject:
1075             toonMesh=bl.object.getData(toonMeshObject)
1076             toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1077             for i in range(10):
1078                 t=bl.material.getTexture(toonMaterial, i)
1079                 if t:
1080                     io.toon_textures[i]="%s" % t.name
1081                 else:
1082                     io.toon_textures[i]="toon%02d.bmp" % (i+1)
1083         else:
1084             for i in range(10):
1085                 io.toon_textures[i]="toon%02d.bmp" % (i+1)
1086
1087         # rigid body
1088         rigidNameMap={}
1089         for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1090             name=obj[bl.RIGID_NAME] if bl.RIGID_NAME in obj else obj.name
1091             print(name)
1092             rigidBody=pmd.RigidBody(name)
1093             rigidNameMap[name]=i
1094             boneIndex=boneNameMap[obj[bl.RIGID_BONE_NAME]]
1095             if boneIndex==0:
1096                 boneIndex=0xFFFF
1097                 bone=self.skeleton.bones[0]
1098             else:
1099                 bone=self.skeleton.bones[boneIndex]
1100             rigidBody.boneIndex=boneIndex
1101             rigidBody.position.x=obj.location.x-bone.pos[0]
1102             rigidBody.position.y=obj.location.z-bone.pos[2]
1103             rigidBody.position.z=obj.location.y-bone.pos[1]
1104             rigidBody.rotation.x=-obj.rotation_euler[0]
1105             rigidBody.rotation.y=-obj.rotation_euler[2]
1106             rigidBody.rotation.z=-obj.rotation_euler[1]
1107             rigidBody.processType=obj[bl.RIGID_PROCESS_TYPE]
1108             rigidBody.group=obj[bl.RIGID_GROUP]
1109             rigidBody.target=obj[bl.RIGID_INTERSECTION_GROUP]
1110             rigidBody.weight=obj[bl.RIGID_WEIGHT]
1111             rigidBody.linearDamping=obj[bl.RIGID_LINEAR_DAMPING]
1112             rigidBody.angularDamping=obj[bl.RIGID_ANGULAR_DAMPING]
1113             rigidBody.restitution=obj[bl.RIGID_RESTITUTION]
1114             rigidBody.friction=obj[bl.RIGID_FRICTION]
1115             if obj[bl.RIGID_SHAPE_TYPE]==0:
1116                 rigidBody.shapeType=pmd.SHAPE_SPHERE
1117                 rigidBody.w=obj.scale[0]
1118                 rigidBody.d=0
1119                 rigidBody.h=0
1120             elif obj[bl.RIGID_SHAPE_TYPE]==1:
1121                 rigidBody.shapeType=pmd.SHAPE_BOX
1122                 rigidBody.w=obj.scale[0]
1123                 rigidBody.d=obj.scale[1]
1124                 rigidBody.h=obj.scale[2]
1125             elif obj[bl.RIGID_SHAPE_TYPE]==2:
1126                 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1127                 rigidBody.w=obj.scale[0]
1128                 rigidBody.h=obj.scale[2]
1129                 rigidBody.d=0
1130             io.rigidbodies.append(rigidBody)
1131
1132         # constraint
1133         for obj in self.oneSkinMesh.constraints:
1134             print(obj)
1135             constraint=pmd.Constraint(obj[bl.CONSTRAINT_NAME])
1136             constraint.rigidA=rigidNameMap[obj[bl.CONSTRAINT_A]]
1137             constraint.rigidB=rigidNameMap[obj[bl.CONSTRAINT_B]]
1138             constraint.pos.x=obj.location[0]
1139             constraint.pos.y=obj.location[2]
1140             constraint.pos.z=obj.location[1]
1141             constraint.rot.x=-obj.rotation_euler[0]
1142             constraint.rot.y=-obj.rotation_euler[2]
1143             constraint.rot.z=-obj.rotation_euler[1]
1144             constraint.constraintPosMin.x=obj[bl.CONSTRAINT_POS_MIN][0]
1145             constraint.constraintPosMin.y=obj[bl.CONSTRAINT_POS_MIN][1]
1146             constraint.constraintPosMin.z=obj[bl.CONSTRAINT_POS_MIN][2]
1147             constraint.constraintPosMax.x=obj[bl.CONSTRAINT_POS_MAX][0]
1148             constraint.constraintPosMax.y=obj[bl.CONSTRAINT_POS_MAX][1]
1149             constraint.constraintPosMax.z=obj[bl.CONSTRAINT_POS_MAX][2]
1150             constraint.constraintRotMin.x=obj[bl.CONSTRAINT_ROT_MIN][0]
1151             constraint.constraintRotMin.y=obj[bl.CONSTRAINT_ROT_MIN][1]
1152             constraint.constraintRotMin.z=obj[bl.CONSTRAINT_ROT_MIN][2]
1153             constraint.constraintRotMax.x=obj[bl.CONSTRAINT_ROT_MAX][0]
1154             constraint.constraintRotMax.y=obj[bl.CONSTRAINT_ROT_MAX][1]
1155             constraint.constraintRotMax.z=obj[bl.CONSTRAINT_ROT_MAX][2]
1156             constraint.springPos.x=obj[bl.CONSTRAINT_SPRING_POS][0]
1157             constraint.springPos.y=obj[bl.CONSTRAINT_SPRING_POS][1]
1158             constraint.springPos.z=obj[bl.CONSTRAINT_SPRING_POS][2]
1159             constraint.springRot.x=obj[bl.CONSTRAINT_SPRING_ROT][0]
1160             constraint.springRot.y=obj[bl.CONSTRAINT_SPRING_ROT][1]
1161             constraint.springRot.z=obj[bl.CONSTRAINT_SPRING_ROT][2]
1162             io.constraints.append(constraint)
1163
1164         # 書き込み
1165         bl.message('write: %s' % path)
1166         return io.write(path)
1167
1168
1169 def _execute(filepath=''):
1170     active=bl.object.getActive()
1171     if not active:
1172         print("abort. no active object.")
1173         return
1174     exporter=PmdExporter()
1175     exporter.setup()
1176     print(exporter)
1177     exporter.write(filepath)
1178     bl.object.activate(active)
1179
1180