OSDN Git Service

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