OSDN Git Service

4d5afdeb5f7d5a8d1508daaeb6f9e278d363a63a
[meshio/pymeshio.git] / blender26-meshio / bl.py
1 # coding: utf-8
2 import os
3 import sys
4 import time
5 import functools
6
7 try:
8     import bpy
9     import mathutils
10 except:
11     pass
12
13 FS_ENCODING=sys.getfilesystemencoding()
14 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
15     INTERNAL_ENCODING='utf-8'
16 else:
17     INTERNAL_ENCODING=FS_ENCODING
18
19 def register():
20     pass
21
22 def unregister():
23     pass
24
25 SCENE=None
26 def initialize(name, scene):
27     global SCENE
28     SCENE=scene
29     progress_start(name)
30
31 def finalize():
32     scene.update(SCENE)
33     progress_finish()
34
35 def message(msg):
36     print(msg)
37
38 def enterEditMode():
39     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
40
41 def enterObjectMode():
42     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
43
44 def enterPoseMode():
45     bpy.ops.object.mode_set(mode='POSE', toggle=False)
46
47 def createVector(x, y, z):
48     return mathutils.Vector([x, y, z])
49
50
51 class Writer(object):
52     '''
53     io wrapper
54     '''
55     def __init__(self, path, encoding):
56         self.io=open(path, "wb")
57         self.encoding=encoding
58
59     def write(self, s):
60         self.io.write(s.encode(self.encoding))
61
62     def flush(self):
63         self.io.flush()
64
65     def close(self):
66         self.io.close()
67
68
69 progressBar=None
70 class ProgressBar(object):
71     '''
72     progress bar wrapper
73     '''
74     def __init__(self, base):
75         print("#### %s ####" % base)
76         self.base=base
77         self.start=time.time() 
78         self.set('<start>', 0)
79
80     def advance(self, message, progress):
81         self.progress+=float(progress)
82         self._print(message)
83
84     def set(self, message, progress):
85         self.progress=float(progress)
86         self._print(message)
87
88     def _print(self, message):
89         print(message)
90         message="%s: %s" % (self.base, message)
91         #Blender.Window.DrawProgressBar(self.progress, message)
92
93     def finish(self):
94         self.progress=1.0
95         message='finished in %.2f sec' % (time.time()-self.start)
96         self.set(message, 1.0)
97
98 def progress_start(base):
99     global progressBar
100     print("#### progressBar ####")
101     progressBar=ProgressBar(base)
102
103 def progress_finish():
104     global progressBar
105     progressBar.finish()
106
107 def progress_print(message, progress=0.05):
108     global progressBar
109     progressBar.advance(message, progress)
110
111 def progress_set(message, progress):
112     global progressBar
113     progressBar.set(message, progress)
114
115
116 class scene:
117     @staticmethod
118     def get():
119         global SCENE
120         return SCENE
121
122     def update(scene):
123         scene.update()
124
125
126 class object:
127     @staticmethod
128     def createEmpty(name):
129         global SCENE
130         empty=bpy.data.objects.new(name, None)
131         SCENE.objects.link(empty)
132         return empty
133
134     @staticmethod
135     def each():
136         for o in SCENE.objects:
137             yield o
138
139     @staticmethod
140     def makeParent(parent, child):
141         child.parent=parent
142
143     @staticmethod
144     def duplicate(o):
145         global SCENE
146         bpy.ops.object.select_all(action='DESELECT')
147         o.select=True
148         SCENE.objects.active=o
149         bpy.ops.object.duplicate()
150         dumy=SCENE.objects.active
151         #bpy.ops.object.rotation_apply()
152         #bpy.ops.object.scale_apply()
153         #bpy.ops.object.location_apply()
154         return dumy.data, dumy
155
156     @staticmethod
157     def delete(o):
158         global SCENE
159         SCENE.objects.unlink(o)
160
161     @staticmethod
162     def getData(o):
163         return o.data
164
165     @staticmethod
166     def select(o):
167         o.select=True
168
169     @staticmethod
170     def activate(o):
171         global SCENE
172         o.select=True 
173         SCENE.objects.active=o
174
175     @staticmethod
176     def getActive():
177         global SCENE 
178         return SCENE.objects.active
179
180     @staticmethod
181     def deselectAll():
182         bpy.ops.object.select_all(action='DESELECT')
183
184     @staticmethod
185     def setLayerMask(object, layers):
186         layer=[]
187         for i in range(20):
188             try:
189                 layer.append(True if layers[i]!=0 else False)
190             except IndexError:
191                 layer.append(False)
192         object.layers=layer
193
194     @staticmethod
195     def isVisible(o):
196         return False if o.hide else True
197
198     @staticmethod
199     def getShapeKeys(o):
200         return o.data.shape_keys.key_blocks
201
202     @staticmethod
203     def addShapeKey(o, name):
204         try:
205             return o.shape_key_add(name)
206         except:
207             return o.add_shape_key(name)
208
209     @staticmethod
210     def hasShapeKey(o):
211         return o.data.shape_keys
212
213     @staticmethod
214     def pinShape(o, enable):
215         o.show_only_shape_key=enable
216
217     @staticmethod
218     def setActivateShapeKey(o, index):
219         o.active_shape_key_index=index
220
221     @staticmethod
222     def getPose(o):
223         return o.pose
224
225     @staticmethod
226     def getVertexGroup(o, name):
227         indices=[]
228         for i, v in enumerate(o.data.vertices):
229             for g in v.groups:
230                 if o.vertex_groups[g.group].name==name:
231                     indices.append(i)
232         return indices
233
234     @staticmethod
235     def getVertexGroupNames(o):
236         for g in o.vertex_groups:
237             yield g.name
238
239     @staticmethod
240     def addVertexGroup(o, name):
241         o.vertex_groups.new(name)
242
243     @staticmethod
244     def assignVertexGroup(o, name, index, weight):
245         o.vertex_groups[name].add([index], weight, 'ADD')
246
247     @staticmethod
248     def createBoneGroup(o, name, color_set='DEFAULT'):
249         # create group
250         object.activate(o)
251         enterPoseMode()
252         bpy.ops.pose.group_add()
253         # set name
254         pose=object.getPose(o)
255         g=pose.bone_groups.active
256         g.name=name
257         g.color_set=color_set
258         return g
259
260     @staticmethod
261     def boneGroups(o):
262         return object.getPose(o).bone_groups
263
264
265 class modifier:
266     @staticmethod
267     def addMirror(mesh_object):
268         return mesh_object.modifiers.new("Modifier", "MIRROR")
269
270     @staticmethod
271     def addArmature(mesh_object, armature_object):
272         mod=mesh_object.modifiers.new("Modifier", "ARMATURE")
273         mod.object = armature_object
274         mod.use_bone_envelopes=False
275
276     @staticmethod
277     def hasType(mesh_object, type_name):
278         for mod in mesh_object.modifiers:
279                 if mod.type==type_name.upper():
280                     return True
281
282     @staticmethod
283     def isType(m, type_name):
284         return m.type==type_name.upper()
285
286     @staticmethod
287     def getArmatureObject(m):
288         return m.object
289
290
291 class shapekey:
292     @staticmethod
293     def assign(shapeKey, index, pos):
294         shapeKey.data[index].co=pos
295
296     @staticmethod
297     def getByIndex(b, index):
298         return b.data[index].co
299
300     @staticmethod
301     def get(b):
302         for k in b.data:
303             yield k.co
304
305
306 class texture:
307     @staticmethod
308     def create(path):
309         texture=bpy.data.textures.new(os.path.basename(path), 'IMAGE')
310         texture.use_mipmap=True
311         texture.use_interpolation=True
312         texture.use_alpha=True
313         try:
314             image=bpy.data.images.load(path)
315         except RuntimeError:
316             image=bpy.data.images.new('Image', width=16, height=16)
317         texture.image=image
318         return texture, image
319
320     @staticmethod
321     def getPath(t):
322         if  t.type=="IMAGE":
323             image=t.image
324             if image:
325                 return image.filepath
326
327
328 class material:
329     @staticmethod
330     def create(name):
331         return bpy.data.materials.new(name)
332
333     @staticmethod
334     def get(material_name):
335         return bpy.data.materials[material_name]
336
337     @staticmethod
338     def addTexture(material, texture, enable=True):
339         # search free slot
340         index=None
341         for i, slot in enumerate(material.texture_slots):
342             if not slot:
343                 index=i
344                 break
345         if index==None:
346             return
347         #
348         #material.add_texture(texture, "UV", "COLOR")
349         #slot=material.texture_slots.add()
350         slot=material.texture_slots.create(index)
351         slot.texture=texture
352         slot.texture_coords='UV'
353         slot.blend_type='MULTIPLY'
354         slot.use_map_alpha=True
355         slot.use=enable
356         return index
357
358     @staticmethod
359     def getTexture(m, index):
360         return m.texture_slots[index].texture
361
362     @staticmethod
363     def hasTexture(m):
364         return m.texture_slots[0]
365
366     @staticmethod
367     def setUseTexture(m, index, enable):
368         m.use_textures[index]=enable
369
370     @staticmethod
371     def eachTexturePath(m):
372         for slot in m.texture_slots:
373             if slot and slot.texture:
374                 texture=slot.texture
375                 if  texture.type=="IMAGE":
376                     image=texture.image
377                     if not image:
378                         continue
379                     yield image.filepath
380
381     @staticmethod
382     def eachEnalbeTexturePath(m):
383         for i, slot in enumerate(m.texture_slots):
384             if m.use_textures[i] and slot and slot.texture:
385                 texture=slot.texture
386                 if  texture.type=="IMAGE":
387                     image=texture.image
388                     if not image:
389                         continue
390                     yield image.filepath
391
392
393 class mesh:
394     @staticmethod
395     def create(name):
396         global SCENE
397         mesh=bpy.data.meshes.new("Mesh")
398         mesh_object= bpy.data.objects.new(name, mesh)
399         SCENE.objects.link(mesh_object)
400         return mesh, mesh_object
401
402     @staticmethod
403     def addGeometry(mesh, vertices, faces):
404         mesh.from_pydata(vertices, [], faces)
405         """
406         mesh.add_geometry(len(vertices), 0, len(faces))
407         # add vertex
408         unpackedVertices=[]
409         for v in vertices:
410             unpackedVertices.extend(v)
411         mesh.vertices.foreach_set("co", unpackedVertices)
412         # add face
413         unpackedFaces = []
414         for face in faces:
415             if len(face) == 4:
416                 if face[3] == 0:
417                     # rotate indices if the 4th is 0
418                     face = [face[3], face[0], face[1], face[2]]
419             elif len(face) == 3:
420                 if face[2] == 0:
421                     # rotate indices if the 3rd is 0
422                     face = [face[2], face[0], face[1], 0]
423                 else:
424                     face.append(0)
425             unpackedFaces.extend(face)
426         mesh.faces.foreach_set("verts_raw", unpackedFaces)
427         """
428         assert(len(vertices)==len(mesh.vertices))
429         assert(len(faces)==len(mesh.faces))
430
431     @staticmethod
432     def hasUV(mesh):
433         return len(mesh.uv_textures)>0
434
435     @staticmethod
436     def useVertexUV(mesh):
437         pass
438
439     @staticmethod
440     def addUV(mesh):
441         mesh.uv_textures.new()
442
443     @staticmethod
444     def hasFaceUV(mesh, i, face):
445         active_uv_texture=None
446         for t in mesh.uv_textures:
447             if t.active:
448                 active_uv_texture=t
449                 break
450         return active_uv_texture and active_uv_texture.data[i]
451
452     @staticmethod
453     def getFaceUV(mesh, i, faces, count=3):
454         active_uv_texture=None
455         for t in mesh.uv_textures:
456             if t.active:
457                 active_uv_texture=t
458                 break
459         if active_uv_texture and active_uv_texture.data[i]:
460             uvFace=active_uv_texture.data[i]
461             if count==3:
462                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3)
463             elif count==4:
464                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4)
465             else:
466                 print(count)
467                 assert(False)
468         else:
469             return ((0, 0), (0, 0), (0, 0), (0, 0))
470
471     @staticmethod
472     def setFaceUV(m, i, face, uv_array, image):
473         uv_face=m.uv_textures[0].data[i]
474         uv_face.uv=uv_array
475         if image:
476             uv_face.image=image
477             #uv_face.use_image=True
478
479     @staticmethod
480     def vertsDelete(m, remove_vertices):
481         enterEditMode()
482         bpy.ops.mesh.select_all(action='DESELECT')
483         enterObjectMode()
484
485         for i in remove_vertices:
486             m.vertices[i].select=True
487
488         enterEditMode()
489         bpy.ops.mesh.delete(type='VERT')
490         enterObjectMode()
491
492     @staticmethod
493     def setSmooth(m, smoothing):
494         m.auto_smooth_angle=int(smoothing)
495         m.use_auto_smooth=True
496
497     @staticmethod
498     def recalcNormals(mesh_object):
499         bpy.ops.object.select_all(action='DESELECT')
500         object.activate(mesh_object)
501         enterEditMode()
502         bpy.ops.mesh.normals_make_consistent()
503         enterObjectMode()
504
505     @staticmethod
506     def flipNormals(m):
507         m.flipNormals()
508
509     @staticmethod
510     def addMaterial(m, material):
511         m.materials.append(material)
512
513     @staticmethod
514     def getMaterial(m, index):
515         return m.materials[index]
516
517
518 class vertex:
519     @staticmethod
520     def setNormal(v, normal):
521         v.normal=mathutils.Vector(normal)
522
523     @staticmethod
524     def getNormal(v):
525         return v.normal
526
527     @staticmethod
528     def setUv(v, uv):
529         # sticky ?
530         pass
531
532
533 class face:
534     @staticmethod
535     def getVertexCount(face):
536         return len(face.vertices)
537
538     @staticmethod
539     def getVertices(face):
540         return face.vertices[:]
541
542     @staticmethod
543     def getIndices(face, count=3):
544         if count==3:
545             return [face.vertices[0], face.vertices[1], face.vertices[2]]
546         elif count==4:
547             return [face.vertices[0], face.vertices[1], face.vertices[2], face.vertices[3]]
548         else:
549             assert(False)
550
551     @staticmethod
552     def setMaterial(face, material_index):
553         face.material_index=material_index
554
555     @staticmethod
556     def getMaterialIndex(face):
557         return face.material_index
558
559     @staticmethod
560     def setNormal(face, normal):
561         face.normal=normal
562
563     @staticmethod
564     def getNormal(face):
565         return face.normal
566
567     @staticmethod
568     def setSmooth(face, isSmooth):
569         face.use_smooth=True if isSmooth else False
570
571
572 class armature:
573     @staticmethod
574     def create():
575         global SCENE
576         armature = bpy.data.armatures.new('Armature')
577         armature_object=bpy.data.objects.new('Armature', armature)
578         SCENE.objects.link(armature_object)
579
580         armature_object.show_x_ray=True
581         armature.show_names=True
582         #armature.draw_type='OCTAHEDRAL'
583         armature.draw_type='STICK'
584         armature.use_deform_envelopes=False
585         armature.use_deform_vertex_groups=True
586         armature.use_mirror_x=True
587
588         return armature, armature_object
589
590     @staticmethod
591     def makeEditable(armature_object):
592         global SCENE
593         # select only armature object and set edit mode
594         SCENE.objects.active=armature_object
595         bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
596         bpy.ops.object.mode_set(mode='EDIT', toggle=False)
597
598     @staticmethod
599     def createIkConstraint(armature_object, p_bone, effector_name, 
600             chain, weight, iterations):
601         constraint = p_bone.constraints.new('IK')
602         constraint.chain_count=len(chain)
603         constraint.target=armature_object
604         constraint.subtarget=effector_name
605         constraint.use_tail=False
606         # ToDo
607         # not used. place folder when export.
608         #constraint.weight=weight
609         #constraint.iterations=iterations * 10
610         return constraint
611
612     @staticmethod
613     def createBone(armature, name):
614         return armature.edit_bones.new(name)
615
616     @staticmethod
617     def update(armature):
618         pass
619
620
621 class bone:
622     @staticmethod
623     def setConnected(bone):
624         bone.use_connect=True
625
626     @staticmethod
627     def isConnected(bone):
628         return bone.use_connect
629
630     @staticmethod
631     def setLayerMask(bone, layers):
632         layer=[]
633         for i in range(32):
634             try:
635                 layer.append(True if layers[i]!=0 else False)
636             except IndexError:
637                 layer.append(False)
638         bone.layers=layer
639
640     @staticmethod
641     def getHeadLocal(b):
642         return b.head_local[0:3]
643
644     @staticmethod
645     def getTailLocal(b):
646         return b.tail_local[0:3]
647
648
649 class constraint:
650     @staticmethod
651     def ikChainLen(c):
652         return c.chain_count
653
654     @staticmethod
655     def ikTarget(c):
656         return c.subtarget
657
658     @staticmethod
659     def ikItration(c):
660         return c.iterations
661
662     @staticmethod
663     def ikRotationWeight(c):
664         return c.weight
665
666     @staticmethod
667     def isIKSolver(c):
668         return c.type=='IK'
669
670 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
671 MMD_MB_NAME='mb_name'
672 MMD_MB_COMMENT='mb_comment'
673 MMD_COMMENT='comment'
674 BASE_SHAPE_NAME='Basis'
675 RIGID_NAME='rigid_name'
676 RIGID_SHAPE_TYPE='rigid_shape_type'
677 RIGID_PROCESS_TYPE='rigid_process_type'
678 RIGID_BONE_NAME='rigid_bone_name'
679 RIGID_GROUP='ribid_group'
680 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
681 RIGID_WEIGHT='rigid_weight'
682 RIGID_LINEAR_DAMPING='rigid_linear_damping'
683 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
684 RIGID_RESTITUTION='rigid_restitution'
685 RIGID_FRICTION='rigid_friction'
686 CONSTRAINT_NAME='const_name'
687 CONSTRAINT_A='const_a'
688 CONSTRAINT_B='const_b'
689 CONSTRAINT_POS_MIN='const_pos_min'
690 CONSTRAINT_POS_MAX='const_pos_max'
691 CONSTRAINT_ROT_MIN='const_rot_min'
692 CONSTRAINT_ROT_MAX='const_rot_max'
693 CONSTRAINT_SPRING_POS='const_spring_pos'
694 CONSTRAINT_SPRING_ROT='const_spring_rot'
695 TOON_TEXTURE_OBJECT='ToonTextures'
696