4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Import PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
14 0.2: 20091209 implement IK.
15 0.3: 20091210 implement morph target.
16 0.4: 20100305 use english name.
17 0.5: 20100408 cleanup not used vertices.
18 0.6: 20100416 fix fornt face. texture load fail safe. add progress.
19 0.7: 20100506 C extension.
20 0.8: 20100521 add shape_key group.
23 from Blender import Mathutils
31 from meshio import pmd, englishmap
34 FS_ENCODING=sys.getfilesystemencoding()
35 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
36 INTERNAL_ENCODING='utf-8'
38 INTERNAL_ENCODING=FS_ENCODING
41 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
44 ###############################################################################
46 ###############################################################################
47 class ProgressBar(object):
48 def __init__(self, base):
49 print "#### %s ####" % base
51 self.start=Blender.sys.time()
52 self.set('<start>', 0)
54 def advance(self, message, progress):
55 self.progress+=float(progress)
58 def set(self, message, progress):
59 self.progress=float(progress)
62 def _print(self, message):
64 message="%s: %s" % (self.base, message)
65 if message.__class__ is unicode:
66 message=message.encode(FS_ENCODING)
67 Blender.Window.DrawProgressBar(self.progress, message)
71 message='finished in %.2f sec' % (Blender.sys.time()-self.start)
72 self.set(message, 1.0)
74 def progress_start(base):
76 progressBar=ProgressBar(base)
78 def progress_finish():
82 def progress_print(message, progress=0.05):
84 progressBar.advance(message, progress)
86 def progress_set(message, progress):
88 progressBar.set(message, progress)
91 ###############################################################################
93 ###############################################################################
94 def convert_coord(pos):
96 Left handed y-up to Right handed z-up
98 return (pos.x, pos.z, pos.y)
102 return (uv.x, 1.0 - uv.y)
105 def get_bone_name(l, index):
106 name=englishmap.getEnglishBoneName(l.bones[index].getName())
107 return name if name else l.bones[index].getName().encode(INTERNAL_ENCODING)
110 def createMaterial():
112 create default materil
114 material=Blender.Material.New()
115 material.setDiffuseShader(Blender.Material.Shaders.DIFFUSE_TOON)
117 material.diffuseSize = 3.14/2
118 material.setDiffuseSmooth(0)
119 material.setSpecShader(Blender.Material.Shaders.SPEC_TOON)
120 material.setSpecSize(0)
125 def importMesh(scene, l, tex_dir):
127 @param l[in] mmd.PMDLoader
131 ############################################################
132 # shpaeキーで使われるマテリアル優先的に前に並べる
133 ############################################################
134 # shapeキーで使われる頂点インデックスを集める
135 shape_key_used_vertices=set()
136 if len(l.morph_list)>0:
139 for s in l.morph_list:
146 for index in base.indices:
147 shape_key_used_vertices.add(index)
149 # マテリアルに含まれる頂点がshape_keyに含まれるか否か?
150 def isMaterialUsedInShape(offset, m):
151 for i in xrange(offset, offset+m.vertex_count):
152 if l.indices[i] in shape_key_used_vertices:
155 # shapeキーで使われるマテリアルを記録する
156 shape_key_materials=set()
157 # 各マテリアルの開始頂点インデックスを記録する
160 for i, m in enumerate(l.materials):
161 face_map[i]=face_count
162 if isMaterialUsedInShape(face_count, m):
163 shape_key_materials.add(i)
164 face_count+=m.vertex_count
167 material_order=list(shape_key_materials)
169 # shapeキーに使われていないマテリアルを後ろに追加
170 for i in range(len(l.materials)):
171 if not i in material_order:
172 material_order.append(i)
174 # マテリアル16個ごとに分割したメッシュを作成する
177 while material_offset<len(l.materials):
179 mesh = Blender.Mesh.New()
182 obj = scene.objects.new(mesh)
184 mesh_objects.append(obj)
186 # shapeキーで使われる順に並べなおしたマテリアル16個分の
188 vertex_map=import16MaerialAndMesh(
190 material_order[material_offset:material_offset+16],
194 importShape(obj, l, vertex_map)
202 def import16MaerialAndMesh(mesh, l, material_order, face_map, tex_dir):
203 ############################################################
205 ############################################################
206 progress_print('create materials')
210 for material_index in material_order:
212 m=l.materials[material_index]
213 mesh_material_map[material_index]=index
217 material=createMaterial()
218 material.setRGBCol([m.diffuse.r, m.diffuse.g, m.diffuse.b])
219 material.setAlpha(m.diffuse.a)
220 material.setSpec(m.shinness*0.1)
221 material.setSpecCol([m.specular.r, m.specular.g, m.specular.b])
222 material.setMirCol([m.ambient.r, m.ambient.g, m.ambient.b])
223 material.enableSSS=True if m.flag==1 else False
225 if m.getTexture()!='':
226 tex_file=re.compile('\*.*.spa$').sub('', m.getTexture())
227 tex_path = os.path.join(tex_dir, tex_file).encode(
229 tex = Blender.Texture.New()
232 tex.image = Blender.Image.Load(tex_path)
233 material.setTexture(0, tex)
234 material.getTextures()[0].texco = Blender.Texture.TexCo.UV
236 print material.name, "fail to load", tex_path
237 materials.append(material)
238 # lookup table for assign
240 mesh.materials=materials
242 ############################################################
244 ############################################################
245 progress_print('create vertices')
249 for v in l.each_vertex():
250 vertices.append(convert_coord(v.pos))
251 vertex_groups[v.bone0]=True
252 vertex_groups[v.bone1]=True
253 mesh.verts.extend(vertices)
255 # create vertex group
256 for i in vertex_groups.keys():
257 mesh.addVertGroup(get_bone_name(l, i))
260 for i, v, mvert in zip(xrange(len(l.vertices)), l.each_vertex(), mesh.verts):
261 mvert.no=Mathutils.Vector(*convert_coord(v.normal))
262 mvert.uvco=convert_uv(v.uv)
263 w1=float(v.weight0)/100.0
265 mesh.assignVertsToGroup(get_bone_name(l, v.bone0), [i], w1,
266 Blender.Mesh.AssignModes.ADD)
267 mesh.assignVertsToGroup(get_bone_name(l, v.bone1), [i], w2,
268 Blender.Mesh.AssignModes.ADD)
270 ############################################################
272 ############################################################
273 progress_print('create faces')
276 mesh_face_materials=[]
279 def degenerate(i0, i1, i2):
280 return i0==i1 or i1==i2 or i2==i0
282 for material_index in material_order:
283 face_offset=face_map[material_index]
284 m=l.materials[material_index]
285 material_faces=l.indices[face_offset:face_offset+m.vertex_count]
286 for j in xrange(0, len(material_faces), 3):
288 i1=material_faces[j+1]
289 i2=material_faces[j+2]
290 triangle=[i0, i1, i2]
291 if degenerate(*triangle):
293 mesh_face_indices.append(triangle)
294 mesh_face_materials.append(material_index)
295 used_vertices.add(i0)
296 used_vertices.add(i1)
297 used_vertices.add(i2)
299 mesh.faces.extend(mesh_face_indices, ignoreDups=True)
303 mesh.addUVLayer('NewUV')
304 for face, material_index in zip(mesh.faces, mesh_face_materials):
306 index=mesh_material_map[material_index]
307 except KeyError, message:
308 print message, mesh_material_map, m
311 material=mesh.materials[index]
312 texture=material.getTextures()[0]
315 face.image=texture.tex.image
316 texture.tex.imageFlags|=Blender.Texture.ImageFlags.USEALPHA
317 face.uv=[face.verts[0].uvco, face.verts[1].uvco, face.verts[2].uvco]
323 ############################################################
324 # clean up not used vertices
325 ############################################################
326 progress_print('clean up vertices not used')
329 for i, v in enumerate(l.each_vertex()):
330 if i in used_vertices:
331 vertex_map[i]=len(vertex_map)
333 remove_vertices.append(i)
334 mesh.verts.delete(remove_vertices)
336 progress_print('%s created' % mesh.name)
340 class Builder(object):
344 def build(self, armature, bones):
347 self.__build(armature, b, None, None)
350 def __build(self, armature, b, p, parent):
351 name=englishmap.getEnglishBoneName(b.getName())
353 name=b.getName().encode(INTERNAL_ENCODING)
356 bone=Blender.Armature.Editbone()
358 armature.bones[name]=bone
362 assert(b.type==6 or b.type==7)
363 bone.head = Mathutils.Vector(*convert_coord(b.pos))
364 bone.tail=bone.head+Mathutils.Vector(0, 1, 0)
367 if bone.name=="center_t":
368 # センターボーンは(0, 1, 0)の方向を向いていないと具合が悪い
369 parent.tail=parent.head+Mathutils.Vector(0, 1, 0)
371 assert(parent.tail==bone.head)
372 bone.options=[Blender.Armature.CONNECTED]
374 bone.layerMask = (1<<1)
376 bone.head = Mathutils.Vector(*convert_coord(b.pos))
377 bone.tail = Mathutils.Vector(*convert_coord(b.tail))
380 if parent.tail==bone.head:
381 bone.options=[Blender.Armature.CONNECTED]
383 if bone.head==bone.tail:
384 bone.tail=bone.head+Mathutils.Vector(0, 1, 0)
387 self.__build(armature, c, b, bone)
390 def importArmature(scene, l):
392 armature = Blender.Armature.New()
394 armature_object = scene.objects.new(armature)
396 act = Blender.Armature.NLA.NewAction()
397 act.setActive(armature_object)
399 armature_object.drawMode = (
400 armature_object.drawMode | Blender.Object.DrawModes.XRAY)
402 armature.drawType = Blender.Armature.OCTAHEDRON
403 armature.drawNames=True
404 armature.envelopes = False
405 armature.vertexGroups = True
406 armature.mirrorEdit = True
409 armature.makeEditable()
411 ############################################################
413 ############################################################
415 builder.build(armature, l.bones)
417 ############################################################
419 ############################################################
420 pose = armature_object.getPose()
421 cSetting = Blender.Constraint.Settings
423 # IKtarget->parent(=IK).name
424 target=l.bones[ik.target]
425 name = englishmap.getEnglishBoneName(target.getName())
426 p_bone = pose.bones[name]
428 print 'not found', name
430 if len(ik.children) >= 16:
431 print 'over MAX_CHAINLEN', ik, len(ik.children)
434 ik_solver = p_bone.constraints.append(Blender.Constraint.Type.IKSOLVER)
435 ik_solver[cSetting.CHAINLEN] = len(ik.children)
436 ik_solver[cSetting.TARGET] = armature_object
438 effector_name=englishmap.getEnglishBoneName(
439 l.bones[ik.index].getName())
440 if not effector_name:
441 effector_name=l.bones[ik.index].getName()
443 ik_solver[cSetting.BONE]=effector_name
444 #ik_solver.influence=ik.weight
445 ik_solver[cSetting.USETIP]=False
447 armature.makeEditable()
450 return armature_object
453 def importShape(obj, l, vertex_map):
454 if len(l.morph_list)==0:
457 mesh=obj.getData(mesh=True)
461 for s in l.morph_list:
465 # create vertex group
466 mesh.addVertGroup(MMD_SHAPE_GROUP_NAME)
472 indices.append(vertex_map[i])
473 mesh.assignVertsToGroup(MMD_SHAPE_GROUP_NAME, indices, 0,
474 Blender.Mesh.AssignModes.ADD)
480 assert(len(mesh.key.blocks)==1)
482 baseShapeBlock=mesh.key.blocks[baseShapeIndex]
483 baseShapeBlock.name='Basis'
484 obj.activeShape=baseShapeIndex
491 for s in l.morph_list:
492 if s.name==base.name:
495 for index, offset in zip(s.indices, s.pos_list):
497 vertex_index=vertex_map[base.indices[index]]
498 v=mesh.verts[vertex_index].co
499 offset=convert_coord(offset)
503 except IndexError, msg:
505 print index, len(base.indices), len(vertex_map)
506 print len(mesh.verts)
507 print base.indices[index]
511 #print 'this mesh not has shape vertices'
515 name=englishmap.getEnglishSkinName(s.getName())
517 name=s.getName().encode(INTERNAL_ENCODING)
520 # create shapekey block
522 shapeIndex=len(mesh.key.blocks)-1
523 keyBlock=mesh.key.blocks[shapeIndex]
526 # copy vertex to shape key
530 for mv, v in zip(mesh.verts, baseShapeBlock.getData()):
537 obj.activeShape=baseShapeIndex
543 filename=filename.decode(INTERNAL_ENCODING)
544 tex_dir=os.path.dirname(filename)
547 progress_start('pmd_import')
548 print(INTERNAL_ENCODING, FS_ENCODING)
551 progress_set('load %s' % filename, 0.0)
554 if not l.read(filename):
555 print "fail to load %s" % filename
557 progress_set('loaded %s' % filename, 0.1)
560 mode_edit = Blender.Window.EditMode()
562 Blender.Window.EditMode(0)
564 scene = bpy.data.scenes.active
566 # import objects container
567 root=scene.objects.new("Empty")
569 l.english_name if len(l.english_name)>0 else l.getName().encode(INTERNAL_ENCODING))
572 mesh_objects=importMesh(scene, l, tex_dir)
573 root.makeParent(mesh_objects)
576 armature_object=importArmature(scene, l)
578 armature = armature_object.getData()
579 root.makeParent([armature_object])
581 # add armature modifier
582 for o in mesh_objects:
583 mod=o.modifiers.append(Blender.Modifier.Types.ARMATURE)
584 mod[Blender.Modifier.Settings.OBJECT] = armature_object
585 mod[Blender.Modifier.Settings.ENVELOPES] = False
588 ############################################################
590 ############################################################
591 for n, b in armature_object.getPose().bones.items():
595 if n.startswith("knee_"):
600 b.limitMax=[180, 0, 0]
601 elif n.startswith("ankle_"):
609 Blender.Window.EditMode(1)
612 Blender.Window.RedrawAll()
615 if __name__=="__main__":
616 Blender.Window.FileSelector(
619 Blender.sys.makename(ext='.pmd'))