4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Export PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
20 from meshio import pmd, englishmap
25 FS_ENCODING=sys.getfilesystemencoding()
26 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
27 INTERNAL_ENCODING='utf-8'
29 INTERNAL_ENCODING=FS_ENCODING
32 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
37 __slots__=['o', 'children']
38 def __init__(self, o):
43 ###############################################################################
44 # Blenderのメッシュをワンスキンメッシュ化する
45 ###############################################################################
46 def near(x, y, EPSILON=1e-5):
48 return d>=-EPSILON and d<=EPSILON
51 class VertexKey(object):
57 'nx', 'ny', 'nz', # 法線
61 def __init__(self, x, y, z, nx, ny, nz, u, v):
72 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
73 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
76 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
77 return int((self.x+self.y+self.z)*100)
79 def __eq__(self, rhs):
80 #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)
81 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
82 return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
85 class VertexArray(object):
105 return "<VertexArray %d vertices, %d indexArrays>" % (
106 len(self.vertices), len(self.indexArrays))
110 self.vertices, self.normals, self.uvs,
111 self.b0, self.b1, self.weight)
113 def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
118 pos[0], pos[1], pos[2],
119 normal[0], normal[1], normal[2],
121 if key in self.vertexMap:
123 index=self.vertexMap[key]
125 index=len(self.vertices)
127 self.vertexMap[key]=index
129 self.vertices.append((pos.x, pos.y, pos.z))
130 self.normals.append((normal.x, normal.y, normal.z))
131 self.uvs.append((uv.x, uv.y))
134 self.weight.append(weight0)
137 if not base_index in self.indexMap:
138 self.indexMap[base_index]=set()
139 self.indexMap[base_index].add(index)
144 def getMappedIndices(self, base_index):
145 return self.indexMap[base_index]
147 def addTriangle(self,
149 base_index0, base_index1, base_index2,
155 weight0, weight1, weight2
157 if not material in self.indexArrays:
158 self.indexArrays[material]=[]
160 index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
161 index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
162 index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
164 self.indexArrays[material]+=[index0, index1, index2]
168 __slots__=['name', 'type', 'offsets']
169 def __init__(self, name, type):
174 def add(self, index, offset):
175 self.offsets.append((index, offset))
178 self.offsets.sort(lambda l, r: l[0]-r[0])
181 return "<Morph %s>" % self.name
183 class IKSolver(object):
184 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
185 def __init__(self, target, effector, length, iterations, weight):
187 self.effector=effector
189 self.iterations=iterations
193 class OneSkinMesh(object):
194 __slots__=['vertexArray', 'morphList']
196 self.vertexArray=VertexArray()
200 return "<OneSkinMesh %s, morph:%d>" % (
204 def addMesh(self, obj):
205 if obj.restrictDisplay:
209 print("export", obj.name)
211 ############################################################
213 ############################################################
214 mesh=obj.getData(mesh=True)
217 for name in mesh.getVertGroupNames():
218 for i, w in mesh.getVertsFromGroup(name, 1):
221 if i in secondWeightMap:
223 if w<secondWeightMap[i]:
227 secondWeightMap[i]=(name, w)
230 weightMap[i]=(name, w)
232 if w>weightMap[i][1]:
234 secondWeightMap[i]=weightMap[i]
235 weightMap[i]=(name, w)
237 secondWeightMap[i]=(name, w)
239 weightMap[i]=(name, w)
242 for i in xrange(len(mesh.verts)):
243 #for i, name_weight in weightMap.items():
244 if i in secondWeightMap:
245 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
247 weightMap[i]=(weightMap[i][0], 1.0)
248 secondWeightMap[i]=("", 0)
250 print "no weight vertex"
252 secondWeightMap[i]=("", 0)
255 ############################################################
258 ############################################################
259 mesh=Blender.Mesh.New()
260 # not applied modifiers
261 mesh.getFromObject(obj.name, 1)
262 # apply object transform
263 mesh.transform(obj.getMatrix())
264 if len(mesh.verts)==0:
267 for face in mesh.faces:
268 faceVertexCount=len(face.v)
269 material=mesh.materials[face.mat]
270 if faceVertexCount==3:
275 self.vertexArray.addTriangle(
277 v0.index, v1.index, v2.index,
280 #v0.no, v1.no, v2.no,
281 face.no, face.no, face.no,
282 face.uv[0], face.uv[1], face.uv[2],
283 weightMap[v0.index][0],
284 weightMap[v1.index][0],
285 weightMap[v2.index][0],
286 secondWeightMap[v0.index][0],
287 secondWeightMap[v1.index][0],
288 secondWeightMap[v2.index][0],
289 weightMap[v0.index][1],
290 weightMap[v1.index][1],
291 weightMap[v2.index][1]
293 elif faceVertexCount==4:
299 self.vertexArray.addTriangle(
301 v0.index, v1.index, v2.index,
303 #v0.no, v1.no, v2.no,
304 face.no, face.no, face.no,
305 face.uv[0], face.uv[1], face.uv[2],
306 weightMap[v0.index][0],
307 weightMap[v1.index][0],
308 weightMap[v2.index][0],
309 secondWeightMap[v0.index][0],
310 secondWeightMap[v1.index][0],
311 secondWeightMap[v2.index][0],
312 weightMap[v0.index][1],
313 weightMap[v1.index][1],
314 weightMap[v2.index][1]
316 self.vertexArray.addTriangle(
318 v2.index, v3.index, v0.index,
320 #v2.no, v3.no, v0.no,
321 face.no, face.no, face.no,
322 face.uv[2], face.uv[3], face.uv[0],
323 weightMap[v2.index][0],
324 weightMap[v3.index][0],
325 weightMap[v0.index][0],
326 secondWeightMap[v2.index][0],
327 secondWeightMap[v3.index][0],
328 secondWeightMap[v0.index][0],
329 weightMap[v2.index][1],
330 weightMap[v3.index][1],
331 weightMap[v0.index][1]
334 ############################################################
336 ############################################################
339 blenderMesh=obj.getData(mesh=True)
342 for b in blenderMesh.key.blocks:
345 baseMorph=self.__getOrCreateMorph('base', 0)
348 for index in blenderMesh.getVertsFromGroup(
349 MMD_SHAPE_GROUP_NAME):
351 pos=[v[0], v[1], v[2]]
352 indices=self.vertexArray.getMappedIndices(index)
354 baseMorph.add(i, pos)
355 indexRelativeMap[i]=relativeIndex
358 print(len(baseMorph.offsets))
363 vg=obj.getData(mesh=True).getVertsFromGroup(
364 MMD_SHAPE_GROUP_NAME)
365 for b in obj.getData(mesh=True).key.blocks:
370 morph=self.__getOrCreateMorph(b.name, 4)
371 for index, src, dst in zip(
372 xrange(len(blenderMesh.verts)),
375 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
377 indices=self.vertexArray.getMappedIndices(index)
379 morph.add(indexRelativeMap[i], offset)
380 assert(len(morph.offsets)==len(baseMorph.offsets))
383 original=self.morphList[:]
385 for i, v in enumerate(englishmap.skinMap):
389 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
391 def __getOrCreateMorph(self, name, type):
392 for m in self.morphList:
396 self.morphList.append(m)
399 def getVertexCount(self):
400 return len(self.vertexArray.vertices)
404 __slots__=['index', 'name', 'ik_index',
405 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
406 def __init__(self, name, pos, tail):
411 self.parent_index=None
417 def __eq__(self, rhs):
418 return self.index==rhs.index
421 return "<Bone %s %d>" % (self.name, self.type)
423 class BoneBuilder(object):
424 __slots__=['bones', 'boneMap', 'ik_list']
430 def build(self, armatureObj):
434 print("gather bones")
435 armature=armatureObj.getData()
436 for b in armature.bones.values():
440 b.head['ARMATURESPACE'][0:3],
441 b.tail['ARMATURESPACE'][0:3])
443 self.__getBone(bone, b)
445 for b in armature.bones.values():
446 if not b.parent and b.name!='center':
449 b.head['ARMATURESPACE'][0:3],
450 b.tail['ARMATURESPACE'][0:3])
452 self.__getBone(bone, b)
454 print("check connection")
455 for b in armature.bones.values():
457 self.__checkConnection(b, None)
460 pose = armatureObj.getPose()
461 cSetting=Blender.Constraint.Settings
462 for b in pose.bones.values():
463 for c in b.constraints:
464 if c.type==Blender.Constraint.Type.IKSOLVER:
468 assert(c[cSetting.TARGET]==armatureObj)
469 target=self.__boneByName(
470 c[Blender.Constraint.Settings.BONE])
477 link=self.__boneByName(b.name)
482 chainLength=c[cSetting.CHAINLEN]
483 for i in range(chainLength):
485 chainBone=self.__boneByName(e.name)
487 chainBone.ik_index=target.index
490 IKSolver(target, link, chainLength,
491 int(c[cSetting.ITERATIONS] * 0.1),
492 c[cSetting.ROTWEIGHT]
495 def __checkConnection(self, b, p):
496 if Blender.Armature.CONNECTED in b.options:
497 parent=self.__boneByName(p.name)
498 parent.isConnect=True
501 self.__checkConnection(c, b)
503 def sortBy(self, boneMap):
507 original=self.bones[:]
509 for i, k_v in enumerate(boneMap):
510 if k_v[0]==bone.name:
514 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
516 for i, b in enumerate(self.bones):
517 src=original.index(b)
520 b.index=sortMap[b.index]
522 b.parent_index=sortMap[b.parent_index]
524 b.tail_index=sortMap[b.tail_index]
526 b.ik_index=sortMap[b.ik_index]
528 def getIndex(self, bone):
529 for i, b in enumerate(self.bones):
534 def indexByName(self, name):
535 return self.getIndex(self.__boneByName(name))
537 def __boneByName(self, name):
538 return self.bones[self.boneMap[name]]
540 def __getBone(self, parent, b):
541 if len(b.children)==0:
545 for i, c in enumerate(b.children):
547 c.head['ARMATURESPACE'][0:3],
548 c.tail['ARMATURESPACE'][0:3])
551 bone.parent_index=parent.index
553 parent.tail_index=bone.index
554 self.__getBone(bone, c)
556 def __addBone(self, bone):
557 bone.index=len(self.bones)
558 self.bones.append(bone)
559 self.boneMap[bone.name]=bone.index
562 class PmdExporter(object):
565 self.armatureObj=None
567 def setup(self, scene):
570 for o in scene.objects:
571 object_node_map[o]=Node(o)
572 for node in object_node_map.values():
574 object_node_map[node.o.parent].children.append(node)
576 root=object_node_map[scene.objects.active]
579 self.oneSkinMesh=OneSkinMesh()
580 self.__createOneSkinMesh(root)
581 print(self.oneSkinMesh)
582 self.name=root.o.name
585 self.builder=BoneBuilder()
586 self.builder.build(self.armatureObj)
587 self.builder.sortBy(englishmap.boneMap)
589 for i, v in enumerate(englishmap.boneMap):
590 if v[0]==ik.target.name:
592 return len(englishmap.boneMap)
593 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
595 def __createOneSkinMesh(self, node):
596 ############################################################
597 # search armature modifier
598 ############################################################
599 for m in node.o.modifiers:
600 if m.name=="Armature":
601 armatureObj=m[Blender.Modifier.Settings.OBJECT]
602 if not self.armatureObj:
603 self.armatureObj=armatureObj
604 elif self.armatureObj!=armatureObj:
605 print "warning! found multiple armature. ignored.", armatureObj.name
607 if node.o.getType()=='Mesh':
608 self.oneSkinMesh.addMesh(node.o)
610 for child in node.children:
611 self.__createOneSkinMesh(child)
613 def write(self, path):
616 io.comment="blender export"
620 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
621 # convert right-handed z-up to left-handed y-up
631 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
632 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
633 v.weight0=int(100*weight)
634 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
637 vertexCount=self.oneSkinMesh.getVertexCount()
638 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
639 m=Blender.Material.Get(m)
641 material=io.addMaterial()
642 material.diffuse.r=m.R
643 material.diffuse.g=m.G
644 material.diffuse.b=m.B
645 material.diffuse.a=m.alpha
646 material.sinness=0 if m.spec<1e-5 else m.spec*10
647 material.specular.r=m.specR
648 material.specular.g=m.specG
649 material.specular.b=m.specB
650 material.ambient.r=m.mirR
651 material.ambient.g=m.mirG
652 material.ambient.b=m.mirB
653 material.vertex_count=len(indices)
654 material.toon_index=0
655 material.flag=1 if m.enableSSS else 0
660 assert(i<vertexCount)
661 for i in xrange(0, len(indices), 3):
663 io.indices.append(indices[i+2])
664 io.indices.append(indices[i+1])
665 io.indices.append(indices[i])
667 #io.indices.append(indices[i])
668 #io.indices.append(indices[i+1])
669 #io.indices.append(indices[i+2])
672 for b in self.builder.bones:
673 if b.name.endswith("_t"):
674 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
676 print "skip %s" % b.name
681 v=englishmap.getUnicodeBoneName(b.name)
683 cp932=v[1].encode('cp932')
684 bone_name="%s" % cp932
685 assert(len(bone_name)<20)
688 bone_english_name="%s" % b.name
689 assert(len(bone_english_name)<20)
690 bone.english_name=bone_english_name
695 b.ik_index=self.builder.indexByName('eyes')
701 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
704 if b.tail_index!=None:
708 bone.tail_index=b.tail_index
712 bone.ik_index=b.ik_index
714 # convert right-handed z-up to left-handed y-up
715 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
716 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
717 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
720 for ik in self.builder.ik_list:
722 solver.index=self.builder.getIndex(ik.target)
723 solver.target=self.builder.getIndex(ik.effector)
724 solver.length=ik.length
725 b=self.builder.bones[ik.effector.parent_index]
726 for i in xrange(solver.length):
727 solver.children.append(self.builder.getIndex(b))
728 b=self.builder.bones[b.parent_index]
729 solver.iterations=ik.iterations
730 solver.weight=ik.weight
733 for i, m in enumerate(self.oneSkinMesh.morphList):
737 v=englishmap.getUnicodeSkinName(m.name)
739 cp932=v[1].encode('cp932')
740 morph.name="%s\n" % cp932
742 morph.english_name="%s\n" % m.name
744 for index, offset in m.offsets:
745 # convert right-handed z-up to left-handed y-up
746 morph.append(index, offset[0], offset[2], offset[1])
747 morph.vertex_count=len(m.offsets)
751 io.face_list.append(i)
754 boneDisplayName=io.addBoneDisplayName()
755 boneDisplayName.name="bones\n"
756 boneDisplayName.english_name="bones\n"
758 for i, b in enumerate(self.builder.bones):
760 io.addBoneDisplay(i, displayIndex)
763 io.english_name="blender export"
764 io.english_coment="blender export"
767 io.getToonTexture(i).name="toon%02d.bmp\n" % i
770 return io.write(path.encode(FS_ENCODING))
773 def export_pmd(filename):
774 filename=filename.decode(INTERNAL_ENCODING)
776 Blender.Window.WaitCursor(1)
777 t = Blender.sys.time()
779 if not filename.lower().endswith(EXTENSION):
780 filename += EXTENSION
781 print "pmd exporter: %s" % filename
783 exporter=PmdExporter()
786 exporter.setup(Blender.Scene.GetCurrent())
789 exporter.write(filename)
791 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
793 Blender.Window.WaitCursor(0)
796 Blender.Window.FileSelector(
798 'Export Metasequoia PMD',
799 Blender.sys.makename(ext=EXTENSION))