OSDN Git Service

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