I am writing a script that adds a cube, applies a subsurface modifier onto it and then randomly deforms that resulting mesh in order to get an irregular blob mesh. More precisely, I select a few mesh vertices and use the bpy.ops.transform.translate method to get smooth proportional deformations.
This below code works well when I run it in the Blender Scripting window. My problem arises when I transfer this same code to my script in VS Code. Most of the time it works without problems. But e.g. if I use it in a loop and create 100 such cubes after some random amount of deformed cubes Blender crashes (Error : EXCEPTION_ACCESS_VIOLATION) without further notice. It is weird that sometimes it crashes instantly when deforming the first cube, but most of the time it creates a couple of deformed objects and crashes then.
Does anyone have any advice?
#Create a cube, subdivide it, and make subdivision a mesh
bpy.ops.mesh.primitive_cube_add(size=1, enter_editmode=False, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers["Subdivision"].levels = 3
bpy.ops.object.modifier_apply(modifier="Subdivision")
#translate random mesh vertices using proportional edit
#i.e.: neighboring vertices are also translated proportionally
#extract mesh
bpy.ops.object.mode_set(mode='EDIT')
context = bpy.context
bm = bmesh.from_edit_mesh(context.edit_object.data)
#deselect all vertices
for v in bm.verts:
v.select = False
bm.verts.ensure_lookup_table() # NOTE: Necessary for accessing vertex list
for i in range(4):
transform = Vector([random.uniform(-1, 1),
random.uniform(-1, 1),
random.uniform(-1, 1)])*TRANSLATION_RANGE
v = bm.verts[random.randint(0, len(bm.verts) - 1)]
v.select = True
bpy.ops.transform.translate(value=transform,
constraint_axis=(False, False, False),
orient_type='GLOBAL',
mirror=False,
use_proportional_edit = True,
use_proportional_connected =True,
proportional_edit_falloff='SMOOTH',
proportional_size=PROPORTIONAL_SIZE)
Enter Object Mode
bpy.ops.object.mode_set(mode='OBJECT')
```