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', 'indices', 'offsets']
169 def __init__(self, name, type):
176 class IKSolver(object):
177 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
178 def __init__(self, target, effector, length, iterations, weight):
180 self.effector=effector
182 self.iterations=iterations
186 class OneSkinMesh(object):
187 __slots__=['armatureObj', 'vertexArray', 'morphList']
188 def __init__(self, root):
189 self.armatureObj=None
190 self.vertexArray=VertexArray()
195 return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
196 self.armatureObj.name if self.armatureObj else None,
200 def __create(self, node):
201 if node.o.getType()=='Mesh':
202 self.__addMesh(node.o)
204 for child in node.children:
207 def __addMesh(self, obj):
208 if obj.restrictDisplay:
212 print("export", obj.name)
214 ############################################################
215 # search armature modifier
216 ############################################################
217 for m in obj.modifiers:
218 if m.name=="Armature":
219 armatureObj=m[Blender.Modifier.Settings.OBJECT]
220 if not self.armatureObj:
221 self.armatureObj=armatureObj
222 elif self.armatureObj!=armatureObj:
223 print "warning! found multiple armature. ignored.", armatureObj.name
225 ############################################################
227 ############################################################
228 mesh=obj.getData(mesh=True)
231 for name in mesh.getVertGroupNames():
232 for i, w in mesh.getVertsFromGroup(name, 1):
235 if i in secondWeightMap:
237 if w<secondWeightMap[i]:
241 secondWeightMap[i]=(name, w)
244 weightMap[i]=(name, w)
246 if w>weightMap[i][1]:
248 secondWeightMap[i]=weightMap[i]
249 weightMap[i]=(name, w)
251 secondWeightMap[i]=(name, w)
253 weightMap[i]=(name, w)
256 for i in xrange(len(mesh.verts)):
257 #for i, name_weight in weightMap.items():
258 if i in secondWeightMap:
259 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
261 weightMap[i]=(weightMap[i][0], 1.0)
262 secondWeightMap[i]=("", 0)
264 print "no weight vertex"
266 secondWeightMap[i]=("", 0)
269 ############################################################
272 ############################################################
273 mesh=Blender.Mesh.New()
274 # not applied modifiers
275 mesh.getFromObject(obj.name, 1)
276 # apply object transform
277 mesh.transform(obj.getMatrix())
278 if len(mesh.verts)==0:
281 for face in mesh.faces:
282 faceVertexCount=len(face.v)
283 material=mesh.materials[face.mat]
284 if faceVertexCount==3:
289 self.vertexArray.addTriangle(
291 v0.index, v1.index, v2.index,
294 #v0.no, v1.no, v2.no,
295 face.no, face.no, face.no,
296 face.uv[0], face.uv[1], face.uv[2],
297 weightMap[v0.index][0],
298 weightMap[v1.index][0],
299 weightMap[v2.index][0],
300 secondWeightMap[v0.index][0],
301 secondWeightMap[v1.index][0],
302 secondWeightMap[v2.index][0],
303 weightMap[v0.index][1],
304 weightMap[v1.index][1],
305 weightMap[v2.index][1]
307 elif faceVertexCount==4:
313 self.vertexArray.addTriangle(
315 v0.index, v1.index, v2.index,
317 #v0.no, v1.no, v2.no,
318 face.no, face.no, face.no,
319 face.uv[0], face.uv[1], face.uv[2],
320 weightMap[v0.index][0],
321 weightMap[v1.index][0],
322 weightMap[v2.index][0],
323 secondWeightMap[v0.index][0],
324 secondWeightMap[v1.index][0],
325 secondWeightMap[v2.index][0],
326 weightMap[v0.index][1],
327 weightMap[v1.index][1],
328 weightMap[v2.index][1]
330 self.vertexArray.addTriangle(
332 v2.index, v3.index, v0.index,
334 #v2.no, v3.no, v0.no,
335 face.no, face.no, face.no,
336 face.uv[2], face.uv[3], face.uv[0],
337 weightMap[v2.index][0],
338 weightMap[v3.index][0],
339 weightMap[v0.index][0],
340 secondWeightMap[v2.index][0],
341 secondWeightMap[v3.index][0],
342 secondWeightMap[v0.index][0],
343 weightMap[v2.index][1],
344 weightMap[v3.index][1],
345 weightMap[v0.index][1]
348 ############################################################
350 ############################################################
353 blenderMesh=obj.getData(mesh=True)
355 for b in blenderMesh.key.blocks:
358 morph=self.__getOrCreateMorph('base', 0)
361 for index in blenderMesh.getVertsFromGroup(
362 MMD_SHAPE_GROUP_NAME):
364 pos=[v[0], v[1], v[2]]
365 indices=self.vertexArray.getMappedIndices(index)
367 morph.indices.append(i)
368 morph.offsets.append(pos)
369 indexRelativeMap[i]=relativeIndex
376 for b in obj.getData(mesh=True).key.blocks:
381 morph=self.__getOrCreateMorph(b.name, 4)
382 for index in obj.getData(mesh=True).getVertsFromGroup(
383 MMD_SHAPE_GROUP_NAME):
384 #offset=[d-s for d, s in zip(
385 # b.data[index], basis.data[index])]
386 src=basis.data[index]
388 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
389 indices=self.vertexArray.getMappedIndices(index)
391 morph.indices.append(indexRelativeMap[i])
392 morph.offsets.append(offset)
394 def __getOrCreateMorph(self, name, type):
395 for m in self.morphList:
399 self.morphList.append(m)
402 def getVertexCount(self):
403 return len(self.vertexArray.vertices)
407 __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
408 def __init__(self, name, pos):
411 self.pos=[pos.x, pos.y, pos.z]
412 self.parent_index=None
417 return "<Bone %s %d>" % (self.name, self.type)
419 class BoneBuilder(object):
420 __slots__=['bones', 'boneMap', 'ik_list']
426 def build(self, armatureObj):
428 armature=armatureObj.getData()
429 for b in armature.bones.values():
432 bone=Bone(b.name, b.head['ARMATURESPACE'])
434 self.__getBone(bone, b)
436 for b in armature.bones.values():
437 if not b.parent and b.name!='center':
439 bone=Bone(b.name, b.head['ARMATURESPACE'])
441 self.__getBone(bone, b)
443 pose = armatureObj.getPose()
444 cSetting=Blender.Constraint.Settings
445 for b in pose.bones.values():
446 for c in b.constraints:
447 if c.type==Blender.Constraint.Type.IKSOLVER:
452 link=self.__boneByName(b.name)
453 link_tail=self.bones[link.tail_index]
454 if link_tail.type==7:
455 # replace ...先 to IK接続先
460 chainLength=c[cSetting.CHAINLEN]
461 for i in range(chainLength):
463 self.__boneByName(e.name).type=4
469 assert(c[cSetting.TARGET]==armatureObj)
470 target=self.__boneByName(
471 c[Blender.Constraint.Settings.BONE])
475 IKSolver(target, link_tail, chainLength,
476 c[cSetting.ITERATIONS], c.influence))
478 target_tail=self.bones[target.tail_index]
479 if target_tail.type!=7:
480 target_bone=armature.bones[target.name]
481 bone=Bone(target.name+'_t',
482 target_bone.tail['ARMATURESPACE'])
485 bone.parent_index=target.index
486 target.tail_index=bone.index
488 def getIndex(self, bone):
489 for i, b in enumerate(self.bones):
494 def __boneByName(self, name):
495 return self.bones[self.boneMap[name]]
497 def __getBone(self, parent, b):
498 if not Blender.Armature.CONNECTED in b.options:
502 if len(b.children)==0:
504 bone=Bone(b.name+'_t', b.tail['ARMATURESPACE'])
508 bone.parent_index=parent.index
509 parent.tail_index=bone.index
512 for i, c in enumerate(b.children):
513 bone=Bone(c.name, c.head['ARMATURESPACE'])
516 bone.parent_index=parent.index
518 parent.tail_index=bone.index
519 self.__getBone(bone, c)
521 def __addBone(self, bone):
522 bone.index=len(self.bones)
523 self.bones.append(bone)
524 self.boneMap[bone.name]=bone.index
527 class PmdExporter(object):
529 def setup(self, scene):
532 for o in scene.objects:
533 object_node_map[o]=Node(o)
534 for node in object_node_map.values():
536 object_node_map[node.o.parent].children.append(node)
538 root=object_node_map[scene.objects.active]
541 self.oneSkinMesh=OneSkinMesh(root)
542 print(self.oneSkinMesh)
543 self.name=root.o.name
545 def write(self, path):
548 io.comment="blender export"
552 builder=BoneBuilder()
553 builder.build(self.oneSkinMesh.armatureObj)
556 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
557 # convert right-handed z-up to left-handed y-up
567 v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
568 v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
569 v.weight0=int(100*weight)
570 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
573 vertexCount=self.oneSkinMesh.getVertexCount()
574 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
575 m=Blender.Material.Get(m)
577 material=io.addMaterial()
578 material.diffuse.r=m.R
579 material.diffuse.g=m.G
580 material.diffuse.b=m.B
581 material.diffuse.a=m.alpha
582 material.sinness=0 if m.spec<1e-5 else m.spec*10
583 material.specular.r=m.specR
584 material.specular.g=m.specG
585 material.specular.b=m.specB
586 material.ambient.r=m.mirR
587 material.ambient.g=m.mirG
588 material.ambient.b=m.mirB
589 material.vertex_count=len(indices)
590 material.toon_index=0
591 material.flag=1 if m.enableSSS else 0
596 assert(i<vertexCount)
597 for i in xrange(0, len(indices), 3):
599 io.indices.append(indices[i+2])
600 io.indices.append(indices[i+1])
601 io.indices.append(indices[i])
603 #io.indices.append(indices[i])
604 #io.indices.append(indices[i+1])
605 #io.indices.append(indices[i+2])
608 for b in builder.bones:
611 unicode=englishmap.getUnicodeBoneName(b.name)
613 cp932=unicode.encode('cp932')
616 bone_name="%s\n" % cp932
617 assert(len(bone_name)<20)
620 bone_english_name="%s\n" % b.name
621 assert(len(bone_english_name)<20)
622 bone.english_name=bone_english_name
625 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
626 bone.tail_index=b.tail_index if b.tail_index!=None else 0
629 # convert right-handed z-up to left-handed y-up
635 for ik in builder.ik_list:
637 solver.index=builder.getIndex(ik.target)
638 solver.target=builder.getIndex(ik.effector)
639 solver.length=ik.length
640 b=builder.bones[ik.effector.parent_index]
641 for i in xrange(solver.length):
642 solver.children.append(builder.getIndex(b))
643 b=builder.bones[b.parent_index]
644 solver.iterations=ik.iterations
645 solver.weight=ik.weight
648 for i, m in enumerate(self.oneSkinMesh.morphList):
652 unicode=englishmap.getUnicodeSkinName(m.name)
654 cp932=unicode.encode('cp932')
657 morph.name="%s\n" % cp932
659 morph.english_name="%s\n" % m.name
661 for index, offset in zip(m.indices, m.offsets):
662 # convert right-handed z-up to left-handed y-up
663 morph.append(index, offset[0], offset[2], offset[1])
664 morph.vertex_count=len(m.indices)
668 io.face_list.append(i)
671 boneDisplayName=io.addBoneDisplayName()
672 boneDisplayName.name="bones\n"
673 boneDisplayName.english_name="bones\n"
675 for i, b in enumerate(builder.bones):
677 io.addBoneDisplay(i, displayIndex)
680 io.english_name="blender export"
681 io.english_coment="blender export"
684 io.getToonTexture(i).name="toon%02d.bmp\n" % i
687 return io.write(path.encode(FS_ENCODING))
690 def export_pmd(filename):
691 filename=filename.decode(INTERNAL_ENCODING)
693 Blender.Window.WaitCursor(1)
694 t = Blender.sys.time()
696 if not filename.lower().endswith(EXTENSION):
697 filename += EXTENSION
698 print "pmd exporter: %s" % filename
700 exporter=PmdExporter()
703 exporter.setup(Blender.Scene.GetCurrent())
706 exporter.write(filename)
708 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
710 Blender.Window.WaitCursor(0)
713 Blender.Window.FileSelector(
715 'Export Metasequoia PMD',
716 Blender.sys.makename(ext=EXTENSION))