OSDN Git Service

remove blender25
[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         if name not in o.vertex_groups:
246             o.vertex_groups.new(name)
247         o.vertex_groups[name].add([index], weight, 'ADD')
248
249     @staticmethod
250     def createBoneGroup(o, name, color_set='DEFAULT'):
251         # create group
252         object.activate(o)
253         enterPoseMode()
254         bpy.ops.pose.group_add()
255         # set name
256         pose=object.getPose(o)
257         g=pose.bone_groups.active
258         g.name=name
259         g.color_set=color_set
260         return g
261
262     @staticmethod
263     def boneGroups(o):
264         return object.getPose(o).bone_groups
265
266
267 class modifier:
268     @staticmethod
269     def addMirror(mesh_object):
270         return mesh_object.modifiers.new("Modifier", "MIRROR")
271
272     @staticmethod
273     def addArmature(mesh_object, armature_object):
274         mod=mesh_object.modifiers.new("Modifier", "ARMATURE")
275         mod.object = armature_object
276         mod.use_bone_envelopes=False
277
278     @staticmethod
279     def hasType(mesh_object, type_name):
280         for mod in mesh_object.modifiers:
281                 if mod.type==type_name.upper():
282                     return True
283
284     @staticmethod
285     def isType(m, type_name):
286         return m.type==type_name.upper()
287
288     @staticmethod
289     def getArmatureObject(m):
290         return m.object
291
292
293 class shapekey:
294     @staticmethod
295     def assign(shapeKey, index, pos):
296         shapeKey.data[index].co=pos
297
298     @staticmethod
299     def getByIndex(b, index):
300         return b.data[index].co
301
302     @staticmethod
303     def get(b):
304         for k in b.data:
305             yield k.co
306
307
308 class texture:
309     @staticmethod
310     def create(path):
311         texture=bpy.data.textures.new(os.path.basename(path), 'IMAGE')
312         texture.use_mipmap=True
313         texture.use_interpolation=True
314         texture.use_alpha=True
315         try:
316             image=bpy.data.images.load(path)
317         except RuntimeError:
318             image=bpy.data.images.new('Image', width=16, height=16)
319         texture.image=image
320         return texture, image
321
322     @staticmethod
323     def getPath(t):
324         if  t.type=="IMAGE":
325             image=t.image
326             if image:
327                 return image.filepath
328
329
330 class material:
331     @staticmethod
332     def create(name):
333         return bpy.data.materials.new(name)
334
335     @staticmethod
336     def get(material_name):
337         return bpy.data.materials[material_name]
338
339     @staticmethod
340     def addTexture(material, texture, enable=True):
341         # search free slot
342         index=None
343         for i, slot in enumerate(material.texture_slots):
344             if not slot:
345                 index=i
346                 break
347         if index==None:
348             return
349         #
350         #material.add_texture(texture, "UV", "COLOR")
351         #slot=material.texture_slots.add()
352         slot=material.texture_slots.create(index)
353         slot.texture=texture
354         slot.texture_coords='UV'
355         slot.blend_type='MULTIPLY'
356         slot.use_map_alpha=True
357         slot.use=enable
358         return index
359
360     @staticmethod
361     def getTexture(m, index):
362         return m.texture_slots[index].texture
363
364     @staticmethod
365     def hasTexture(m):
366         return m.texture_slots[0]
367
368     @staticmethod
369     def setUseTexture(m, index, enable):
370         m.use_textures[index]=enable
371
372     @staticmethod
373     def eachTexturePath(m):
374         for slot in m.texture_slots:
375             if slot and slot.texture:
376                 texture=slot.texture
377                 if  texture.type=="IMAGE":
378                     image=texture.image
379                     if not image:
380                         continue
381                     yield image.filepath
382
383     @staticmethod
384     def eachEnalbeTexturePath(m):
385         for i, slot in enumerate(m.texture_slots):
386             if m.use_textures[i] and slot and slot.texture:
387                 texture=slot.texture
388                 if  texture.type=="IMAGE":
389                     image=texture.image
390                     if not image:
391                         continue
392                     yield image.filepath
393
394
395 class mesh:
396     @staticmethod
397     def create(name):
398         global SCENE
399         mesh=bpy.data.meshes.new("Mesh")
400         mesh_object= bpy.data.objects.new(name, mesh)
401         SCENE.objects.link(mesh_object)
402         return mesh, mesh_object
403
404     @staticmethod
405     def addGeometry(mesh, vertices, faces):
406         mesh.from_pydata(vertices, [], faces)
407         """
408         mesh.add_geometry(len(vertices), 0, len(faces))
409         # add vertex
410         unpackedVertices=[]
411         for v in vertices:
412             unpackedVertices.extend(v)
413         mesh.vertices.foreach_set("co", unpackedVertices)
414         # add face
415         unpackedFaces = []
416         for face in faces:
417             if len(face) == 4:
418                 if face[3] == 0:
419                     # rotate indices if the 4th is 0
420                     face = [face[3], face[0], face[1], face[2]]
421             elif len(face) == 3:
422                 if face[2] == 0:
423                     # rotate indices if the 3rd is 0
424                     face = [face[2], face[0], face[1], 0]
425                 else:
426                     face.append(0)
427             unpackedFaces.extend(face)
428         mesh.faces.foreach_set("verts_raw", unpackedFaces)
429         """
430         assert(len(vertices)==len(mesh.vertices))
431         assert(len(faces)==len(mesh.faces))
432
433     @staticmethod
434     def hasUV(mesh):
435         return len(mesh.uv_textures)>0
436
437     @staticmethod
438     def useVertexUV(mesh):
439         pass
440
441     @staticmethod
442     def addUV(mesh):
443         mesh.uv_textures.new()
444
445     @staticmethod
446     def hasFaceUV(mesh, i, face):
447         active_uv_texture=None
448         for t in mesh.uv_textures:
449             if t.active:
450                 active_uv_texture=t
451                 break
452         return active_uv_texture and active_uv_texture.data[i]
453
454     @staticmethod
455     def getFaceUV(mesh, i, faces, count=3):
456         active_uv_texture=None
457         for t in mesh.uv_textures:
458             if t.active:
459                 active_uv_texture=t
460                 break
461         if active_uv_texture and active_uv_texture.data[i]:
462             uvFace=active_uv_texture.data[i]
463             if count==3:
464                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3)
465             elif count==4:
466                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4)
467             else:
468                 print(count)
469                 assert(False)
470         else:
471             return ((0, 0), (0, 0), (0, 0), (0, 0))
472
473     @staticmethod
474     def setFaceUV(m, i, face, uv_array, image):
475         uv_face=m.uv_textures[0].data[i]
476         uv_face.uv=uv_array
477         if image:
478             uv_face.image=image
479             #uv_face.use_image=True
480
481     @staticmethod
482     def vertsDelete(m, remove_vertices):
483         enterEditMode()
484         bpy.ops.mesh.select_all(action='DESELECT')
485         enterObjectMode()
486
487         for i in remove_vertices:
488             m.vertices[i].select=True
489
490         enterEditMode()
491         bpy.ops.mesh.delete(type='VERT')
492         enterObjectMode()
493
494     @staticmethod
495     def setSmooth(m, smoothing):
496         m.auto_smooth_angle=int(smoothing)
497         m.use_auto_smooth=True
498
499     @staticmethod
500     def recalcNormals(mesh_object):
501         bpy.ops.object.select_all(action='DESELECT')
502         object.activate(mesh_object)
503         enterEditMode()
504         bpy.ops.mesh.normals_make_consistent()
505         enterObjectMode()
506
507     @staticmethod
508     def flipNormals(m):
509         m.flipNormals()
510
511     @staticmethod
512     def addMaterial(m, material):
513         m.materials.append(material)
514
515     @staticmethod
516     def getMaterial(m, index):
517         return m.materials[index]
518
519
520 class vertex:
521     @staticmethod
522     def setNormal(v, normal):
523         v.normal=mathutils.Vector(normal)
524
525     @staticmethod
526     def getNormal(v):
527         return v.normal
528
529     @staticmethod
530     def setUv(v, uv):
531         # sticky ?
532         pass
533
534
535 class face:
536     @staticmethod
537     def getVertexCount(face):
538         return len(face.vertices)
539
540     @staticmethod
541     def getVertices(face):
542         return face.vertices[:]
543
544     @staticmethod
545     def getIndices(face, count=3):
546         if count==3:
547             return [face.vertices[0], face.vertices[1], face.vertices[2]]
548         elif count==4:
549             return [face.vertices[0], face.vertices[1], face.vertices[2], face.vertices[3]]
550         else:
551             assert(False)
552
553     @staticmethod
554     def setMaterial(face, material_index):
555         face.material_index=material_index
556
557     @staticmethod
558     def getMaterialIndex(face):
559         return face.material_index
560
561     @staticmethod
562     def setNormal(face, normal):
563         face.normal=normal
564
565     @staticmethod
566     def getNormal(face):
567         return face.normal
568
569     @staticmethod
570     def setSmooth(face, isSmooth):
571         face.use_smooth=True if isSmooth else False
572
573
574 class armature:
575     @staticmethod
576     def create():
577         global SCENE
578         armature = bpy.data.armatures.new('Armature')
579         armature_object=bpy.data.objects.new('Armature', armature)
580         SCENE.objects.link(armature_object)
581
582         armature_object.show_x_ray=True
583         armature.show_names=True
584         #armature.draw_type='OCTAHEDRAL'
585         armature.draw_type='STICK'
586         armature.use_deform_envelopes=False
587         armature.use_deform_vertex_groups=True
588         armature.use_mirror_x=True
589
590         return armature, armature_object
591
592     @staticmethod
593     def makeEditable(armature_object):
594         global SCENE
595         # select only armature object and set edit mode
596         SCENE.objects.active=armature_object
597         bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
598         bpy.ops.object.mode_set(mode='EDIT', toggle=False)
599
600     @staticmethod
601     def createIkConstraint(armature_object, p_bone, effector_name, 
602             chain, weight, iterations):
603         constraint = p_bone.constraints.new('IK')
604         constraint.chain_count=len(chain)
605         constraint.target=armature_object
606         constraint.subtarget=effector_name
607         constraint.use_tail=False
608         # ToDo
609         # not used. place folder when export.
610         #constraint.weight=weight
611         #constraint.iterations=iterations * 10
612         return constraint
613
614     @staticmethod
615     def createBone(armature, name):
616         return armature.edit_bones.new(name)
617
618     @staticmethod
619     def update(armature):
620         pass
621
622
623 class bone:
624     @staticmethod
625     def setConnected(bone):
626         bone.use_connect=True
627
628     @staticmethod
629     def isConnected(bone):
630         return bone.use_connect
631
632     @staticmethod
633     def setLayerMask(bone, layers):
634         layer=[]
635         for i in range(32):
636             try:
637                 layer.append(True if layers[i]!=0 else False)
638             except IndexError:
639                 layer.append(False)
640         bone.layers=layer
641
642     @staticmethod
643     def getHeadLocal(b):
644         return b.head_local[0:3]
645
646     @staticmethod
647     def getTailLocal(b):
648         return b.tail_local[0:3]
649
650
651 class constraint:
652     @staticmethod
653     def ikChainLen(c):
654         return c.chain_count
655
656     @staticmethod
657     def ikTarget(c):
658         return c.subtarget
659
660     @staticmethod
661     def ikItration(c):
662         return c.iterations
663
664     @staticmethod
665     def ikRotationWeight(c):
666         return c.weight
667
668     @staticmethod
669     def isIKSolver(c):
670         return c.type=='IK'
671
672 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
673 MMD_MB_NAME='mb_name'
674 MMD_MB_COMMENT='mb_comment'
675 MMD_COMMENT='comment'
676 BASE_SHAPE_NAME='Basis'
677 RIGID_NAME='rigid_name'
678 RIGID_SHAPE_TYPE='rigid_shape_type'
679 RIGID_PROCESS_TYPE='rigid_process_type'
680 RIGID_BONE_NAME='rigid_bone_name'
681 RIGID_GROUP='ribid_group'
682 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
683 RIGID_WEIGHT='rigid_weight'
684 RIGID_LINEAR_DAMPING='rigid_linear_damping'
685 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
686 RIGID_RESTITUTION='rigid_restitution'
687 RIGID_FRICTION='rigid_friction'
688 CONSTRAINT_NAME='const_name'
689 CONSTRAINT_A='const_a'
690 CONSTRAINT_B='const_b'
691 CONSTRAINT_POS_MIN='const_pos_min'
692 CONSTRAINT_POS_MAX='const_pos_max'
693 CONSTRAINT_ROT_MIN='const_rot_min'
694 CONSTRAINT_ROT_MAX='const_rot_max'
695 CONSTRAINT_SPRING_POS='const_spring_pos'
696 CONSTRAINT_SPRING_ROT='const_spring_rot'
697 TOON_TEXTURE_OBJECT='ToonTextures'
698