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.
21 1.2 20100616: implement rigid body.
22 1.3 20100619: fix rigid body, bone weight.
23 1.4 20100626: refactoring.
24 1.5 20100629: sphere map.
25 1.6 20100710: toon texture & bone group.
26 1.7 20100711: separate vertex with normal or uv.
29 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
30 BASE_SHAPE_NAME='Basis'
31 RIGID_SHAPE_TYPE='rigid_shape_type'
32 RIGID_PROCESS_TYPE='rigid_process_type'
33 RIGID_BONE_NAME='rigid_bone_name'
34 #RIGID_LOCATION='rigid_loation'
35 RIGID_GROUP='ribid_group'
36 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
37 RIGID_WEIGHT='rigid_weight'
38 RIGID_LINEAR_DAMPING='rigid_linear_damping'
39 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
40 RIGID_RESTITUTION='rigid_restitution'
41 RIGID_FRICTION='rigid_friction'
42 CONSTRAINT_NAME='constraint_name'
43 CONSTRAINT_A='const_a'
44 CONSTRAINT_B='const_b'
45 CONSTRAINT_POS_MIN='const_pos_min'
46 CONSTRAINT_POS_MAX='const_pos_max'
47 CONSTRAINT_ROT_MIN='const_rot_min'
48 CONSTRAINT_ROT_MAX='const_rot_max'
49 CONSTRAINT_SPRING_POS='const_spring_pos'
50 CONSTRAINT_SPRING_ROT='const_spring_rot'
51 TOON_TEXTURE_OBJECT='ToonTextures'
54 ###############################################################################
56 ###############################################################################
61 from meshio import pmd, englishmap
64 return sys.version_info[0]<3
69 from Blender import Mathutils
75 def setMaterialParams(material, m):
77 material.diffuse.r=m.R
78 material.diffuse.g=m.G
79 material.diffuse.b=m.B
80 material.diffuse.a=m.alpha
82 material.sinness=0 if m.spec<1e-5 else m.spec*10
83 material.specular.r=m.specR
84 material.specular.g=m.specG
85 material.specular.b=m.specB
87 material.ambient.r=m.mirR
88 material.ambient.g=m.mirG
89 material.ambient.b=m.mirB
91 material.flag=1 if m.enableSSS else 0
100 from bpy.props import *
108 def setMaterialParams(material, m):
110 material.diffuse.r=m.diffuse_color[0]
111 material.diffuse.g=m.diffuse_color[1]
112 material.diffuse.b=m.diffuse_color[2]
113 material.diffuse.a=m.alpha
115 material.sinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
116 material.specular.r=m.specular_color[0]
117 material.specular.g=m.specular_color[1]
118 material.specular.b=m.specular_color[2]
120 material.ambient.r=m.mirror_color[0]
121 material.ambient.g=m.mirror_color[1]
122 material.ambient.b=m.mirror_color[2]
124 material.flag=1 if m.subsurface_scattering.enabled else 0
126 material.toon_index=7
129 return s.encode('cp932')
133 __slots__=['o', 'children']
134 def __init__(self, o):
139 ###############################################################################
140 # Blenderのメッシュをワンスキンメッシュ化する
141 ###############################################################################
142 def near(x, y, EPSILON=1e-5):
144 return d>=-EPSILON and d<=EPSILON
147 class VertexAttribute(object):
149 'nx', 'ny', 'nz', # normal
152 def __init__(self, nx, ny, nz, u, v):
160 return "<vkey: %f, %f, %f, %f, %f>" % (
161 self.nx, self.ny, self.nz, self.u, self.v)
164 return self.nx + self.ny + self.nz + self.u + self.v
166 def __eq__(self, rhs):
167 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
170 class VertexKey(object):
172 'obj_index', 'index',
175 def __init__(self, obj_index, index):
176 self.obj_index=obj_index
180 return "<vkey: %d, %d>" % (self.obj_index, self.index)
183 return self.index*100+self.obj_index
185 def __eq__(self, rhs):
186 return self.obj_index==rhs.obj_index and self.index==rhs.index
189 class VertexArray(object):
196 'attributes', # normal and uv
197 'b0', 'b1', 'weight',
202 # indexArrays split with each material
215 return "<VertexArray %d positions, %d indexArrays>" % (
216 len(self.positions), len(self.indexArrays))
220 self.positions, self.attributes,
221 self.b0, self.b1, self.weight)
224 keys=[key for key in self.indexArrays.keys()]
227 yield(key, self.indexArrays[key])
229 def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
230 key=VertexKey(obj_index, base_index)
231 attribute=VertexAttribute(
232 normal[0], normal[1], normal[2],
234 if key in self.vertexMap:
235 if attribute in self.vertexMap[key]:
236 return self.vertexMap[key][attribute]
238 return self.__addVertex(self.vertexMap[key],
239 pos, attribute, b0, b1, weight0)
242 self.vertexMap[key]=vertexMapKey
243 return self.__addVertex(vertexMapKey,
244 pos, attribute, b0, b1, weight0)
246 def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
247 index=len(self.positions)
248 vertexMapKey[attribute]=index
250 self.positions.append((pos.x, pos.y, pos.z))
252 self.attributes.append(attribute)
256 self.weight.append(weight0)
260 def getMappedIndex(self, obj_name, base_index):
261 return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
263 def addTriangle(self,
264 object_name, material,
265 base_index0, base_index1, base_index2,
271 weight0, weight1, weight2
273 if object_name in self.objectMap:
274 obj_index=self.objectMap[object_name]
276 obj_index=len(self.objectMap)
277 self.objectMap[object_name]=obj_index
278 index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
279 index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
280 index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
282 if not material in self.indexArrays:
283 self.indexArrays[material]=[]
284 self.indexArrays[material]+=[index0, index1, index2]
288 __slots__=['name', 'type', 'offsets']
289 def __init__(self, name, type):
294 def add(self, index, offset):
295 self.offsets.append((index, offset))
299 self.offsets.sort(lambda l, r: l[0]-r[0])
301 self.offsets.sort(key=lambda e: e[0])
304 return "<Morph %s>" % self.name
306 class IKSolver(object):
307 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
308 def __init__(self, target, effector, length, iterations, weight):
310 self.effector=effector
312 self.iterations=iterations
316 class OneSkinMesh(object):
317 __slots__=['scene', 'vertexArray', 'morphList',
321 def __init__(self, scene):
322 self.vertexArray=VertexArray()
329 return "<OneSkinMesh %s, morph:%d>" % (
333 def addMesh(self, obj):
334 if bl.object.isVisible(obj):
338 self.__rigidbody(obj)
339 self.__constraint(obj)
341 def __getWeightMap(self, obj, mesh):
345 def setWeight(i, name, w):
348 if i in secondWeightMap:
350 if w<secondWeightMap[i][1]:
352 elif w<weightMap[i][1]:
354 secondWeightMap[i]=(name, w)
357 weightMap[i]=(name, w)
359 if w>weightMap[i][1]:
361 secondWeightMap[i]=weightMap[i]
362 weightMap[i]=(name, w)
364 secondWeightMap[i]=(name, w)
366 weightMap[i]=(name, w)
368 # ToDo bone weightと関係ないvertex groupを除外する
370 for name in bl.object.getVertexGroupNames(obj):
371 for i, w in mesh.getVertsFromGroup(name, 1):
372 setWeight(i, name, w)
374 for i, v in enumerate(mesh.verts):
377 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
379 setWeight(i, obj.vertex_groups[0].name, 1)
382 for i in xrange(len(mesh.verts)):
383 #for i, name_weight in weightMap.items():
384 if i in secondWeightMap:
385 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
387 weightMap[i]=(weightMap[i][0], 1.0)
388 secondWeightMap[i]=("", 0)
390 print("no weight vertex")
392 secondWeightMap[i]=("", 0)
394 return weightMap, secondWeightMap
396 def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
398 for i, face in enumerate(mesh.faces):
399 faceVertexCount=bl.face.getVertexCount(face)
400 material=mesh.materials[bl.face.getMaterialIndex(face)]
401 v=[mesh.verts[index] for index in bl.face.getVertices(face)]
402 uv=bl.mesh.getFaceUV(
403 mesh, i, face, bl.face.getVertexCount(face))
405 if faceVertexCount==3:
407 self.vertexArray.addTriangle(
408 obj_name, material.name,
415 bl.vertex.getNormal(v[2]),
416 bl.vertex.getNormal(v[1]),
417 bl.vertex.getNormal(v[0]),
421 weightMap[v[2].index][0],
422 weightMap[v[1].index][0],
423 weightMap[v[0].index][0],
424 secondWeightMap[v[2].index][0],
425 secondWeightMap[v[1].index][0],
426 secondWeightMap[v[0].index][0],
427 weightMap[v[2].index][1],
428 weightMap[v[1].index][1],
429 weightMap[v[0].index][1]
431 elif faceVertexCount==4:
433 self.vertexArray.addTriangle(
434 obj_name, material.name,
441 bl.vertex.getNormal(v[2]),
442 bl.vertex.getNormal(v[1]),
443 bl.vertex.getNormal(v[0]),
447 weightMap[v[2].index][0],
448 weightMap[v[1].index][0],
449 weightMap[v[0].index][0],
450 secondWeightMap[v[2].index][0],
451 secondWeightMap[v[1].index][0],
452 secondWeightMap[v[0].index][0],
453 weightMap[v[2].index][1],
454 weightMap[v[1].index][1],
455 weightMap[v[0].index][1]
457 self.vertexArray.addTriangle(
458 obj_name, material.name,
465 bl.vertex.getNormal(v[0]),
466 bl.vertex.getNormal(v[3]),
467 bl.vertex.getNormal(v[2]),
471 weightMap[v[0].index][0],
472 weightMap[v[3].index][0],
473 weightMap[v[2].index][0],
474 secondWeightMap[v[0].index][0],
475 secondWeightMap[v[3].index][0],
476 secondWeightMap[v[2].index][0],
477 weightMap[v[0].index][1],
478 weightMap[v[3].index][1],
479 weightMap[v[2].index][1]
482 def __mesh(self, obj):
486 if RIGID_SHAPE_TYPE in obj:
488 if CONSTRAINT_A in obj:
491 #if not bl.modifier.hasType(obj, 'ARMATURE'):
494 bl.message("export: %s" % obj.name)
496 # メッシュのコピーを生成してオブジェクトの行列を適用する
497 copyMesh, copyObj=bl.object.duplicate(obj)
498 if len(copyMesh.verts)==0:
501 copyObj.scale=obj.scale
502 bpy.ops.object.scale_apply()
503 copyObj.rotation_euler=obj.rotation_euler
504 bpy.ops.object.rotation_apply()
505 copyObj.location=obj.location
506 bpy.ops.object.location_apply()
508 for m in [m for m in copyObj.modifiers]:
509 if m.type=='SOLIDFY':
511 elif m.type=='ARMATURE':
513 elif m.type=='MIRROR':
514 bpy.ops.object.modifier_apply(modifier=m.name)
518 weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
519 self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
521 bl.object.delete(copyObj)
523 def createEmptyBasicSkin(self):
524 self.__getOrCreateMorph('base', 0)
526 def __skin(self, obj):
527 if not bl.object.hasShapeKey(obj):
531 blenderMesh=bl.object.getData(obj)
535 vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
539 for b in bl.object.getShapeKeys(obj):
540 if b.name==BASE_SHAPE_NAME:
541 baseMorph=self.__getOrCreateMorph('base', 0)
546 v=bl.shapekey.getByIndex(b, index)
547 pos=[v[0], v[1], v[2]]
549 indices=self.vertexArray.getMappedIndex(obj.name, index)
550 for attribute, i in indices.items():
555 baseMorph.add(i, pos)
556 indexRelativeMap[i]=relativeIndex
561 print(basis.name, len(baseMorph.offsets))
563 if len(baseMorph.offsets)==0:
567 for b in bl.object.getShapeKeys(obj):
568 if b.name==BASE_SHAPE_NAME:
572 morph=self.__getOrCreateMorph(b.name, 4)
574 for index, src, dst in zip(
575 xrange(len(blenderMesh.verts)),
576 bl.shapekey.get(basis),
578 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
579 if offset[0]==0 and offset[1]==0 and offset[2]==0:
582 indices=self.vertexArray.getMappedIndex(obj.name, index)
583 for attribute, i in indices.items():
587 morph.add(indexRelativeMap[i], offset)
588 assert(len(morph.offsets)<len(baseMorph.offsets))
591 original=self.morphList[:]
593 for i, v in enumerate(englishmap.skinMap):
597 return len(englishmap.skinMap)
599 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
601 self.morphList.sort(key=getIndex)
603 def __rigidbody(self, obj):
606 if not RIGID_SHAPE_TYPE in obj:
608 self.rigidbodies.append(obj)
610 def __constraint(self, obj):
613 if not CONSTRAINT_A in obj:
615 self.constraints.append(obj)
617 def __getOrCreateMorph(self, name, type):
618 for m in self.morphList:
622 self.morphList.append(m)
625 def getVertexCount(self):
626 return len(self.vertexArray.positions)
630 __slots__=['index', 'name', 'ik_index',
631 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
632 def __init__(self, name, pos, tail):
637 self.parent_index=None
643 def __eq__(self, rhs):
644 return self.index==rhs.index
647 return "<Bone %s %d>" % (self.name, self.type)
649 class BoneBuilder(object):
650 __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
657 def getBoneGroup(self, bone):
658 for i, g in enumerate(self.bone_groups):
662 print('no gorup', bone)
665 def build(self, armatureObj):
669 bl.message("build skeleton")
670 armature=bl.object.getData(armatureObj)
675 for g in bl.object.boneGroups(armatureObj):
676 self.bone_groups.append((g.name, []))
681 for b in armature.bones.values():
685 bl.bone.getHeadLocal(b),
686 bl.bone.getTailLocal(b))
688 self.__getBone(bone, b)
690 for b in armature.bones.values():
691 if not b.parent and b.name!='center':
694 bl.bone.getHeadLocal(b),
695 bl.bone.getTailLocal(b))
697 self.__getBone(bone, b)
699 for b in armature.bones.values():
701 self.__checkConnection(b, None)
706 pose = bl.object.getPose(armatureObj)
707 for b in pose.bones.values():
711 self.__assignBoneGroup(b, b.bone_group)
712 for c in b.constraints:
713 if bl.constraint.isIKSolver(c):
717 target=self.__boneByName(bl.constraint.ikTarget(c))
724 link=self.__boneByName(b.name)
729 chainLength=bl.constraint.ikChainLen(c)
730 for i in range(chainLength):
732 chainBone=self.__boneByName(e.name)
734 chainBone.ik_index=target.index
737 IKSolver(target, link, chainLength,
738 int(bl.constraint.ikItration(c) * 0.1),
739 bl.constraint.ikRotationWeight(c)
749 for i, v in enumerate(englishmap.boneMap):
750 if v[0]==ik.target.name:
752 return len(englishmap.boneMap)
754 self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
756 self.ik_list.sort(key=getIndex)
758 def __assignBoneGroup(self, poseBone, boneGroup):
760 for g in self.bone_groups:
761 if g[0]==boneGroup.name:
762 g[1].append(poseBone.name)
764 def __checkConnection(self, b, p):
765 if bl.bone.isConnected(b):
766 parent=self.__boneByName(p.name)
767 parent.isConnect=True
770 self.__checkConnection(c, b)
776 boneMap=englishmap.boneMap
777 original=self.bones[:]
779 for i, k_v in enumerate(boneMap):
780 if k_v[0]==bone.name:
786 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
788 self.bones.sort(key=getIndex)
791 for i, b in enumerate(self.bones):
792 src=original.index(b)
795 b.index=sortMap[b.index]
797 b.parent_index=sortMap[b.parent_index]
799 b.tail_index=sortMap[b.tail_index]
801 b.ik_index=sortMap[b.ik_index]
809 if b.parent_index==None:
810 b.parent_index=0xFFFF
812 if b.type==6 or b.type==7:
814 parent=self.bones[b.parent_index]
815 parent.tail_index=b.index
818 if b.tail_index==None:
823 def getIndex(self, bone):
824 for i, b in enumerate(self.bones):
829 def indexByName(self, name):
833 return self.getIndex(self.__boneByName(name))
835 def __boneByName(self, name):
836 return self.boneMap[name]
838 def __getBone(self, parent, b):
839 if len(b.children)==0:
843 for i, c in enumerate(b.children):
845 bl.bone.getHeadLocal(c),
846 bl.bone.getTailLocal(c))
849 bone.parent_index=parent.index
851 parent.tail_index=bone.index
852 self.__getBone(bone, c)
854 def __addBone(self, bone):
855 bone.index=len(self.bones)
856 self.bones.append(bone)
857 self.boneMap[bone.name]=bone
860 class PmdExporter(object):
862 def setup(self, scene):
863 self.armatureObj=None
868 for o in scene.objects:
869 object_node_map[o]=Node(o)
870 for o in scene.objects:
871 #for node in object_node_map.values():
872 node=object_node_map[o]
874 object_node_map[node.o.parent].children.append(node)
877 root=object_node_map[scene.objects.active]
880 self.oneSkinMesh=OneSkinMesh(scene)
881 self.__createOneSkinMesh(root)
882 bl.message(self.oneSkinMesh)
883 if len(self.oneSkinMesh.morphList)==0:
885 self.oneSkinMesh.createEmptyBasicSkin()
887 self.name=root.o.name
890 self.skeleton=BoneBuilder()
891 self.skeleton.build(self.armatureObj)
893 def __createOneSkinMesh(self, node):
894 ############################################################
895 # search armature modifier
896 ############################################################
897 for m in node.o.modifiers:
898 if bl.modifier.isType(m, 'ARMATURE'):
899 armatureObj=bl.modifier.getArmatureObject(m)
900 if not self.armatureObj:
901 self.armatureObj=armatureObj
902 elif self.armatureObj!=armatureObj:
903 print("warning! found multiple armature. ignored.",
906 if node.o.type.upper()=='MESH':
907 self.oneSkinMesh.addMesh(node.o)
909 for child in node.children:
910 self.__createOneSkinMesh(child)
912 def write(self, path, scene):
915 io.comment="blender export"
919 for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
920 # convert right-handed z-up to left-handed y-up
925 v.normal.x=attribute.nx
926 v.normal.y=attribute.ny
927 v.normal.z=attribute.nz
929 v.uv.y=1.0-attribute.v # reverse vertical
930 v.bone0=self.skeleton.indexByName(b0)
931 v.bone1=self.skeleton.indexByName(b1)
932 v.weight0=int(100*weight)
933 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
936 vertexCount=self.oneSkinMesh.getVertexCount()
937 for material_name, indices in self.oneSkinMesh.vertexArray.each():
938 #print('material:', material_name)
939 m=bl.material.get(material_name)
941 material=io.addMaterial()
942 setMaterialParams(material, m)
944 material.vertex_count=len(indices)
945 material.toon_index=0
946 textures=[os.path.basename(path)
947 for path in bl.material.eachEnalbeTexturePath(m)]
949 material.setTexture(toCP932('*'.join(textures)))
951 material.setTexture(toCP932(""))
954 assert(i<vertexCount)
955 for i in xrange(0, len(indices), 3):
957 io.indices.append(indices[i])
958 io.indices.append(indices[i+1])
959 io.indices.append(indices[i+2])
963 for i, b in enumerate(self.skeleton.bones):
967 boneNameMap[b.name]=i
968 v=englishmap.getUnicodeBoneName(b.name)
972 cp932=v[1].encode('cp932')
973 assert(len(cp932)<20)
977 bone_english_name=toCP932(b.name)
978 assert(len(bone_english_name)<20)
979 bone.setEnglishName(bone_english_name)
984 b.ik_index=self.skeleton.indexByName('eyes')
989 bone.parent_index=b.parent_index
990 bone.tail_index=b.tail_index
991 bone.ik_index=b.ik_index
993 # convert right-handed z-up to left-handed y-up
994 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
995 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
996 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
999 for ik in self.skeleton.ik_list:
1001 solver.index=self.skeleton.getIndex(ik.target)
1002 solver.target=self.skeleton.getIndex(ik.effector)
1003 solver.length=ik.length
1004 b=self.skeleton.bones[ik.effector.parent_index]
1005 for i in xrange(solver.length):
1006 solver.children.append(self.skeleton.getIndex(b))
1007 b=self.skeleton.bones[b.parent_index]
1008 solver.iterations=ik.iterations
1009 solver.weight=ik.weight
1012 for i, m in enumerate(self.oneSkinMesh.morphList):
1016 v=englishmap.getUnicodeSkinName(m.name)
1018 v=[m.name, m.name, 0]
1020 cp932=v[1].encode('cp932')
1021 morph.setName(cp932)
1022 morph.setEnglishName(m.name.encode('cp932'))
1025 for index, offset in m.offsets:
1026 # convert right-handed z-up to left-handed y-up
1027 morph.append(index, offset[0], offset[2], offset[1])
1028 morph.vertex_count=len(m.offsets)
1032 for i, m in enumerate(self.oneSkinMesh.morphList):
1034 io.face_list.append(i)
1035 for i, m in enumerate(self.oneSkinMesh.morphList):
1037 io.face_list.append(i)
1038 for i, m in enumerate(self.oneSkinMesh.morphList):
1040 io.face_list.append(i)
1041 for i, m in enumerate(self.oneSkinMesh.morphList):
1043 io.face_list.append(i)
1046 for g in self.skeleton.bone_groups:
1047 boneDisplayName=io.addBoneGroup()
1049 name=englishmap.getUnicodeBoneGroupName(g[0])
1052 boneDisplayName.setName(toCP932(name+'\n'))
1055 boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1058 for i, b in enumerate(self.skeleton.bones):
1061 if b.type in [6, 7]:
1063 io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1065 #assert(len(io.bones)==len(io.bone_display_list)+1)
1068 io.setEnglishName(toCP932("blender export\n"))
1069 io.setEnglishComment(toCP932("blender export comment"))
1073 for o in scene.objects:
1074 if o.name.startswith(TOON_TEXTURE_OBJECT):
1078 toonMesh=bl.object.getData(toonMeshObject)
1079 toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1081 t=bl.material.getTexture(toonMaterial, i)
1083 io.getToonTexture(i).setName(toCP932(t.name))
1085 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1088 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1092 for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1093 rigidBody=io.addRigidBody()
1094 rigidBody.setName(obj.name.encode('cp932'))
1095 rigidNameMap[obj.name]=i
1096 boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1099 bone=self.skeleton.bones[0]
1101 bone=self.skeleton.bones[boneIndex]
1102 rigidBody.boneIndex=boneIndex
1103 #rigidBody.position.x=obj[RIGID_LOCATION][0]
1104 #rigidBody.position.y=obj[RIGID_LOCATION][1]
1105 #rigidBody.position.z=obj[RIGID_LOCATION][2]
1106 rigidBody.position.x=obj.location.x-bone.pos[0]
1107 rigidBody.position.y=obj.location.z-bone.pos[2]
1108 rigidBody.position.z=obj.location.y-bone.pos[1]
1109 rigidBody.rotation.x=-obj.rotation_euler[0]
1110 rigidBody.rotation.y=-obj.rotation_euler[2]
1111 rigidBody.rotation.z=-obj.rotation_euler[1]
1112 rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1113 rigidBody.group=obj[RIGID_GROUP]
1114 rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1115 rigidBody.weight=obj[RIGID_WEIGHT]
1116 rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1117 rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1118 rigidBody.restitution=obj[RIGID_RESTITUTION]
1119 rigidBody.friction=obj[RIGID_FRICTION]
1120 if obj[RIGID_SHAPE_TYPE]==0:
1121 rigidBody.shapeType=pmd.SHAPE_SPHERE
1122 rigidBody.w=obj.scale[0]
1123 elif obj[RIGID_SHAPE_TYPE]==1:
1124 rigidBody.shapeType=pmd.SHAPE_BOX
1125 rigidBody.w=obj.scale[0]
1126 rigidBody.d=obj.scale[1]
1127 rigidBody.h=obj.scale[2]
1128 elif obj[RIGID_SHAPE_TYPE]==2:
1129 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1130 rigidBody.w=obj.scale[0]
1131 rigidBody.h=obj.scale[2]
1134 for obj in self.oneSkinMesh.constraints:
1135 constraint=io.addConstraint()
1136 constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1137 constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1138 constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1139 constraint.pos.x=obj.location[0]
1140 constraint.pos.y=obj.location[2]
1141 constraint.pos.z=obj.location[1]
1142 constraint.rot.x=-obj.rotation_euler[0]
1143 constraint.rot.y=-obj.rotation_euler[2]
1144 constraint.rot.z=-obj.rotation_euler[1]
1145 constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1146 constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1147 constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1148 constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1149 constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1150 constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1151 constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1152 constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1153 constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1154 constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1155 constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1156 constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1157 constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1158 constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1159 constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1160 constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1161 constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1162 constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1165 bl.message('write %s' % path)
1166 return io.write(path)
1169 def __execute(filename, scene):
1170 if not scene.objects.active:
1171 print("abort. no active object.")
1174 active=bl.object.getActive()
1175 exporter=PmdExporter()
1176 exporter.setup(scene)
1177 exporter.write(filename, scene)
1178 bl.object.activate(active)
1183 def execute_24(filename):
1184 scene = bpy.data.scenes.active
1185 bl.initialize('pmd_export', scene)
1186 __execute(filename.decode(bl.INTERNAL_ENCODING), scene)
1189 Blender.Window.FileSelector(
1191 'Export Metasequoia PMD',
1192 Blender.sys.makename(ext='.pmd'))
1196 def execute_25(filename, scene):
1197 bl.initialize('pmd_export', scene)
1198 __execute(filename, scene)
1202 class EXPORT_OT_pmd(bpy.types.Operator):
1203 '''Save a Metasequoia PMD file.'''
1204 bl_idname = "export_scene.pmd"
1205 bl_label = 'Export PMD'
1207 # List of operator properties, the attributes will be assigned
1208 # to the class instance from the operator settings before calling.
1210 path = StringProperty(
1212 description="File path used for exporting the PMD file",
1216 filename = StringProperty(
1218 description="Name of the file.")
1219 directory = StringProperty(
1221 description="Directory of the file.")
1223 check_existing = BoolProperty(
1224 name="Check Existing",
1225 description="Check and warn on overwriting existing files",
1227 options=set('HIDDEN'))
1229 def execute(self, context):
1231 self.properties.path,
1236 def invoke(self, context, event):
1238 wm.add_fileselect(self)
1239 return 'RUNNING_MODAL'
1242 def menu_func(self, context):
1243 #default_path=bpy.data.filename.replace(".blend", ".pmd")
1244 self.layout.operator(
1245 EXPORT_OT_pmd.bl_idname,
1246 text="Miku Miku Dance Model(.pmd)")#.path=default_path
1249 bpy.types.register(EXPORT_OT_pmd)
1250 bpy.types.INFO_MT_file_export.append(menu_func)
1253 bpy.types.unregister(EXPORT_OT_pmd)
1254 bpy.types.INFO_MT_file_export.remove(menu_func)
1256 if __name__ == "__main__":