I try to export a collection of meshes such that
- The original meshes is not touched by the exporter
- All modifiers affect the exported mesh
- The exported mesh is triangulated
- It should not look like the file has been changed by the exporter
It is permissable to not fullfil the fourth requirement though.
Here is my preparation functions, used to copy the meshes and joining them into one:
def collect_meshes(collection):
meshes = []
for object in collection:
if object.type == 'MESH':
tmp = object.copy()
tmp.data = object.data.copy()
meshes.append(tmp)
return meshes
def apply_modifiers(objects):
context = bpy.context.copy()
for object in objects:
# Cannot select this object because it is not in a view layer
# object.select_set(True)
for modifier in object.modifiers:
# How to apply a modifier on a different object?
# bpy.ops.object.modifier_apply(context, modifier = modifier.name)
pass
def join_meshes(mesh_array):
context = bpy.context.copy()
context['active_object'] = mesh_array[0]
context['selected_editable_objects'] = mesh_array
bpy.ops.object.join(context)
return context['active_object']
def triangulate(mesh):
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.triangulate(bm, faces = bm.faces[:])
bm.to_mesh(mesh)
In case something went wrong, I also have the following cleanup:
class MeshCopy:
def __init__(self, mesh):
self.__mesh = mesh
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.__mesh.user_clear()
bpy.data.objects.remove(self.__mesh)
def get(self):
return self.__mesh
So I can use the with
statement for RAII. Is only way to get this working to create a copy of the original file, and export the content of that file and then delete the copy?