Skip to content

Instantly share code, notes, and snippets.

@dvoros
Created February 6, 2025 07:37
Blender script that turns curves (imported from a specially crafted SVG) to meshes according to rules encoded in their names.
import bpy
import bmesh
import re
layer_height=0.08
# Trying to use this to avoid slicer issues where certain parts of
# certain layers are left blank.
gap=-0.001
# gap=0.001
def parse_name(s):
# Split the string at underscores
parts = s.split('_')
parsed_results = []
# Iterate over each part
for part in parts:
# Use regular expressions to find the number and the letter(s)
match = re.match(r'(\d+)([a-zA-Z]+)', part)
if match:
number = int(match.group(1))
letters = match.group(2)
parsed_results.append((number, letters))
return parsed_results
def extrude_faces(obj, extrude_length):
# Ensure the object is a mesh
if obj.type != 'MESH':
bpy.ops.object.convert(target='MESH')
# Set the object to be the active object and switch to edit mode
bpy.context.view_layer.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
# Create a BMesh representation
bm = bmesh.from_edit_mesh(obj.data)
# Ensure we start with all faces selected
for face in bm.faces:
face.select = True
# Update the selection
bmesh.update_edit_mesh(obj.data)
# Perform the extrusion
bpy.ops.mesh.extrude_region_move(
TRANSFORM_OT_translate={
"value": (0, 0, extrude_length),
"orient_type": 'NORMAL',
"constraint_axis": (False, False, True)
}
)
# Switch back to object mode
bpy.ops.object.mode_set(mode='OBJECT')
def duplicate_object(obj):
# Ensure the object is selected
bpy.context.view_layer.objects.active = obj
obj.select_set(True)
# Duplicate the object
bpy.ops.object.duplicate()
# Deselect the original object
obj.select_set(False)
# Get the newly created duplicate
duplicate = bpy.context.selected_objects[0]
return duplicate
def color_extrude(obj):
parts = parse_name(obj.name)
height = 0.0
i = 0
for (n, c) in parts:
bpy.ops.object.select_all(action='DESELECT')
i += 1
width = n*layer_height
print("i=",i)
if c == "x":
height += width
continue
dupe = duplicate_object(obj)
dupe.name = f"{c}_{i}_{obj.name}"
extrude_faces(dupe, width-(2*gap))
dupe.location.z += height+gap
height += width
def do_selected():
# Example usage
# Get the active object
active_obj = bpy.context.active_object
# Extrude faces
if active_obj:
# extrude_faces(active_obj, extrude_length=0.4)
d = color_extrude(active_obj)
else:
print("No active object found.")
def do_all():
for obj in list(bpy.data.objects):
color_extrude(obj)
do_all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment