Tooltip: 'Export PMD file for MikuMikuDance.'
"""
__author__= ["ousttrue"]
-__version__= "1.6"
+__version__= "2.0"
__url__=()
__bpydoc__="""
pmd Importer
1.4 20100626: refactoring.
1.5 20100629: sphere map.
1.6 20100710: toon texture & bone group.
+1.7 20100711: separate vertex with normal or uv.
+2.0 20100724: update for Blender2.53.
+2.1 20100731: add full python module.
"""
+bl_addon_info = {
+ 'category': 'Import/Export',
+ 'name': 'Export: MikuMikuDance Model Format (.pmd)',
+ 'author': 'ousttrue',
+ 'version': '2.0',
+ 'blender': (2, 5, 3),
+ 'location': 'File > Export',
+ 'description': 'Export to the MikuMikuDance Model Format (.pmd)',
+ 'warning': '', # used for warning icon and text in addons panel
+ 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
+ }
+
MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
+MMD_MB_NAME='mb_name'
+MMD_MB_COMMENT='mb_comment'
+MMD_COMMENT='comment'
BASE_SHAPE_NAME='Basis'
+RIGID_NAME='rigid_name'
RIGID_SHAPE_TYPE='rigid_shape_type'
RIGID_PROCESS_TYPE='rigid_process_type'
RIGID_BONE_NAME='rigid_bone_name'
import os
import sys
-# C extension
-from meshio import pmd, englishmap
+try:
+ # C extension
+ from meshio import pmd, englishmap
+except ImportError:
+ # full python
+ from pymeshio import englishmap
+ from pymeshio.mmd import PMDLoader as pmd
def isBlender24():
return sys.version_info[0]<3
else:
# for 2.5
import bpy
- from bpy.props import *
import mathutils
# wrapper
return d>=-EPSILON and d<=EPSILON
-class VertexKey(object):
- """
- 重複頂点の検索キー
- """
+class VertexAttribute(object):
__slots__=[
- 'obj', 'index',
- 'x', 'y', 'z', # 位置
- 'nx', 'ny', 'nz', # 法線
+ 'nx', 'ny', 'nz', # normal
'u', 'v', # uv
]
-
- def __init__(self, obj, index, x, y, z, nx, ny, nz, u, v):
- self.obj=obj
- self.index=index
- self.x=x
- self.y=y
- self.z=z
+ def __init__(self, nx, ny, nz, u, v):
self.nx=nx
self.ny=ny
self.nz=nz
self.v=v
def __str__(self):
- return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
- self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
+ return "<vkey: %f, %f, %f, %f, %f>" % (
+ self.nx, self.ny, self.nz, self.u, self.v)
def __hash__(self):
- #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
- #return int((self.x+self.y+self.z)*100)
- return self.index*100+self.obj
+ return self.nx + self.ny + self.nz + self.u + self.v
def __eq__(self, rhs):
- #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)
- #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
- #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
- return self.obj==rhs.obj and self.index==rhs.index
+ return self.nx==rhs.nx and self.ny==rhs.ny and self.nz==rhs.nz and self.u==rhs.u and self.v==rhs.v
+
+
+class VertexKey(object):
+ __slots__=[
+ 'obj_index', 'index',
+ ]
+
+ def __init__(self, obj_index, index):
+ self.obj_index=obj_index
+ self.index=index
+
+ def __str__(self):
+ return "<vkey: %d, %d>" % (self.obj_index, self.index)
+
+ def __hash__(self):
+ return self.index*100+self.obj_index
+
+ def __eq__(self, rhs):
+ return self.obj_index==rhs.obj_index and self.index==rhs.index
class VertexArray(object):
"""
__slots__=[
'indexArrays',
- 'vertices',
- 'normals',
- 'uvs',
+ 'positions',
+ 'attributes', # normal and uv
'b0', 'b1', 'weight',
'vertexMap',
'objectMap',
]
def __init__(self):
- # マテリアル毎に分割したインデックス配列
+ # indexArrays split with each material
self.indexArrays={}
- # 頂点属性
- self.vertices=[]
- self.normals=[]
- self.uvs=[]
- # skinning属性
+
+ self.positions=[]
+ self.attributes=[]
self.b0=[]
self.b1=[]
self.weight=[]
self.vertexMap={}
- #self.indexMap={}
self.objectMap={}
def __str__(self):
- return "<VertexArray %d vertices, %d indexArrays>" % (
- len(self.vertices), len(self.indexArrays))
+ return "<VertexArray %d positions, %d indexArrays>" % (
+ len(self.positions), len(self.indexArrays))
def zip(self):
return zip(
- self.vertices, self.normals, self.uvs,
+ self.positions, self.attributes,
self.b0, self.b1, self.weight)
def each(self):
for key in keys:
yield(key, self.indexArrays[key])
- def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
- """
- 頂点属性からその頂点のインデックスを得る
- """
- key=VertexKey(
- obj, base_index,
- pos[0], pos[1], pos[2],
+ def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
+ key=VertexKey(obj_index, base_index)
+ attribute=VertexAttribute(
normal[0], normal[1], normal[2],
uv[0], uv[1])
if key in self.vertexMap:
- # 同じ頂点を登録済み
- index=self.vertexMap[key]
+ if attribute in self.vertexMap[key]:
+ return self.vertexMap[key][attribute]
+ else:
+ return self.__addVertex(self.vertexMap[key],
+ pos, attribute, b0, b1, weight0)
else:
- index=len(self.vertices)
- # 新規頂点
- self.vertexMap[key]=index
- # append...
- self.vertices.append((pos.x, pos.y, pos.z))
- self.normals.append((normal.x, normal.y, normal.z))
- self.uvs.append((uv[0], uv[1]))
- self.b0.append(b0)
- self.b1.append(b1)
- self.weight.append(weight0)
-
- # indexのマッピングを保存する
- #if not base_index in self.indexMap:
- # self.indexMap[base_index]=set()
- #self.indexMap[base_index].add(index)
-
+ vertexMapKey={}
+ self.vertexMap[key]=vertexMapKey
+ return self.__addVertex(vertexMapKey,
+ pos, attribute, b0, b1, weight0)
+
+ def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
+ index=len(self.positions)
+ vertexMapKey[attribute]=index
+ # position
+ self.positions.append((pos.x, pos.y, pos.z))
+ # unique attribute
+ self.attributes.append(attribute)
+ # shared attribute
+ self.b0.append(b0)
+ self.b1.append(b1)
+ self.weight.append(weight0)
assert(index<=65535)
return index
-
+
def getMappedIndex(self, obj_name, base_index):
- key=VertexKey(
- self.objectMap[obj_name], base_index,
- None, None, None,
- None, None, None,
- None, None)
- return self.vertexMap[key]
-
- def getMappedIndices(self, obj, base_index):
- return self.indexMap[base_index]
+ return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
def addTriangle(self,
object_name, material,
weight0, weight1, weight2
):
if object_name in self.objectMap:
- obj=self.objectMap[object_name]
+ obj_index=self.objectMap[object_name]
else:
- obj=len(self.objectMap)
- self.objectMap[object_name]=obj
- index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
- index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
- index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
+ obj_index=len(self.objectMap)
+ self.objectMap[object_name]=obj_index
+ index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
+ index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
+ index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
if not material in self.indexArrays:
self.indexArrays[material]=[]
class OneSkinMesh(object):
- __slots__=['scene', 'vertexArray', 'morphList',
- 'rigidbodies',
- 'constraints',
- ]
- def __init__(self, scene):
+ __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
+ def __init__(self):
self.vertexArray=VertexArray()
self.morphList=[]
self.rigidbodies=[]
self.constraints=[]
- self.scene=scene
def __str__(self):
return "<OneSkinMesh %s, morph:%d>" % (
len(self.morphList))
def addMesh(self, obj):
- if bl.object.isVisible(obj):
+ if not bl.object.isVisible(obj):
return
self.__mesh(obj)
self.__skin(obj)
else:
weightMap[i]=(name, w)
+ # ToDo bone weightと関係ないvertex groupを除外する
if isBlender24():
for name in bl.object.getVertexGroupNames(obj):
for i, w in mesh.getVertsFromGroup(name, 1):
# 合計値が1になるようにする
for i in xrange(len(mesh.verts)):
- #for i, name_weight in weightMap.items():
if i in secondWeightMap:
secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
elif i in weightMap:
v[2].co,
v[1].co,
v[0].co,
- # ToDo vertex normal
- #v0.no, v1.no, v2.no,
- bl.face.getNormal(face),
- bl.face.getNormal(face),
- bl.face.getNormal(face),
+ bl.vertex.getNormal(v[2]),
+ bl.vertex.getNormal(v[1]),
+ bl.vertex.getNormal(v[0]),
uv[2],
uv[1],
uv[0],
v[2].co,
v[1].co,
v[0].co,
- #v0.no, v1.no, v2.no,
- bl.face.getNormal(face),
- bl.face.getNormal(face),
- bl.face.getNormal(face),
+ bl.vertex.getNormal(v[2]),
+ bl.vertex.getNormal(v[1]),
+ bl.vertex.getNormal(v[0]),
uv[2],
uv[1],
uv[0],
v[0].co,
v[3].co,
v[2].co,
- #v2.no, v3.no, v0.no,
- bl.face.getNormal(face),
- bl.face.getNormal(face),
- bl.face.getNormal(face),
+ bl.vertex.getNormal(v[0]),
+ bl.vertex.getNormal(v[3]),
+ bl.vertex.getNormal(v[2]),
uv[0],
uv[3],
uv[2],
# メッシュのコピーを生成してオブジェクトの行列を適用する
copyMesh, copyObj=bl.object.duplicate(obj)
- if len(copyMesh.verts)==0:
- return
- # apply transform
- copyObj.scale=obj.scale
- bpy.ops.object.scale_apply()
- copyObj.rotation_euler=obj.rotation_euler
- bpy.ops.object.rotation_apply()
- copyObj.location=obj.location
- bpy.ops.object.location_apply()
- # apply modifier
- for m in [m for m in copyObj.modifiers]:
- if m.type=='SOLIDFY':
- continue
- elif m.type=='ARMATURE':
- continue
- elif m.type=='MIRROR':
- bpy.ops.object.modifier_apply(modifier=m.name)
- else:
- print(m.tpye)
-
- weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
- self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
+ if len(copyMesh.verts)>0:
+ # apply transform
+ copyObj.scale=obj.scale
+ bpy.ops.object.scale_apply()
+ copyObj.rotation_euler=obj.rotation_euler
+ bpy.ops.object.rotation_apply()
+ copyObj.location=obj.location
+ bpy.ops.object.location_apply()
+ # apply modifier
+ for m in [m for m in copyObj.modifiers]:
+ if m.type=='SOLIDFY':
+ continue
+ elif m.type=='ARMATURE':
+ continue
+ elif m.type=='MIRROR':
+ bpy.ops.object.modifier_apply(modifier=m.name)
+ else:
+ print(m.type)
+ weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
+ self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
bl.object.delete(copyObj)
def createEmptyBasicSkin(self):
for index in vg:
v=bl.shapekey.getByIndex(b, index)
pos=[v[0], v[1], v[2]]
- i=self.vertexArray.getMappedIndex(obj.name, index)
- baseMorph.add(i, pos)
- indexRelativeMap[i]=relativeIndex
- relativeIndex+=1
- #indices=self.vertexArray.getMappedIndices(index)
- #for i in indices:
- # if i in used:
- # continue
- # used.add(i)
-
- # baseMorph.add(i, pos)
- # indexRelativeMap[i]=relativeIndex
- # relativeIndex+=1
+
+ indices=self.vertexArray.getMappedIndex(obj.name, index)
+ for attribute, i in indices.items():
+ if i in used:
+ continue
+ used.add(i)
+
+ baseMorph.add(i, pos)
+ indexRelativeMap[i]=relativeIndex
+ relativeIndex+=1
break
assert(basis)
if offset[0]==0 and offset[1]==0 and offset[2]==0:
continue
if index in vg:
- i=self.vertexArray.getMappedIndex(obj.name, index)
- if i in used:
- continue
- used.add(i)
- morph.add(indexRelativeMap[i], offset)
- #indices=self.vertexArray.getMappedIndices(index)
- #for i in indices:
- # if i in used:
- # continue
- # used.add(i)
- # morph.add(indexRelativeMap[i], offset)
+ indices=self.vertexArray.getMappedIndex(obj.name, index)
+ for attribute, i in indices.items():
+ if i in used:
+ continue
+ used.add(i)
+ morph.add(indexRelativeMap[i], offset)
assert(len(morph.offsets)<len(baseMorph.offsets))
# sort skinmap
return m
def getVertexCount(self):
- return len(self.vertexArray.vertices)
+ return len(self.vertexArray.positions)
class Bone(object):
__slots__=['index', 'name', 'ik_index',
'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
- def __init__(self, name, pos, tail):
+ def __init__(self, name, pos, tail, isConnect):
self.index=-1
self.name=name
self.pos=pos
self.parent_index=None
self.tail_index=None
self.type=0
- self.isConnect=False
+ self.isConnect=isConnect
self.ik_index=0
def __eq__(self, rhs):
# get bones
####################
for b in armature.bones.values():
- if b.name=='center':
- # root bone
- bone=Bone(b.name,
- bl.bone.getHeadLocal(b),
- bl.bone.getTailLocal(b))
- self.__addBone(bone)
- self.__getBone(bone, b)
-
- for b in armature.bones.values():
- if not b.parent and b.name!='center':
+ if not b.parent:
# root bone
bone=Bone(b.name,
bl.bone.getHeadLocal(b),
- bl.bone.getTailLocal(b))
+ bl.bone.getTailLocal(b),
+ False)
self.__addBone(bone)
self.__getBone(bone, b)
if b.type==6 or b.type==7:
# fix tail bone
parent=self.bones[b.parent_index]
+ #print('parnet', parent.name)
parent.tail_index=b.index
for b in self.bones:
for i, c in enumerate(b.children):
bone=Bone(c.name,
bl.bone.getHeadLocal(c),
- bl.bone.getTailLocal(c))
+ bl.bone.getTailLocal(c),
+ bl.bone.isConnected(c))
self.__addBone(bone)
if parent:
bone.parent_index=parent.index
- if i==0:
+ #if i==0:
+ if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
parent.tail_index=bone.index
self.__getBone(bone, c)
class PmdExporter(object):
- def setup(self, scene):
+ __slots__=[
+ 'armatureObj',
+ 'oneSkinMesh',
+ 'englishName',
+ 'englishComment',
+ 'name',
+ 'comment',
+ 'skeleton',
+ ]
+ def setup(self):
self.armatureObj=None
- self.scene=scene
# 木構造を構築する
object_node_map={}
- for o in scene.objects:
+ for o in bl.object.each():
object_node_map[o]=Node(o)
- for o in scene.objects:
- #for node in object_node_map.values():
+ for o in bl.object.each():
node=object_node_map[o]
if node.o.parent:
object_node_map[node.o.parent].children.append(node)
# ルートを得る
- root=object_node_map[scene.objects.active]
+ root=object_node_map[bl.object.getActive()]
+ o=root.o
+ self.englishName=o.name
+ self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
+ self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
+ self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
# ワンスキンメッシュを作る
- self.oneSkinMesh=OneSkinMesh(scene)
+ self.oneSkinMesh=OneSkinMesh()
self.__createOneSkinMesh(root)
bl.message(self.oneSkinMesh)
if len(self.oneSkinMesh.morphList)==0:
# create emtpy skin
self.oneSkinMesh.createEmptyBasicSkin()
- self.name=root.o.name
-
# skeleton
self.skeleton=BoneBuilder()
self.skeleton.build(self.armatureObj)
for child in node.children:
self.__createOneSkinMesh(child)
- def write(self, path, scene):
+ def write(self, path):
io=pmd.IO()
- io.name=self.name
- io.comment="blender export"
+ io.setName(toCP932(self.name))
+ io.setComment(toCP932(self.comment))
io.version=1.0
# 頂点
- for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
+ for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
# convert right-handed z-up to left-handed y-up
v=io.addVertex()
v.pos.x=pos[0]
v.pos.y=pos[2]
v.pos.z=pos[1]
- v.normal.x=normal[0]
- v.normal.y=normal[2]
- v.normal.z=normal[1]
- v.uv.x=uv[0]
- v.uv.y=1.0-uv[1] # reverse vertical
+ v.normal.x=attribute.nx
+ v.normal.y=attribute.ny
+ v.normal.z=attribute.nz
+ v.uv.x=attribute.u
+ v.uv.y=1.0-attribute.v # reverse vertical
v.bone0=self.skeleton.indexByName(b0)
v.bone1=self.skeleton.indexByName(b1)
v.weight0=int(100*weight)
material.vertex_count=len(indices)
material.toon_index=0
textures=[os.path.basename(path)
- for path in bl.material.eachTexturePath(m)]
+ for path in bl.material.eachEnalbeTexturePath(m)]
if len(textures)>0:
material.setTexture(toCP932('*'.join(textures)))
else:
#assert(len(io.bones)==len(io.bone_display_list)+1)
# English
- io.setEnglishName(toCP932("blender export\n"))
- io.setEnglishComment(toCP932("blender export comment"))
+ io.setEnglishName(toCP932(self.englishName))
+ io.setEnglishComment(toCP932(self.englishComment))
# toon
toonMeshObject=None
- for o in scene.objects:
- if o.name.startswith(TOON_TEXTURE_OBJECT):
- toonMeshObject=o
- break
+ for o in bl.object.each():
+ try:
+ if o.name.startswith(TOON_TEXTURE_OBJECT):
+ toonMeshObject=o
+ except:
+ p(o.name)
+ break
if toonMeshObject:
toonMesh=bl.object.getData(toonMeshObject)
toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
# rigid body
rigidNameMap={}
for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
+ name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
+ print(name)
rigidBody=io.addRigidBody()
- rigidBody.setName(obj.name.encode('cp932'))
- rigidNameMap[obj.name]=i
+ rigidBody.setName(name.encode('cp932'))
+ rigidNameMap[name]=i
boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
if boneIndex==0:
boneIndex=0xFFFF
return io.write(path)
-def __execute(filename, scene):
- if not scene.objects.active:
+def __execute(filename):
+ active=bl.object.getActive()
+ if not active:
print("abort. no active object.")
return
-
- active=bl.object.getActive()
exporter=PmdExporter()
- exporter.setup(scene)
- exporter.write(filename, scene)
+ exporter.setup()
+ print(exporter)
+ exporter.write(filename)
bl.object.activate(active)
if isBlender24():
# for 2.4
def execute_24(filename):
- scene = bpy.data.scenes.active
- bl.initialize('pmd_export', scene)
- __execute(filename.decode(bl.INTERNAL_ENCODING), scene)
+ bl.initialize('pmd_export', bpy.data.scenes.active)
+ __execute(filename.decode(bl.INTERNAL_ENCODING))
bl.finalize()
Blender.Window.FileSelector(
# for 2.5
def execute_25(filename, scene):
bl.initialize('pmd_export', scene)
- __execute(filename, scene)
+ __execute(filename)
bl.finalize()
# operator
# List of operator properties, the attributes will be assigned
# to the class instance from the operator settings before calling.
-
- path = StringProperty(
- name="File Path",
- description="File path used for exporting the PMD file",
- maxlen= 1024,
- default= ""
- )
- filename = StringProperty(
- name="File Name",
- description="Name of the file.")
- directory = StringProperty(
- name="Directory",
- description="Directory of the file.")
-
- check_existing = BoolProperty(
- name="Check Existing",
- description="Check and warn on overwriting existing files",
- default=True,
- options=set('HIDDEN'))
+ filepath = bpy.props.StringProperty()
+ filename = bpy.props.StringProperty()
+ directory = bpy.props.StringProperty()
def execute(self, context):
execute_25(
- self.properties.path,
+ self.properties.filepath,
context.scene
)
return 'FINISHED'
# register menu
def menu_func(self, context):
- #default_path=bpy.data.filename.replace(".blend", ".pmd")
+ default_path=bpy.data.filepath.replace(".blend", ".pmd")
self.layout.operator(
EXPORT_OT_pmd.bl_idname,
- text="Miku Miku Dance Model(.pmd)")#.path=default_path
+ text="Miku Miku Dance Model(.pmd)",
+ icon='PLUGIN'
+ ).filepath=default_path
def register():
bpy.types.register(EXPORT_OT_pmd)