Skip to content

Instantly share code, notes, and snippets.

@dupontgu
Created January 4, 2025 18:51
Show Gist options
  • Save dupontgu/93e91fe3577c01a997612d5c3da1d389 to your computer and use it in GitHub Desktop.
Save dupontgu/93e91fe3577c01a997612d5c3da1d389 to your computer and use it in GitHub Desktop.
slice STL to SVG groups
import numpy as np
from stl import mesh
import svgwrite
def export_stl_slices_to_svg_with_groups(stl_file, output_svg, num_slices):
m = mesh.Mesh.from_file(stl_file)
z_min, z_max = m.z.min(), m.z.max()
x_min, x_max = m.x.min(), m.x.max()
y_min, y_max = m.y.min(), m.y.max()
width = x_max - x_min
height = y_max - y_min
slice_heights = np.linspace(z_min, z_max, num_slices)
dwg = svgwrite.Drawing(
output_svg,
profile='tiny',
size=(width.item(), height.item()),
viewBox=f"{x_min} {y_min} {width} {height}"
)
for i, z in enumerate(slice_heights):
slice_lines = []
for triangle in m.vectors:
# Extract vertices
v1, v2, v3 = triangle
plane_z = z
# Check intersections of triangle edges with the slicing plane
edges = [(v1, v2), (v2, v3), (v3, v1)]
intersections = []
for edge in edges:
p1, p2 = edge
if (p1[2] < plane_z and p2[2] >= plane_z) or (p1[2] >= plane_z and p2[2] < plane_z):
t = (plane_z - p1[2]) / (p2[2] - p1[2])
intersection = p1 + t * (p2 - p1)
intersections.append(intersection[:2])
if len(intersections) == 2: # A valid edge is found
slice_lines.append(intersections)
group = dwg.g(id=f"slice_{i:03d}")
for line in slice_lines:
# Convert numpy float32 to Python float
start = (float(line[0][0]), float(line[0][1]))
end = (float(line[1][0]), float(line[1][1]))
group.add(dwg.line(start=start, end=end, stroke=svgwrite.rgb(0, 0, 0, '%')))
dwg.add(group)
dwg.save()
stl_file = 'bunny.stl'
output_svg = 'bunny.svg'
num_slices = 30 # Adjust as needed
export_stl_slices_to_svg_with_groups(stl_file, output_svg, num_slices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment