OSDN Git Service

5fc37b8f091ed307ef6cc2ed752e38804c35e899
[meshio/meshio.git] / swig / blender24 / pmd_export.py
1 #!BPY
2 # coding: utf-8
3 """
4  Name: 'MikuMikuDance model (.pmd)...'
5  Blender: 248
6  Group: 'Export'
7  Tooltip: 'Export PMD file for MikuMikuDance.'
8 """
9 __author__= ["ousttrue"]
10 __version__= "0.2"
11 __url__=()
12 __bpydoc__="""
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
15 """
16 import Blender
17 import os
18 import sys
19
20 from meshio import pmd, englishmap
21
22
23 # ファイルシステムの文字コード
24 # 改造版との共用のため
25 FS_ENCODING=sys.getfilesystemencoding()
26 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
27     INTERNAL_ENCODING='utf-8'
28 else:
29     INTERNAL_ENCODING=FS_ENCODING
30
31
32 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
33 EXTENSION = u'.pmd'
34
35
36 class Node(object):
37     __slots__=['o', 'children']
38     def __init__(self, o):
39         self.o=o
40         self.children=[]
41
42
43 ###############################################################################
44 # Blenderのメッシュをワンスキンメッシュ化する
45 ###############################################################################
46 def near(x, y, EPSILON=1e-5):
47     d=x-y
48     return d>=-EPSILON and d<=EPSILON
49
50
51 class VertexKey(object):
52     """
53     重複頂点の検索キー
54     """
55     __slots__=[
56             'x', 'y', 'z', # 位置
57             'nx', 'ny', 'nz', # 法線
58             'u', 'v', # uv
59             ]
60
61     def __init__(self, x, y, z, nx, ny, nz, u, v):
62         self.x=x
63         self.y=y
64         self.z=z
65         self.nx=nx
66         self.ny=ny
67         self.nz=nz
68         self.u=u
69         self.v=v
70
71     def __str__(self):
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)
74
75     def __hash__(self):
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)
78
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
83
84
85 class VertexArray(object):
86     """
87     頂点配列
88     """
89     def __init__(self):
90         # マテリアル毎に分割したインデックス配列
91         self.indexArrays={}
92         # 頂点属性
93         self.vertices=[]
94         self.normals=[]
95         self.uvs=[]
96         # skinning属性
97         self.b0=[]
98         self.b1=[]
99         self.weight=[]
100
101         self.vertexMap={}
102         self.indexMap={}
103
104     def __str__(self):
105         return "<VertexArray %d vertices, %d indexArrays>" % (
106                 len(self.vertices), len(self.indexArrays))
107
108     def zip(self):
109         return zip(
110                 self.vertices, self.normals, self.uvs,
111                 self.b0, self.b1, self.weight)
112
113     def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
114         """
115         頂点属性からその頂点のインデックスを得る
116         """
117         key=VertexKey(
118                 pos[0], pos[1], pos[2],
119                 normal[0], normal[1], normal[2],
120                 uv[0], uv[1])
121         if key in self.vertexMap:
122             # 同じ頂点を登録済み
123             index=self.vertexMap[key]
124         else:
125             index=len(self.vertices)
126             # 新規頂点
127             self.vertexMap[key]=index
128             # append...
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))
132             self.b0.append(b0)
133             self.b1.append(b1)
134             self.weight.append(weight0)
135             
136         # indexのマッピングを保存する
137         if not base_index in self.indexMap:
138             self.indexMap[base_index]=set()
139         self.indexMap[base_index].add(index)
140
141         assert(index<=65535)
142         return index
143
144     def getMappedIndices(self, base_index):
145         return self.indexMap[base_index]
146
147     def addTriangle(self,
148             material,
149             base_index0, base_index1, base_index2,
150             pos0, pos1, pos2,
151             n0, n1, n2,
152             uv0, uv1, uv2,
153             b0_0, b0_1, b0_2,
154             b1_0, b1_1, b1_2,
155             weight0, weight1, weight2
156             ):
157         if not material in self.indexArrays:
158             self.indexArrays[material]=[]
159
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)
163
164         self.indexArrays[material]+=[index0, index1, index2]
165
166
167 class Morph(object):
168     __slots__=['name', 'type', 'indices', 'offsets']
169     def __init__(self, name, type):
170         self.name=name
171         self.type=type
172         self.indices=[]
173         self.offsets=[]
174
175
176 class IKSolver(object):
177     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
178     def __init__(self, target, effector, length, iterations, weight):
179         self.target=target
180         self.effector=effector
181         self.length=length
182         self.iterations=iterations
183         self.weight=weight
184
185
186 class OneSkinMesh(object):
187     __slots__=['armatureObj', 'vertexArray', 'morphList']
188     def __init__(self, root):
189         self.armatureObj=None
190         self.vertexArray=VertexArray()
191         self.morphList=[]
192         self.__create(root)
193
194     def __str__(self):
195         return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
196                 self.armatureObj.name if self.armatureObj else None, 
197                 self.vertexArray,
198                 len(self.morphList))
199
200     def __create(self, node):
201         if node.o.getType()=='Mesh':
202             self.__addMesh(node.o)
203
204         for child in node.children:
205             self.__create(child)
206
207     def __addMesh(self, obj):
208         if obj.restrictDisplay:
209             # 非表示
210             return
211
212         print("export", obj.name)
213
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
224
225         ############################################################
226         # bone weight
227         ############################################################
228         mesh=obj.getData(mesh=True)
229         weightMap={}
230         secondWeightMap={}
231         for name in mesh.getVertGroupNames():
232             for i, w in mesh.getVertsFromGroup(name, 1):
233                 if w>0:
234                     if i in weightMap:
235                         if i in secondWeightMap:
236                             # 上位2つのweightを採用する
237                             if w<secondWeightMap[i]:
238                                 pass
239                             elif w<weightMap[i]:
240                                 # 2つ目を入れ替え
241                                 secondWeightMap[i]=(name, w)
242                             else:
243                                 # 1つ目を入れ替え
244                                 weightMap[i]=(name, w)
245                         else:
246                             if w>weightMap[i][1]:
247                                 # 多い方をweightMapに
248                                 secondWeightMap[i]=weightMap[i]
249                                 weightMap[i]=(name, w)
250                             else:
251                                 secondWeightMap[i]=(name, w)
252                     else:
253                         weightMap[i]=(name, w)
254
255         # 合計値が1になるようにする
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])
260             elif i in weightMap:
261                 weightMap[i]=(weightMap[i][0], 1.0)
262                 secondWeightMap[i]=("", 0)
263             else:
264                 print "no weight vertex"
265                 weightMap[i]=("", 0)
266                 secondWeightMap[i]=("", 0)
267                 
268
269         ############################################################
270         # faces
271         # 新たにメッシュを生成する
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:
279             return
280
281         for face in mesh.faces:
282             faceVertexCount=len(face.v)
283             material=mesh.materials[face.mat]
284             if faceVertexCount==3:
285                 v0=face.v[0]
286                 v1=face.v[1]
287                 v2=face.v[2]
288                 # triangle
289                 self.vertexArray.addTriangle(
290                         material.name,
291                         v0.index, v1.index, v2.index,
292                         v0.co, v1.co, v2.co,
293                         # ToDo vertex normal
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]
306                         )
307             elif faceVertexCount==4:
308                 v0=face.v[0]
309                 v1=face.v[1]
310                 v2=face.v[2]
311                 v3=face.v[3]
312                 # quadrangle
313                 self.vertexArray.addTriangle(
314                         material.name,
315                         v0.index, v1.index, v2.index,
316                         v0.co, v1.co, v2.co,
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]
329                         )
330                 self.vertexArray.addTriangle(
331                         material.name,
332                         v2.index, v3.index, v0.index,
333                         v2.co, v3.co, v0.co,
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]
346                         )
347
348         ############################################################
349         # skin
350         ############################################################
351         # base
352         indexRelativeMap={}
353         blenderMesh=obj.getData(mesh=True)
354         if blenderMesh.key:
355             for b in blenderMesh.key.blocks:
356                 if b.name=='Basis':
357                     print(b.name)
358                     morph=self.__getOrCreateMorph('base', 0)
359                     relativeIndex=0
360                     basis=b
361                     for index in blenderMesh.getVertsFromGroup(
362                             MMD_SHAPE_GROUP_NAME):
363                         v=b.data[index]
364                         pos=[v[0], v[1], v[2]]
365                         indices=self.vertexArray.getMappedIndices(index)
366                         for i in indices:
367                             morph.indices.append(i)
368                             morph.offsets.append(pos)
369                             indexRelativeMap[i]=relativeIndex
370                             relativeIndex+=1
371                     break
372
373             assert(basis)
374
375             # shape keys
376             for b in obj.getData(mesh=True).key.blocks:
377                 if b.name=='Basis':
378                     continue
379
380                 print(b.name)
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]
387                     dst=b.data[index]
388                     offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
389                     indices=self.vertexArray.getMappedIndices(index)
390                     for i in indices:
391                         morph.indices.append(indexRelativeMap[i])
392                         morph.offsets.append(offset)
393
394     def __getOrCreateMorph(self, name, type):
395         for m in self.morphList:
396             if m.name==name:
397                 return m
398         m=Morph(name, type)
399         self.morphList.append(m)
400         return m
401
402     def getVertexCount(self):
403         return len(self.vertexArray.vertices)
404
405
406 class Bone(object):
407     __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
408     def __init__(self, name, pos):
409         self.index=-1
410         self.name=name
411         self.pos=[pos.x, pos.y, pos.z]
412         self.parent_index=None
413         self.tail_index=None
414         self.type=0
415
416     def __str__(self):
417         return "<Bone %s %d>" % (self.name, self.type)
418
419 class BoneBuilder(object):
420     __slots__=['bones', 'boneMap', 'ik_list']
421     def __init__(self):
422         self.bones=[]
423         self.boneMap={}
424         self.ik_list=[]
425
426     def build(self, armatureObj):
427         if armatureObj:
428             armature=armatureObj.getData()
429             for b in armature.bones.values():
430                 if not b.parent:
431                     # root bone
432                     bone=Bone(b.name, b.head['ARMATURESPACE'])
433                     self.__addBone(bone)
434                     self.__getBone(bone, b)
435
436         pose = armatureObj.getPose()
437         cSetting=Blender.Constraint.Settings
438         for b in pose.bones.values():
439             for c in b.constraints:
440                 if c.type==Blender.Constraint.Type.IKSOLVER:
441                     ####################
442                     # IK effector
443                     ####################
444                     # IK 接続先
445                     link=self.__boneByName(b.name)
446                     link_tail=self.bones[link.tail_index]
447                     if link_tail.type==7:
448                         # replace ...先 to IK接続先
449                         link_tail.type=6
450
451                     # IK chain
452                     e=b
453                     chainLength=c[cSetting.CHAINLEN]
454                     for i in range(chainLength):
455                         # IK影響下
456                         self.__boneByName(e.name).type=4
457                         e=e.parent
458
459                     ####################
460                     # IK target
461                     ####################
462                     assert(c[cSetting.TARGET]==armatureObj)
463                     target=self.__boneByName(
464                             c[Blender.Constraint.Settings.BONE])
465                     target.type=2
466
467                     self.ik_list.append(
468                             IKSolver(target, link_tail, chainLength, 
469                                 c[cSetting.ITERATIONS], c.influence))
470
471     def getIndex(self, bone):
472         for i, b in enumerate(self.bones):
473             if b==bone:
474                 return i
475         assert(false)
476
477     def __boneByName(self, name):
478         return self.bones[self.boneMap[name]]
479                     
480     def __getBone(self, parent, b):
481         if not Blender.Armature.CONNECTED in b.options:
482             #print b, b.options
483             pass
484
485         if len(b.children)==0:
486             # 末端の非表示ボーン
487             bone=Bone(b.name+'_t', b.tail['ARMATURESPACE'])
488             bone.type=7
489             self.__addBone(bone)
490             assert(parent)
491             bone.parent_index=parent.index
492             parent.tail_index=bone.index
493             return
494
495         for i, c in enumerate(b.children):
496             bone=Bone(c.name, c.head['ARMATURESPACE'])
497             self.__addBone(bone)
498             if parent:
499                 bone.parent_index=parent.index
500                 if i==0:
501                     parent.tail_index=bone.index
502             self.__getBone(bone, c)
503
504     def __addBone(self, bone):
505         bone.index=len(self.bones)
506         self.bones.append(bone)
507         self.boneMap[bone.name]=bone.index
508
509
510 class PmdExporter(object):
511
512     def setup(self, scene):
513         # 木構造を構築する
514         object_node_map={}
515         for o in scene.objects:
516             object_node_map[o]=Node(o)
517         for node in object_node_map.values():
518             if node.o.parent:
519                 object_node_map[node.o.parent].children.append(node)
520         # ルートを得る
521         root=object_node_map[scene.objects.active]
522
523         # ワンスキンメッシュを作る
524         self.oneSkinMesh=OneSkinMesh(root)
525         print(self.oneSkinMesh)
526         self.name=root.o.name
527
528     def write(self, path):
529         io=pmd.IO()
530         io.name=self.name
531         io.comment="blender export"
532         io.version=1.0
533
534         # skeleton
535         builder=BoneBuilder()
536         builder.build(self.oneSkinMesh.armatureObj)
537
538         # 頂点
539         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
540             # convert right-handed z-up to left-handed y-up
541             v=io.addVertex()
542             v.pos.x=pos[0]
543             v.pos.y=pos[2]
544             v.pos.z=pos[1]
545             v.normal.x=normal[0]
546             v.normal.y=normal[2]
547             v.normal.z=normal[1]
548             v.uv.x=uv[0]
549             v.uv.y=uv[1]
550             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
551             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
552             v.weight0=int(100*weight)
553             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
554
555         # 面とマテリアル
556         vertexCount=self.oneSkinMesh.getVertexCount()
557         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
558             m=Blender.Material.Get(m)
559             # マテリアル
560             material=io.addMaterial()
561             material.diffuse.r=m.R
562             material.diffuse.g=m.G
563             material.diffuse.b=m.B
564             material.diffuse.a=m.alpha
565             material.sinness=m.spec
566             material.specular.r=m.specR
567             material.specular.g=m.specG
568             material.specular.b=m.specB
569             material.ambient.r=m.amb
570             material.ambient.g=m.amb
571             material.ambient.b=m.amb
572             material.vertex_count=len(indices)
573             material.toon_index=0
574             # ToDo
575             material.texture=""
576             # 面
577             for i in indices:
578                 assert(i<vertexCount)
579             for i in xrange(0, len(indices), 3):
580                 # reverse triangle
581                 io.indices.append(indices[i+2])
582                 io.indices.append(indices[i+1])
583                 io.indices.append(indices[i])
584
585                 #io.indices.append(indices[i])
586                 #io.indices.append(indices[i+1])
587                 #io.indices.append(indices[i+2])
588
589         # bones
590         for b in builder.bones:
591             bone=io.addBone()
592
593             unicode=englishmap.getUnicodeBoneName(b.name)
594             if unicode:
595                 cp932=unicode.encode('cp932')
596             else:
597                 cp932=b.name
598             bone_name="%s\n" % cp932
599             assert(len(bone_name)<20)
600             bone.name=bone_name
601
602             bone_english_name="%s\n" % b.name
603             assert(len(bone_english_name)<20)
604             bone.english_name=bone_english_name
605
606             bone.type=b.type
607             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
608             bone.tail_index=b.tail_index if b.tail_index!=None else 0
609             # ToDo
610             bone.ik_index=0xFFFF
611             # convert right-handed z-up to left-handed y-up
612             bone.pos.x=b.pos[0]
613             bone.pos.y=b.pos[2]
614             bone.pos.z=b.pos[1]
615
616         # IK
617         for ik in builder.ik_list:
618             solver=io.addIK()
619             solver.index=builder.getIndex(ik.target)
620             solver.target=builder.getIndex(ik.effector)
621             solver.length=ik.length
622             b=builder.bones[ik.effector.parent_index]
623             for i in xrange(solver.length):
624                 solver.children.append(builder.getIndex(b))
625                 b=builder.bones[b.parent_index]
626             solver.iterations=ik.iterations
627             solver.weight=ik.weight
628
629         # 表情
630         for i, m in enumerate(self.oneSkinMesh.morphList):
631             # morph
632             morph=io.addMorph()
633
634             unicode=englishmap.getUnicodeSkinName(m.name)
635             if unicode:
636                 cp932=unicode.encode('cp932')
637             else:
638                 cp932=m.name
639             morph.name="%s\n" % cp932
640
641             morph.english_name="%s\n" % m.name
642             morph.type=m.type
643             for index, offset in zip(m.indices, m.offsets):
644                 # convert right-handed z-up to left-handed y-up
645                 morph.append(index, offset[0], offset[2], offset[1])
646             morph.vertex_count=len(m.indices)
647
648             # 表情枠
649             if i>0:
650                 io.face_list.append(i)
651
652         # ボーン表示枠
653         boneDisplayName=io.addBoneDisplayName()
654         boneDisplayName.name="bones\n"
655         boneDisplayName.english_name="bones\n"
656         displayIndex=1
657         for i, b in enumerate(builder.bones):
658             if b.type in [6, 7]:
659                 io.addBoneDisplay(i, displayIndex)
660
661         # English
662         io.english_name="blender export model"
663         io.english_coment="blender export"
664
665         for i in range(10):
666             io.getToonTexture(i).name="toon%02d.bmp" % i
667
668         # 書き込み
669         return io.write(path.encode(FS_ENCODING))
670
671
672 def export_pmd(filename):
673     filename=filename.decode(INTERNAL_ENCODING)
674
675     Blender.Window.WaitCursor(1) 
676     t = Blender.sys.time() 
677
678     if not filename.lower().endswith(EXTENSION):
679         filename += EXTENSION
680     print "pmd exporter: %s" % filename
681
682     exporter=PmdExporter()
683
684     # 情報収集
685     exporter.setup(Blender.Scene.GetCurrent())
686
687     # 出力
688     exporter.write(filename)
689
690     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
691     Blender.Redraw()
692     Blender.Window.WaitCursor(0) 
693  
694
695 Blender.Window.FileSelector(
696         export_pmd,
697         'Export Metasequoia PMD',
698         Blender.sys.makename(ext=EXTENSION))
699