OSDN Git Service

refactoring add geometry.
[meshio/meshio.git] / swig / blender / bl25.py
1 # coding: utf-8
2 import bpy
3 import mathutils
4
5 import os
6 import sys
7 import time
8 import functools
9
10\e$B%U%!%$%k%7%9%F%`$NJ8;z%3!<%I\e(B
11\e$B2~B$HG$H$N6&MQ$N$?$a\e(B
12 FS_ENCODING=sys.getfilesystemencoding()
13 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
14     INTERNAL_ENCODING='utf-8'
15 else:
16     INTERNAL_ENCODING=FS_ENCODING
17
18
19 ###############################################################################
20 # ProgressBar
21 ###############################################################################
22 class ProgressBar(object):
23     def __init__(self, base):
24         print("#### %s ####" % base)
25         self.base=base
26         self.start=time.time() 
27         self.set('<start>', 0)
28
29     def advance(self, message, progress):
30         self.progress+=float(progress)
31         self._print(message)
32
33     def set(self, message, progress):
34         self.progress=float(progress)
35         self._print(message)
36
37     def _print(self, message):
38         print(message)
39         message="%s: %s" % (self.base, message)
40         #Blender.Window.DrawProgressBar(self.progress, message)
41
42     def finish(self):
43         self.progress=1.0
44         message='finished in %.2f sec' % (time.time()-self.start)
45         self.set(message, 1.0)
46
47 def progress_start(base):
48     global progressBar
49     progressBar=ProgressBar(base)
50
51 def progress_finish():
52     global progressBar
53     progressBar.finish()
54
55 def progress_print(message, progress=0.05):
56     global progressBar
57     progressBar.advance(message, progress)
58
59 def progress_set(message, progress):
60     global progressBar
61     progressBar.set(message, progress)
62
63
64 ###############################################################################
65 class Writer(object):
66     def __init__(self, path, encoding):
67         self.io=open(path, "wb")
68         self.encoding=encoding
69
70     def write(self, s):
71         self.io.write(s.encode(self.encoding))
72
73     def flush(self):
74         self.io.flush()
75
76     def close(self):
77         self.io.close()
78
79 ###############################################################################
80 def createEmptyObject(scene, name):
81     empty=bpy.data.objects.new(name, None)
82     scene.objects.link(empty)
83     return empty
84
85 def createMaterial(name):
86     material = bpy.data.materials.new(name)
87     return material
88
89 def createMqoMaterial(m):
90     material = bpy.data.materials.new(m.getName())
91     material.diffuse_color=[m.color.r, m.color.g, m.color.b]
92     material.alpha=m.color.a
93     material.diffuse_intensity=m.diffuse
94     return material
95
96 def createPmdMaterial(m):
97     material = bpy.data.materials.new("Material")
98     material.diffuse_shader='FRESNEL'
99     material.specular_shader='TOON'
100     material.diffuse_color=([m.diffuse.r, m.diffuse.g, m.diffuse.b])
101     material.alpha=m.diffuse.a
102     material.specular_hardness=int(m.shinness)
103     material.specular_color=([m.specular.r, m.specular.g, m.specular.b])
104     material.mirror_color=([m.ambient.r, m.ambient.g, m.ambient.b])
105     material.subsurface_scattering.enabled=True if m.flag==1 else False
106     return material
107
108 def createTexture(path):
109     texture=bpy.data.textures.new(os.path.basename(path))
110     texture.type='IMAGE'
111     texture=texture.recast_type()
112     image=bpy.data.images.load(path)
113     texture.image=image
114     texture.mipmap = True
115     texture.interpolation = True
116     texture.use_alpha = True
117     return texture, image
118
119
120 def materialAddTexture(material, texture):
121     #material.add_texture(texture, "UV", {"COLOR", "ALPHA"})
122     material.add_texture(texture, "UV", "COLOR")
123
124
125 def meshAddMaterial(mesh, material):
126     mesh.add_material(material)
127
128
129 def createMesh(scene, name):
130     mesh=bpy.data.meshes.new("Mesh")
131     mesh_object= bpy.data.objects.new(name, mesh)
132     scene.objects.link(mesh_object)
133     return mesh, mesh_object
134
135
136 def objectMakeParent(parent, child):
137     child.parent=parent
138
139 def objectAddMirrorModifier(mesh_object):
140     return mesh_object.modifiers.new("Modifier", "MIRROR")
141
142 def meshAddGeometry(mesh, vertices, faces):
143     mesh.from_pydata(vertices, [], faces)
144     """
145     mesh.add_geometry(len(vertices), 0, len(faces))
146     # add vertex
147     unpackedVertices=[]
148     for v in vertices:
149         unpackedVertices.extend(v)
150     mesh.verts.foreach_set("co", unpackedVertices)
151     # add face
152     unpackedFaces = []
153     for face in faces:
154         if len(face) == 4:
155             if face[3] == 0:
156                 # rotate indices if the 4th is 0
157                 face = [face[3], face[0], face[1], face[2]]
158         elif len(face) == 3:
159             if face[2] == 0:
160                 # rotate indices if the 3rd is 0
161                 face = [face[2], face[0], face[1], 0]
162             else:
163                 face.append(0)
164         unpackedFaces.extend(face)
165     mesh.faces.foreach_set("verts_raw", unpackedFaces)
166     """
167     assert(len(vertices)==len(mesh.verts))
168     assert(len(faces)==len(mesh.faces))
169
170 def meshSetFaceUv(mesh, i, face, uv_array, image):
171     uv_face=mesh.uv_textures[0].data[i]
172     uv_face.uv=uv_array
173     if image:
174         uv_face.image=image
175         uv_face.tex=True
176
177 def faceSetMaterial(face, material_index):
178     face.material_index=material_index
179
180 def faceSetSmooth(face, isSmooth):
181     face.smooth=True if isSmooth else False
182
183 def getTexture(m, dirname):
184     tex=""
185     aplane=""
186     # texture
187     for slot in m.texture_slots:
188         if slot and slot.texture:
189             texture=slot.texture
190             if  texture.type=="IMAGE":
191                 image=texture.image
192                 if not image:
193                     continue
194                 imagePath=image.filename
195                 if len(dirname)>0 and imagePath.startswith(dirname):
196                     # \e$BAjBP%Q%9$KJQ49$9$k\e(B
197                     imagePath=imagePath[len(dirname)+1:len(imagePath)]
198                 #imagePath=Blender.sys.expandpath(
199                 #        imagePath).replace("\\", '/')
200                 if slot.map_colordiff:
201                     tex=" tex(\"%s\")" % imagePath
202                 elif slot.map_alpha:
203                     aplane=" aplane(\"%s\")" % imagePath
204     return tex, aplane
205
206 def objectDuplicate(scene, obj):
207     bpy.ops.object.select_all(action='DESELECT')
208     obj.selected=True
209     scene.objects.active=obj
210     bpy.ops.object.duplicate()
211     dumy=scene.objects.active
212     bpy.ops.object.rotation_apply()
213     bpy.ops.object.scale_apply()
214     bpy.ops.object.location_apply()
215     return dumy.data, dumy
216
217 def objectDelete(scene, obj):
218     scene.objects.unlink(obj)
219
220 def faceVertexCount(face):
221     return len(face.verts)
222
223 def faceVertices(face):
224     return face.verts[:]
225
226 def meshHasUV(mesh):
227     return mesh.active_uv_texture
228
229 def faceHasUV(mesh, i, face):
230     return mesh.active_uv_texture.data[i]
231
232 def faceGetUV(mesh, i, faces, count):
233     uvFace=mesh.active_uv_texture.data[i]
234     if count==3:
235         return (uvFace.uv1, uvFace.uv2, uvFace.uv3)
236     elif count==4:
237         return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4)
238     else:
239         print(count)
240         assert(False)
241
242 def materialToMqo(m):
243     return "\"%s\" shader(3) col(%f %f %f %f)" % (
244             m.name, 
245             m.diffuse_color[0], m.diffuse_color[1], m.diffuse_color[2], 
246             m.alpha)
247
248 def faceMaterialIndex(face):
249     return face.material_index
250
251 def objectGetData(o):
252     return o.data
253
254 def objectAddArmatureModifier(o, armature_object):
255     mod=o.modifiers.new("Modifier", "ARMATURE")
256     mod.object = armature_object
257     mod.use_bone_envelopes=False
258
259 def objectSelect(o):
260     o.selected=True
261
262 def objectGetPose(o):
263     return o.pose
264
265 def poseBoneLimit(n, b):
266     if n.endswith("_t"):
267         return
268     if n.startswith("knee_"):
269         b.ik_dof_y=False
270         b.ik_dof_z=False
271         b.ik_dof_x=True
272         b.ik_limit_x=True
273         b.ik_min_x=0
274         b.ik_max_x=180
275     elif n.startswith("ankle_"):
276         #b.ik_dof_y=False
277         pass
278
279 def enterEditMode():
280     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
281
282 def exitEditMode():
283     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
284
285 def objectDeselectAll():
286     bpy.ops.object.select_all(action='DESELECT')
287
288 def objectActivate(scene, o):
289     o.selected=True 
290     scene.objects.active=o
291
292 def objectGetActive(scene):
293     return scene.objects.active
294
295 def meshAddVertexGroup(meshObject, name):
296     meshObject.add_vertex_group(name)
297
298 def vertexSetNormal(mvert, normal):
299     mvert.normal=mathutils.Vector(normal)
300
301 def faceSetNormal(face, normal):
302     face.normal=normal
303
304 def meshUseVertexUv(mesh):
305     pass
306
307 def vertexSetUv(mvert, uv):
308     pass
309
310 def meshAssignVertexGroup(meshObject, name, index, weight):
311     meshObject.add_vertex_to_group(index, 
312                 meshObject.vertex_groups[name], weight, 'ADD')
313
314 def meshAddUV(mesh):
315     mesh.add_uv_texture()
316
317 def meshVertsDelete(mesh, remove_vertices):
318     enterEditMode()
319     bpy.ops.mesh.select_all(action='DESELECT')
320     exitEditMode()
321
322     for i in remove_vertices:
323         mesh.verts[i].selected=True
324
325     enterEditMode()
326     bpy.ops.mesh.delete(type='VERT')
327     exitEditMode()
328
329 def createArmature(scene):
330     armature = bpy.data.armatures.new('Armature')
331     armature_object=bpy.data.objects.new('Armature', armature)
332     scene.objects.link(armature_object)
333
334     armature_object.x_ray=True
335     armature.draw_names=True
336     armature.drawtype='OCTAHEDRAL'
337     armature.deform_envelope=False
338     armature.deform_vertexgroups=True
339     armature.x_axis_mirror=True
340
341     return armature, armature_object
342
343 def armatureMakeEditable(scene, armature_object):
344     # select only armature object and set edit mode
345     scene.objects.active=armature_object
346     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
347     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
348
349 def createIkConstraint(armature_object, p_bone, effector_name, ik):
350     constraint = p_bone.constraints.new('IK')
351     constraint.chain_length=len(ik.children)
352     constraint.target=armature_object
353     constraint.subtarget=effector_name
354     constraint.use_tail=False
355     # not used. place folder when export.
356     constraint.weight=ik.weight
357     constraint.iterations=ik.iterations * 10
358     return constraint
359
360 def createArmatureBone(armature, name):
361     return armature.edit_bones.new(name)
362
363 def boneSetConnected(bone):
364     bone.connected=True
365
366 def createVector(x, y, z):
367     return mathutils.Vector([x, y, z])
368
369 def armatureUpdate(armature):
370     pass
371
372 def boneLayerMask(bone, layers):
373     layer=[]
374     for i in range(32):
375         try:
376             layer.append(True if layers[i]!=0 else False)
377         except IndexError:
378             layer.append(False)
379     bone.layer=layer
380
381 def objectLayerMask(object, layers):
382     layer=[]
383     for i in range(20):
384         try:
385             layer.append(True if layers[i]!=0 else False)
386         except IndexError:
387             layer.append(False)
388     object.layers=layer
389
390 def objectPinShape(o):
391     o.shape_key_lock=True
392
393 def objectAddShapeKey(o, name):
394     return o.add_shape_key(name)
395
396 def objectActivateShapeKey(o, index):
397     o.active_shape_key_index=index
398
399 def shapeKeyAssign(shapeKey, index, pos):
400     shapeKey.data[index].co=pos
401
402 def objectIsVisible(obj):
403     return obj.restrict_view
404
405 def meshVertexGroupNames(meshObject):
406     for g in meshObject.vertex_groups:
407         yield g.name
408
409 def faceNormal(face):
410     return face.normal
411
412 def meshFaceUv(mesh, i, face):
413     return mesh.uv_textures[0].data[i].uv
414
415 def armatureModifierGetObject(m):
416     return m.object
417
418 def objectHasShapeKey(o):
419     return o.data.shape_keys
420
421 def objectShapeKeys(o):
422     return o.data.shape_keys.keys
423
424 def meshVertexGroup(meshObject, name):
425     indices=[]
426     for i, v in enumerate(meshObject.data.verts):
427         for g in v.groups:
428             if meshObject.vertex_groups[g.group].name==name:
429                 indices.append(i)
430     return indices
431
432 def materialGet(scene, material_name):
433     return bpy.data.materials[material_name]
434
435 def modifierIsArmature(m):
436     return m.type=="ARMATURE"
437
438 def boneHeadLocal(b):
439     return b.head_local[0:3]
440
441 def boneTailLocal(b):
442     return b.tail_local[0:3]
443
444 def boneIsConnected(b):
445     return b.connected
446
447 def constraintIsIKSolver(c):
448     return c.type=='IK'
449
450 def ikChainLen(c):
451     return c.chain_length
452
453 def ikTarget(c):
454     return c.subtarget
455
456 def ikItration(c):
457     return c.iterations
458
459 def ikRotationWeight(c):
460     return c.weight
461
462 def shapeKeyGet(b, index):
463     return b.data[index].co
464
465 def shapeKeys(b):
466     for k in b.data:
467         yield k.co
468
469 def VtoV(v):
470     return mathutils.Vector([v.x, v.y, v.z])
471
472 def meshSetSmooth(mesh, smoothing):
473     mesh.autosmooth_angle=int(smoothing)
474     mesh.autosmooth=True
475
476 def meshRecalcNormals(mesh_object):
477     bpy.ops.object.select_all(action='DESELECT')
478     objectActivate(bpy.context.scene, mesh_object)
479     enterEditMode()
480     bpy.ops.mesh.normals_make_consistent()
481     exitEditMode()
482
483 def meshFlipNormals(mesh):
484     mesh.flipNormals()
485
486 def materialHasTexture(material):
487     return material.texture_slots[0]
488
489 def faceGetIndices(face):
490     return [face.verts[0], face.verts[1], face.verts[2]]
491