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.x, uv.y))
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))
203 self.offsets.sort(lambda l, r: l[0]-r[0])
206 return "<Morph %s>" % self.name
208 class IKSolver(object):
209 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
210 def __init__(self, target, effector, length, iterations, weight):
212 self.effector=effector
214 self.iterations=iterations
218 class OneSkinMesh(object):
219 __slots__=['vertexArray', 'morphList']
221 self.vertexArray=VertexArray()
225 return "<OneSkinMesh %s, morph:%d>" % (
229 def addMesh(self, obj):
230 if obj.restrictDisplay:
234 print("export", obj.name)
236 ############################################################
238 ############################################################
239 mesh=obj.getData(mesh=True)
242 for name in mesh.getVertGroupNames():
243 for i, w in mesh.getVertsFromGroup(name, 1):
246 if i in secondWeightMap:
248 if w<secondWeightMap[i]:
252 secondWeightMap[i]=(name, w)
255 weightMap[i]=(name, w)
257 if w>weightMap[i][1]:
259 secondWeightMap[i]=weightMap[i]
260 weightMap[i]=(name, w)
262 secondWeightMap[i]=(name, w)
264 weightMap[i]=(name, w)
267 for i in xrange(len(mesh.verts)):
268 #for i, name_weight in weightMap.items():
269 if i in secondWeightMap:
270 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
272 weightMap[i]=(weightMap[i][0], 1.0)
273 secondWeightMap[i]=("", 0)
275 print "no weight vertex"
277 secondWeightMap[i]=("", 0)
280 ############################################################
283 ############################################################
284 mesh=Blender.Mesh.New()
285 # not applied modifiers
286 mesh.getFromObject(obj.name, 1)
287 # apply object transform
288 mesh.transform(obj.getMatrix())
289 if len(mesh.verts)==0:
292 for face in mesh.faces:
293 faceVertexCount=len(face.v)
294 material=mesh.materials[face.mat]
295 if faceVertexCount==3:
300 self.vertexArray.addTriangle(
302 v0.index, v1.index, v2.index,
305 #v0.no, v1.no, v2.no,
306 face.no, face.no, face.no,
307 face.uv[0], face.uv[1], face.uv[2],
308 weightMap[v0.index][0],
309 weightMap[v1.index][0],
310 weightMap[v2.index][0],
311 secondWeightMap[v0.index][0],
312 secondWeightMap[v1.index][0],
313 secondWeightMap[v2.index][0],
314 weightMap[v0.index][1],
315 weightMap[v1.index][1],
316 weightMap[v2.index][1]
318 elif faceVertexCount==4:
324 self.vertexArray.addTriangle(
326 v0.index, v1.index, v2.index,
328 #v0.no, v1.no, v2.no,
329 face.no, face.no, face.no,
330 face.uv[0], face.uv[1], face.uv[2],
331 weightMap[v0.index][0],
332 weightMap[v1.index][0],
333 weightMap[v2.index][0],
334 secondWeightMap[v0.index][0],
335 secondWeightMap[v1.index][0],
336 secondWeightMap[v2.index][0],
337 weightMap[v0.index][1],
338 weightMap[v1.index][1],
339 weightMap[v2.index][1]
341 self.vertexArray.addTriangle(
343 v2.index, v3.index, v0.index,
345 #v2.no, v3.no, v0.no,
346 face.no, face.no, face.no,
347 face.uv[2], face.uv[3], face.uv[0],
348 weightMap[v2.index][0],
349 weightMap[v3.index][0],
350 weightMap[v0.index][0],
351 secondWeightMap[v2.index][0],
352 secondWeightMap[v3.index][0],
353 secondWeightMap[v0.index][0],
354 weightMap[v2.index][1],
355 weightMap[v3.index][1],
356 weightMap[v0.index][1]
359 ############################################################
361 ############################################################
364 blenderMesh=obj.getData(mesh=True)
367 for b in blenderMesh.key.blocks:
370 baseMorph=self.__getOrCreateMorph('base', 0)
373 for index in blenderMesh.getVertsFromGroup(
374 MMD_SHAPE_GROUP_NAME):
376 pos=[v[0], v[1], v[2]]
377 indices=self.vertexArray.getMappedIndices(index)
379 baseMorph.add(i, pos)
380 indexRelativeMap[i]=relativeIndex
383 print(len(baseMorph.offsets))
388 vg=obj.getData(mesh=True).getVertsFromGroup(
389 MMD_SHAPE_GROUP_NAME)
390 for b in obj.getData(mesh=True).key.blocks:
395 morph=self.__getOrCreateMorph(b.name, 4)
396 for index, src, dst in zip(
397 xrange(len(blenderMesh.verts)),
400 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
402 indices=self.vertexArray.getMappedIndices(index)
404 morph.add(indexRelativeMap[i], offset)
405 assert(len(morph.offsets)==len(baseMorph.offsets))
408 original=self.morphList[:]
410 for i, v in enumerate(englishmap.skinMap):
414 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
416 def __getOrCreateMorph(self, name, type):
417 for m in self.morphList:
421 self.morphList.append(m)
424 def getVertexCount(self):
425 return len(self.vertexArray.vertices)
429 __slots__=['index', 'name', 'ik_index',
430 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
431 def __init__(self, name, pos, tail):
436 self.parent_index=None
442 def __eq__(self, rhs):
443 return self.index==rhs.index
446 return "<Bone %s %d>" % (self.name, self.type)
448 class BoneBuilder(object):
449 __slots__=['bones', 'boneMap', 'ik_list']
455 def build(self, armatureObj):
459 print("gather bones")
460 armature=armatureObj.getData()
461 for b in armature.bones.values():
465 b.head['ARMATURESPACE'][0:3],
466 b.tail['ARMATURESPACE'][0:3])
468 self.__getBone(bone, b)
470 for b in armature.bones.values():
471 if not b.parent and b.name!='center':
474 b.head['ARMATURESPACE'][0:3],
475 b.tail['ARMATURESPACE'][0:3])
477 self.__getBone(bone, b)
479 print("check connection")
480 for b in armature.bones.values():
482 self.__checkConnection(b, None)
485 pose = armatureObj.getPose()
486 cSetting=Blender.Constraint.Settings
487 for b in pose.bones.values():
488 for c in b.constraints:
489 if c.type==Blender.Constraint.Type.IKSOLVER:
493 assert(c[cSetting.TARGET]==armatureObj)
494 target=self.__boneByName(
495 c[Blender.Constraint.Settings.BONE])
502 link=self.__boneByName(b.name)
507 chainLength=c[cSetting.CHAINLEN]
508 for i in range(chainLength):
510 chainBone=self.__boneByName(e.name)
512 chainBone.ik_index=target.index
515 IKSolver(target, link, chainLength,
516 int(c[cSetting.ITERATIONS] * 0.1),
517 c[cSetting.ROTWEIGHT]
520 def __checkConnection(self, b, p):
521 if Blender.Armature.CONNECTED in b.options:
522 parent=self.__boneByName(p.name)
523 parent.isConnect=True
526 self.__checkConnection(c, b)
528 def sortBy(self, boneMap):
532 original=self.bones[:]
534 for i, k_v in enumerate(boneMap):
535 if k_v[0]==bone.name:
539 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
541 for i, b in enumerate(self.bones):
542 src=original.index(b)
545 b.index=sortMap[b.index]
547 b.parent_index=sortMap[b.parent_index]
549 b.tail_index=sortMap[b.tail_index]
551 b.ik_index=sortMap[b.ik_index]
553 def getIndex(self, bone):
554 for i, b in enumerate(self.bones):
559 def indexByName(self, name):
560 return self.getIndex(self.__boneByName(name))
562 def __boneByName(self, name):
563 return self.bones[self.boneMap[name]]
565 def __getBone(self, parent, b):
566 if len(b.children)==0:
570 for i, c in enumerate(b.children):
572 c.head['ARMATURESPACE'][0:3],
573 c.tail['ARMATURESPACE'][0:3])
576 bone.parent_index=parent.index
578 parent.tail_index=bone.index
579 self.__getBone(bone, c)
581 def __addBone(self, bone):
582 bone.index=len(self.bones)
583 self.bones.append(bone)
584 self.boneMap[bone.name]=bone.index
587 class PmdExporter(object):
590 self.armatureObj=None
592 def setup(self, scene):
595 for o in scene.objects:
596 object_node_map[o]=Node(o)
597 for node in object_node_map.values():
599 object_node_map[node.o.parent].children.append(node)
601 root=object_node_map[scene.objects.active]
604 self.oneSkinMesh=OneSkinMesh()
605 self.__createOneSkinMesh(root)
606 print(self.oneSkinMesh)
607 self.name=root.o.name
610 self.builder=BoneBuilder()
611 self.builder.build(self.armatureObj)
612 self.builder.sortBy(englishmap.boneMap)
614 for i, v in enumerate(englishmap.boneMap):
615 if v[0]==ik.target.name:
617 return len(englishmap.boneMap)
618 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
620 def __createOneSkinMesh(self, node):
621 ############################################################
622 # search armature modifier
623 ############################################################
624 for m in node.o.modifiers:
625 if m.name=="Armature":
626 armatureObj=m[Blender.Modifier.Settings.OBJECT]
627 if not self.armatureObj:
628 self.armatureObj=armatureObj
629 elif self.armatureObj!=armatureObj:
630 print "warning! found multiple armature. ignored.", armatureObj.name
632 if node.o.getType()=='Mesh':
633 self.oneSkinMesh.addMesh(node.o)
635 for child in node.children:
636 self.__createOneSkinMesh(child)
638 def write(self, path):
641 io.comment="blender export"
645 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
646 # convert right-handed z-up to left-handed y-up
656 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
657 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
658 v.weight0=int(100*weight)
659 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
662 vertexCount=self.oneSkinMesh.getVertexCount()
663 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
664 m=Blender.Material.Get(m)
666 material=io.addMaterial()
667 material.diffuse.r=m.R
668 material.diffuse.g=m.G
669 material.diffuse.b=m.B
670 material.diffuse.a=m.alpha
671 material.sinness=0 if m.spec<1e-5 else m.spec*10
672 material.specular.r=m.specR
673 material.specular.g=m.specG
674 material.specular.b=m.specB
675 material.ambient.r=m.mirR
676 material.ambient.g=m.mirG
677 material.ambient.b=m.mirB
678 material.vertex_count=len(indices)
679 material.toon_index=0
680 material.flag=1 if m.enableSSS else 0
685 assert(i<vertexCount)
686 for i in xrange(0, len(indices), 3):
688 io.indices.append(indices[i+2])
689 io.indices.append(indices[i+1])
690 io.indices.append(indices[i])
692 #io.indices.append(indices[i])
693 #io.indices.append(indices[i+1])
694 #io.indices.append(indices[i+2])
697 for b in self.builder.bones:
698 if b.name.endswith("_t"):
699 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
701 print "skip %s" % b.name
706 v=englishmap.getUnicodeBoneName(b.name)
708 cp932=v[1].encode('cp932')
709 bone_name="%s" % cp932
710 assert(len(bone_name)<20)
713 bone_english_name="%s" % b.name
714 assert(len(bone_english_name)<20)
715 bone.english_name=bone_english_name
720 b.ik_index=self.builder.indexByName('eyes')
726 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
729 if b.tail_index!=None:
733 bone.tail_index=b.tail_index
737 bone.ik_index=b.ik_index
739 # convert right-handed z-up to left-handed y-up
740 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
741 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
742 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
745 for ik in self.builder.ik_list:
747 solver.index=self.builder.getIndex(ik.target)
748 solver.target=self.builder.getIndex(ik.effector)
749 solver.length=ik.length
750 b=self.builder.bones[ik.effector.parent_index]
751 for i in xrange(solver.length):
752 solver.children.append(self.builder.getIndex(b))
753 b=self.builder.bones[b.parent_index]
754 solver.iterations=ik.iterations
755 solver.weight=ik.weight
758 for i, m in enumerate(self.oneSkinMesh.morphList):
762 v=englishmap.getUnicodeSkinName(m.name)
764 cp932=v[1].encode('cp932')
765 morph.name="%s\n" % cp932
767 morph.english_name="%s\n" % m.name
770 for index, offset in m.offsets:
771 # convert right-handed z-up to left-handed y-up
772 morph.append(index, offset[0], offset[2], offset[1])
773 morph.vertex_count=len(m.offsets)
777 for i, m in enumerate(self.oneSkinMesh.morphList):
779 io.face_list.append(i)
780 for i, m in enumerate(self.oneSkinMesh.morphList):
782 io.face_list.append(i)
783 for i, m in enumerate(self.oneSkinMesh.morphList):
785 io.face_list.append(i)
786 for i, m in enumerate(self.oneSkinMesh.morphList):
788 io.face_list.append(i)
791 def createBoneDisplayName(name, english):
792 boneDisplayName=io.addBoneDisplayName()
793 boneDisplayName.name=name.decode('utf-8').encode('cp932')
794 boneDisplayName.english_name=english
795 boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
796 boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
797 boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
798 boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
799 boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
800 boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
801 boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
802 for i, b in enumerate(self.builder.bones):
807 io.addBoneDisplay(i, getBoneDisplayGroup(b))
810 io.english_name="blender export"
811 io.english_coment="blender export"
814 io.getToonTexture(i).name="toon%02d.bmp\n" % i
817 return io.write(path.encode(bl.FS_ENCODING))
820 def getBoneDisplayGroup(bone):
823 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
824 "toe IK_L", "toe IK_R",
827 "upper body", "neck", "head", "eye_L", "eye_R",
828 "necktie1", "necktie2", "necktie3", "eyes",
829 "eyelight_L", "eyelight_R",
832 "front hair1", "front hair2", "front hair3",
833 "hair1_L", "hair2_L", "hair3_L",
834 "hair4_L", "hair5_L", "hair6_L",
835 "hair1_R", "hair2_R", "hair3_R",
836 "hair4_R", "hair5_R", "hair6_R",
839 "shoulder_L", "arm_L", "arm twist_L", "elbow_L",
840 "wrist twist_L", "wrist_L", "sleeve_L",
841 "shoulder_R", "arm_R", "arm twist_R", "elbow_R",
842 "wrist twist_R", "wrist_R", "sleeve_R",
845 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
846 "middle1_L", "middle2_L", "middle3_L",
847 "third1_L", "third2_L", "third3_L",
848 "little1_L", "little2_L", "little3_L",
849 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
850 "middle1_R", "middle2_R", "middle3_R",
851 "third1_R", "third2_R", "third3_R",
852 "little1_R", "little2_R", "little3_R",
855 "lower body", "waist accessory",
856 "front skirt_L", "back skirt_L",
857 "front skirt_R", "back skirt_R",
860 "leg_L", "knee_L", "ankle_L",
861 "leg_R", "knee_R", "ankle_R",
873 def __execute(filename, scene):
874 exporter=PmdExporter()
875 exporter.setup(scene)
876 exporter.write(filename)
881 def execute_24(filename):
882 filename=filename.decode(bl.INTERNAL_ENCODING)
883 print("pmd exporter: %s" % filename)
885 Blender.Window.WaitCursor(1)
886 t = Blender.sys.time()
888 scene = bpy.data.scenes.active
889 __execute(filename, scene)
891 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
893 Blender.Window.WaitCursor(0)
895 Blender.Window.FileSelector(
897 'Export Metasequoia PMD',
898 Blender.sys.makename(ext='.pmd'))