4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Export PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
15 This script exports a pmd model.
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.
23 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
24 BASE_SHAPE_NAME='Basis'
27 ###############################################################################
29 ###############################################################################
36 from meshio import pmd, englishmap
39 return sys.version_info[0]<3
44 from Blender import Mathutils
52 from bpy.props import *
62 __slots__=['o', 'children']
63 def __init__(self, o):
68 ###############################################################################
69 # Blenderのメッシュをワンスキンメッシュ化する
70 ###############################################################################
71 def near(x, y, EPSILON=1e-5):
73 return d>=-EPSILON and d<=EPSILON
76 class VertexKey(object):
82 'nx', 'ny', 'nz', # 法線
86 def __init__(self, x, y, z, nx, ny, nz, u, v):
97 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
98 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
101 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
102 return int((self.x+self.y+self.z)*100)
104 def __eq__(self, rhs):
105 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z) and near(self.nx, rhs.nx) and near(self.ny, rhs.ny) and near(self.nz, rhs.nz) and near(self.u, rhs.u) and near(self.v, rhs.v)
106 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
107 return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
110 class VertexArray(object):
115 # マテリアル毎に分割したインデックス配列
130 return "<VertexArray %d vertices, %d indexArrays>" % (
131 len(self.vertices), len(self.indexArrays))
135 self.vertices, self.normals, self.uvs,
136 self.b0, self.b1, self.weight)
138 def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
143 pos[0], pos[1], pos[2],
144 normal[0], normal[1], normal[2],
146 if key in self.vertexMap:
148 index=self.vertexMap[key]
150 index=len(self.vertices)
152 self.vertexMap[key]=index
154 self.vertices.append((pos.x, pos.y, pos.z))
155 self.normals.append((normal.x, normal.y, normal.z))
156 self.uvs.append((uv[0], uv[1]))
159 self.weight.append(weight0)
162 if not base_index in self.indexMap:
163 self.indexMap[base_index]=set()
164 self.indexMap[base_index].add(index)
169 def getMappedIndices(self, base_index):
170 return self.indexMap[base_index]
172 def addTriangle(self,
174 base_index0, base_index1, base_index2,
180 weight0, weight1, weight2
182 if not material in self.indexArrays:
183 self.indexArrays[material]=[]
185 index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
186 index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
187 index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
189 self.indexArrays[material]+=[index0, index1, index2]
193 __slots__=['name', 'type', 'offsets']
194 def __init__(self, name, type):
199 def add(self, index, offset):
200 self.offsets.append((index, offset))
204 self.offsets.sort(lambda l, r: l[0]-r[0])
206 self.offsets.sort(key=lambda e: e[0])
209 return "<Morph %s>" % self.name
211 class IKSolver(object):
212 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
213 def __init__(self, target, effector, length, iterations, weight):
215 self.effector=effector
217 self.iterations=iterations
221 class OneSkinMesh(object):
222 __slots__=['scene', 'vertexArray', 'morphList']
223 def __init__(self, scene):
224 self.vertexArray=VertexArray()
229 return "<OneSkinMesh %s, morph:%d>" % (
233 def addMesh(self, obj):
234 if bl.objectIsVisible(obj):
238 print("export", obj.name)
240 ############################################################
242 ############################################################
243 mesh=bl.objectGetData(obj)
246 def setWeight(i, name, w):
249 if i in secondWeightMap:
251 if w<secondWeightMap[i]:
255 secondWeightMap[i]=(name, w)
258 weightMap[i]=(name, w)
260 if w>weightMap[i][1]:
262 secondWeightMap[i]=weightMap[i]
263 weightMap[i]=(name, w)
265 secondWeightMap[i]=(name, w)
267 weightMap[i]=(name, w)
270 for name in bl.meshVertexGroupNames(obj):
271 for i, w in mesh.getVertsFromGroup(name, 1):
272 setWeight(i, name, w)
274 for i, v in enumerate(mesh.verts):
276 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
279 for i in xrange(len(mesh.verts)):
280 #for i, name_weight in weightMap.items():
281 if i in secondWeightMap:
282 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
284 weightMap[i]=(weightMap[i][0], 1.0)
285 secondWeightMap[i]=("", 0)
287 print("no weight vertex")
289 secondWeightMap[i]=("", 0)
291 ############################################################
292 # メッシュのコピーを生成してオブジェクトの行列を適用する
293 ############################################################
294 copyMesh, copyObj=bl.objectDuplicate(self.scene, obj)
295 if len(copyMesh.verts)==0:
298 for i, face in enumerate(copyMesh.faces):
299 faceVertexCount=bl.faceVertexCount(face)
300 material=copyMesh.materials[bl.faceMaterialIndex(face)]
301 v=[copyMesh.verts[index] for index in bl.faceVertices(face)]
302 uv=bl.meshFaceUv(copyMesh, i, face)
303 if faceVertexCount==3:
305 self.vertexArray.addTriangle(
307 v[0].index, v[1].index, v[2].index,
308 v[0].co, v[1].co, v[2].co,
310 #v0.no, v1.no, v2.no,
315 weightMap[v[0].index][0],
316 weightMap[v[1].index][0],
317 weightMap[v[2].index][0],
318 secondWeightMap[v[0].index][0],
319 secondWeightMap[v[1].index][0],
320 secondWeightMap[v[2].index][0],
321 weightMap[v[0].index][1],
322 weightMap[v[1].index][1],
323 weightMap[v[2].index][1]
325 elif faceVertexCount==4:
327 self.vertexArray.addTriangle(
329 v[0].index, v[1].index, v[2].index,
330 v[0].co, v[1].co, v[2].co,
331 #v0.no, v1.no, v2.no,
336 weightMap[v[0].index][0],
337 weightMap[v[1].index][0],
338 weightMap[v[2].index][0],
339 secondWeightMap[v[0].index][0],
340 secondWeightMap[v[1].index][0],
341 secondWeightMap[v[2].index][0],
342 weightMap[v[0].index][1],
343 weightMap[v[1].index][1],
344 weightMap[v[2].index][1]
346 self.vertexArray.addTriangle(
348 v[2].index, v[3].index, v[0].index,
349 v[2].co, v[3].co, v[0].co,
350 #v2.no, v3.no, v0.no,
355 weightMap[v[2].index][0],
356 weightMap[v[3].index][0],
357 weightMap[v[0].index][0],
358 secondWeightMap[v[2].index][0],
359 secondWeightMap[v[3].index][0],
360 secondWeightMap[v[0].index][0],
361 weightMap[v[2].index][1],
362 weightMap[v[3].index][1],
363 weightMap[v[0].index][1]
365 bl.objectDelete(self.scene, copyObj)
367 ############################################################
369 ############################################################
371 blenderMesh=bl.objectGetData(obj)
373 if bl.objectHasShapeKey(obj):
375 for b in bl.objectShapeKeys(obj):
376 if b.name==BASE_SHAPE_NAME:
377 baseMorph=self.__getOrCreateMorph('base', 0)
381 for index in bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME):
382 v=bl.shapeKeyGet(b, index)
383 pos=[v[0], v[1], v[2]]
384 indices=self.vertexArray.getMappedIndices(index)
386 baseMorph.add(i, pos)
387 indexRelativeMap[i]=relativeIndex
392 print(basis.name, len(baseMorph.offsets))
394 if(len(baseMorph.offsets)>0):
398 vg=bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
399 for b in bl.objectShapeKeys(obj):
400 if b.name==BASE_SHAPE_NAME:
404 morph=self.__getOrCreateMorph(b.name, 4)
405 for index, src, dst in zip(
406 xrange(len(blenderMesh.verts)),
409 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
410 if offset[0]==0 and offset[1]==0 and offset[2]==0:
413 indices=self.vertexArray.getMappedIndices(index)
415 morph.add(indexRelativeMap[i], offset)
418 original=self.morphList[:]
420 for i, v in enumerate(englishmap.skinMap):
425 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
427 self.morphList.sort(key=getIndex)
429 def __getOrCreateMorph(self, name, type):
430 for m in self.morphList:
434 self.morphList.append(m)
437 def getVertexCount(self):
438 return len(self.vertexArray.vertices)
442 __slots__=['index', 'name', 'ik_index',
443 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
444 def __init__(self, name, pos, tail):
449 self.parent_index=None
455 def __eq__(self, rhs):
456 return self.index==rhs.index
459 return "<Bone %s %d>" % (self.name, self.type)
461 class BoneBuilder(object):
462 __slots__=['bones', 'boneMap', 'ik_list']
468 def build(self, armatureObj):
472 print("gather bones")
473 armature=bl.objectGetData(armatureObj)
474 for b in armature.bones.values():
481 self.__getBone(bone, b)
483 for b in armature.bones.values():
484 if not b.parent and b.name!='center':
490 self.__getBone(bone, b)
492 print("check connection")
493 for b in armature.bones.values():
495 self.__checkConnection(b, None)
498 pose = bl.objectGetPose(armatureObj)
499 for b in pose.bones.values():
500 for c in b.constraints:
501 if bl.constraintIsIKSolver(c):
505 target=self.__boneByName(bl.ikTarget(c))
512 link=self.__boneByName(b.name)
517 chainLength=bl.ikChainLen(c)
518 for i in range(chainLength):
520 chainBone=self.__boneByName(e.name)
522 chainBone.ik_index=target.index
525 IKSolver(target, link, chainLength,
526 int(bl.ikItration(c) * 0.1),
527 bl.ikRotationWeight(c)
530 def __checkConnection(self, b, p):
531 if bl.boneIsConnected(b):
532 parent=self.__boneByName(p.name)
533 parent.isConnect=True
536 self.__checkConnection(c, b)
538 def sortBy(self, boneMap):
542 original=self.bones[:]
544 for i, k_v in enumerate(boneMap):
545 if k_v[0]==bone.name:
550 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
552 self.bones.sort(key=getIndex)
555 for i, b in enumerate(self.bones):
556 src=original.index(b)
559 b.index=sortMap[b.index]
561 b.parent_index=sortMap[b.parent_index]
563 b.tail_index=sortMap[b.tail_index]
565 b.ik_index=sortMap[b.ik_index]
567 def getIndex(self, bone):
568 for i, b in enumerate(self.bones):
573 def indexByName(self, name):
574 return self.getIndex(self.__boneByName(name))
576 def __boneByName(self, name):
577 return self.bones[self.boneMap[name]]
579 def __getBone(self, parent, b):
580 if len(b.children)==0:
584 for i, c in enumerate(b.children):
590 bone.parent_index=parent.index
592 parent.tail_index=bone.index
593 self.__getBone(bone, c)
595 def __addBone(self, bone):
596 bone.index=len(self.bones)
597 self.bones.append(bone)
598 self.boneMap[bone.name]=bone.index
601 class PmdExporter(object):
603 def setup(self, scene):
604 self.armatureObj=None
609 for o in scene.objects:
610 object_node_map[o]=Node(o)
611 for node in object_node_map.values():
613 object_node_map[node.o.parent].children.append(node)
616 root=object_node_map[scene.objects.active]
619 self.oneSkinMesh=OneSkinMesh(scene)
620 self.__createOneSkinMesh(root)
621 print(self.oneSkinMesh)
622 self.name=root.o.name
625 self.builder=BoneBuilder()
626 self.builder.build(self.armatureObj)
627 self.builder.sortBy(englishmap.boneMap)
629 for i, v in enumerate(englishmap.boneMap):
630 if v[0]==ik.target.name:
632 return len(englishmap.boneMap)
634 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
636 self.builder.ik_list.sort(key=getIndex)
638 def __createOneSkinMesh(self, node):
640 ############################################################
641 # search armature modifier
642 ############################################################
643 for m in node.o.modifiers:
644 if bl.modifierIsArmature(m):
645 armatureObj=bl.armatureModifierGetObject(m)
646 if not self.armatureObj:
647 self.armatureObj=armatureObj
648 elif self.armatureObj!=armatureObj:
649 print("warning! found multiple armature. ignored.", armatureObj.name)
651 if node.o.type.upper()=='MESH':
652 self.oneSkinMesh.addMesh(node.o)
654 for child in node.children:
655 self.__createOneSkinMesh(child)
657 def write(self, path):
660 io.comment="blender export"
664 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
665 # convert right-handed z-up to left-handed y-up
675 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
676 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
677 v.weight0=int(100*weight)
678 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
681 vertexCount=self.oneSkinMesh.getVertexCount()
682 for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
683 m=bl.materialGet(self.scene, material_name)
685 material=io.addMaterial()
687 material.diffuse.r=m.R
688 material.diffuse.g=m.G
689 material.diffuse.b=m.B
690 material.diffuse.a=m.alpha
691 material.sinness=0 if m.spec<1e-5 else m.spec*10
692 material.specular.r=m.specR
693 material.specular.g=m.specG
694 material.specular.b=m.specB
695 material.ambient.r=m.mirR
696 material.ambient.g=m.mirG
697 material.ambient.b=m.mirB
698 material.flag=1 if m.enableSSS else 0
700 material.diffuse.r=m.diffuse_color[0]
701 material.diffuse.g=m.diffuse_color[1]
702 material.diffuse.b=m.diffuse_color[2]
703 material.diffuse.a=m.alpha
704 material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
705 material.specular.r=m.specular_color[0]
706 material.specular.g=m.specular_color[1]
707 material.specular.b=m.specular_color[2]
708 material.ambient.r=m.mirror_color[0]
709 material.ambient.g=m.mirror_color[1]
710 material.ambient.b=m.mirror_color[2]
711 material.flag=1 if m.subsurface_scattering.enabled else 0
713 material.vertex_count=len(indices)
714 material.toon_index=0
719 assert(i<vertexCount)
720 for i in xrange(0, len(indices), 3):
722 io.indices.append(indices[i])
723 io.indices.append(indices[i+1])
724 io.indices.append(indices[i+2])
727 for b in self.builder.bones:
728 if b.name.endswith("_t"):
729 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
731 print("skip %s" % b.name)
737 v=englishmap.getUnicodeBoneName(b.name)
739 cp932=v[1].encode('cp932')
740 assert(len(cp932)<20)
744 bone_english_name=b.name
745 assert(len(bone_english_name)<20)
746 bone.english_name=bone_english_name
751 b.ik_index=self.builder.indexByName('eyes')
757 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
760 if b.tail_index!=None:
764 bone.tail_index=b.tail_index
768 bone.ik_index=b.ik_index
770 # convert right-handed z-up to left-handed y-up
771 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
772 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
773 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
776 for ik in self.builder.ik_list:
778 solver.index=self.builder.getIndex(ik.target)
779 solver.target=self.builder.getIndex(ik.effector)
780 solver.length=ik.length
781 b=self.builder.bones[ik.effector.parent_index]
782 for i in xrange(solver.length):
783 solver.children.append(self.builder.getIndex(b))
784 b=self.builder.bones[b.parent_index]
785 solver.iterations=ik.iterations
786 solver.weight=ik.weight
789 for i, m in enumerate(self.oneSkinMesh.morphList):
793 v=englishmap.getUnicodeSkinName(m.name)
795 cp932=v[1].encode('cp932')
797 morph.setEnglishName(m.name.encode('cp932'))
800 for index, offset in m.offsets:
801 # convert right-handed z-up to left-handed y-up
802 morph.append(index, offset[0], offset[2], offset[1])
803 morph.vertex_count=len(m.offsets)
807 for i, m in enumerate(self.oneSkinMesh.morphList):
809 io.face_list.append(i)
810 for i, m in enumerate(self.oneSkinMesh.morphList):
812 io.face_list.append(i)
813 for i, m in enumerate(self.oneSkinMesh.morphList):
815 io.face_list.append(i)
816 for i, m in enumerate(self.oneSkinMesh.morphList):
818 io.face_list.append(i)
821 def createBoneDisplayName(name, english):
822 boneDisplayName=io.addBoneDisplayName()
824 boneDisplayName.name=name.decode('utf-8').encode('cp932')
825 boneDisplayName.english_name=english
827 boneDisplayName.setName(name.encode('cp932'))
828 boneDisplayName.setEnglishName(english.encode('cp932'))
829 boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
830 boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
831 boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
832 boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
833 boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
834 boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
835 boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
836 for i, b in enumerate(self.builder.bones):
841 io.addBoneDisplay(i, getBoneDisplayGroup(b))
844 io.english_name="blender export"
845 io.english_coment="blender export"
848 io.getToonTexture(i).name="toon%02d.bmp\n" % i
851 return io.write(path)
854 def getBoneDisplayGroup(bone):
857 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
858 "toe IK_L", "toe IK_R",
861 "upper body", "neck", "head", "eye_L", "eye_R",
862 "necktie1", "necktie2", "necktie3", "eyes",
863 "eyelight_L", "eyelight_R",
866 "front hair1", "front hair2", "front hair3",
867 "hair1_L", "hair2_L", "hair3_L",
868 "hair4_L", "hair5_L", "hair6_L",
869 "hair1_R", "hair2_R", "hair3_R",
870 "hair4_R", "hair5_R", "hair6_R",
873 "shoulder_L", "arm_L", "arm twist_L", "elbow_L",
874 "wrist twist_L", "wrist_L", "sleeve_L",
875 "shoulder_R", "arm_R", "arm twist_R", "elbow_R",
876 "wrist twist_R", "wrist_R", "sleeve_R",
879 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
880 "middle1_L", "middle2_L", "middle3_L",
881 "third1_L", "third2_L", "third3_L",
882 "little1_L", "little2_L", "little3_L",
883 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
884 "middle1_R", "middle2_R", "middle3_R",
885 "third1_R", "third2_R", "third3_R",
886 "little1_R", "little2_R", "little3_R",
889 "lower body", "waist accessory",
890 "front skirt_L", "back skirt_L",
891 "front skirt_R", "back skirt_R",
894 "leg_L", "knee_L", "ankle_L",
895 "leg_R", "knee_R", "ankle_R",
907 def __execute(filename, scene):
908 if not scene.objects.active:
909 print("abort. no active object.")
912 exporter=PmdExporter()
913 exporter.setup(scene)
914 exporter.write(filename)
919 def execute_24(filename):
920 filename=filename.decode(bl.INTERNAL_ENCODING)
921 print("pmd exporter: %s" % filename)
923 Blender.Window.WaitCursor(1)
924 t = Blender.sys.time()
926 scene = bpy.data.scenes.active
927 __execute(filename, scene)
929 print('finished in %.2f seconds' % (Blender.sys.time()-t))
931 Blender.Window.WaitCursor(0)
933 Blender.Window.FileSelector(
935 'Export Metasequoia PMD',
936 Blender.sys.makename(ext='.pmd'))
940 def execute_25(*args):
944 class EXPORT_OT_pmd(bpy.types.Operator):
945 '''Save a Metasequoia PMD file.'''
946 bl_idname = "export_scene.pmd"
947 bl_label = 'Export PMD'
949 # List of operator properties, the attributes will be assigned
950 # to the class instance from the operator settings before calling.
952 path = StringProperty(
954 description="File path used for exporting the PMD file",
958 filename = StringProperty(
960 description="Name of the file.")
961 directory = StringProperty(
963 description="Directory of the file.")
965 check_existing = BoolProperty(
966 name="Check Existing",
967 description="Check and warn on overwriting existing files",
969 options=set('HIDDEN'))
971 def execute(self, context):
973 self.properties.path,
978 def invoke(self, context, event):
980 wm.add_fileselect(self)
981 return 'RUNNING_MODAL'
984 def menu_func(self, context):
985 default_path=bpy.data.filename.replace(".blend", ".pmd")
986 self.layout.operator(
987 EXPORT_OT_pmd.bl_idname,
988 text="Miku Miku Dance Model(.pmd)").path=default_path
991 bpy.types.register(EXPORT_OT_pmd)
992 bpy.types.INFO_MT_file_export.append(menu_func)
995 bpy.types.unregister(EXPORT_OT_pmd)
996 bpy.types.INFO_MT_file_export.remove(menu_func)
998 if __name__ == "__main__":