Algorithmadvanced
Direct slicing of CAD models
Also called CAD-based slicing.
Cuts the exact CAD solid by each layer plane instead of a triangle mesh, so the layer contours are exact curves and the only error is the one chosen for the printer path.
- Time
- O(k t) conic_treesO(t n) polygons
- Space
- O(t + n) extra
- Where
- k = number of layers; n = total number of polygon vertices over all layers; t = number of nodes of the CSG tree
- Model
- Real RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sashidhar Guduri, Richard H. Crawford, Joseph J. Beaman, Ron Jamieson, Herbert Hacker, 1992
Direct slicing computes the layers of a part for additive manufacturing from the exact CAD model, not from a triangle mesh. The usual chain exports the solid as an STL mesh and then cuts the triangles with the layer planes, as in triangle mesh slicing. The mesh only touches the true surface at its vertices, so every contour inherits the chord error of the export, and this error is fixed in 3D before anyone knows the layer height. Direct slicing intersects each layer plane with the true faces of the model. For a solid made of planes, spheres, cylinders and cones the section of each face is an exact conic with rational coefficients, and the layer is the same Boolean expression of these conics. For NURBS faces the section is a curve that a numerical method computes to a tolerance that the user sets per layer. Guduri, Crawford and Beaman (1992) did this for CSG solids of quadrics, and Jamieson and Hacker (1995) did it for the B-rep inside a CAD system. This page gives the exact version for a CSG tree of quadrics, proves that the section of the tree is the tree of the sections, and bounds the error of the polygon that is finally sent to the printer.
In plain words
To print a part, the printer needs its outline on each layer. The common way first turns the smooth part into many small flat triangles, then cuts the triangles. The triangles are a little off the real surface, so every outline is a little off too, and nothing later can fix it.
Direct slicing skips the triangles. It asks the CAD model itself where each layer crosses the surface. For a ball or a round hole the answer is an exact circle or oval. The outline only becomes straight segments at the very end, and the program picks as many segments as it needs to stay within the error that the user allows on that layer.
The problem
A solid is given as a CSG tree (constructive solid geometry). Each leaf is a quadric half-space: a symmetric matrix , with the solid for . Each inner node is a union, an intersection or a difference of its two children. A ball of center and radius is . An infinite cylinder through the point with axis direction and radius is
and a half-space is a quadric with no quadratic part. All input numbers are rational.
Given the tree , the layer heights and a tolerance tol, the task is to give, for each layer, the exact set , and a set of polygons for the printer whose distance from the true contours is at most tol.
The algorithm
Substitute in the quadric. The result is a conic with and a symmetric matrix . The upper left block of is the same as in , the last column picks up , and the corner is . With rational and these are rational numbers, computed without error.
DIRECT-SLICE(T, Z, tol)- 1
for each leaf Q of T: M_Q ← SECTION(Q, Z) ▷ exact rational conic - 2
T_Z ← T with each leaf Q replaced by M_Q ▷ the exact layer - 3
contours ← empty list - 4
for each leaf M of T_Z do - 5
(kind, c, f_c) ← CLASSIFY(M) - 6
if kind = ellipse then P ← POLYLINE(M, tol) - 7
append the runs of vertices v of P with CLASSIFY-POINT(T_Z, v, M) = on - 8
return T_Z, contours CLASSIFY(M) ▷ A = 2×2 block, b = (M13, M23), f₀ = M33- 9
if det A = 0 then return parabolic - 10
c ← −A⁻¹ b; f_c ← f₀ + b·c ▷ the value of the conic at its center - 11
if A is positive definite then return ellipse, point or empty as f_c <, =, > 0 - 12
return hyperbola, line pair or complement POLYLINE(M, tol) ▷ a ≥ b semi-axes, e₁, e₂ unit axes- 13
n ← max(3, ⌈π / arccos(1 − tol/a)⌉) - 14
return c + a cos(2πj/n) e₁ + b sin(2πj/n) e₂ for j = 0 … n−1
Lines L1 and L2 are the whole exact part: the layer is the tree , and a point is in the layer if and only if the same Boolean expression of the signs of the conics says so. CLASSIFY finds the center where the gradient of the conic vanishes, and the value there. If the block is positive definite and , the leaf is an ellipse with squared semi-axes and , where are the eigenvalues of . The type, the center, , and are exact. The semi-axes and their directions need square roots, so only they are floats.
POLYLINE is the only step that approximates. It places vertices on the ellipse, and is the least number of vertices for which the chord error is at most tol. Line L7 trims the polygon of one leaf to the boundary of the layer. A vertex is kept when it is on the boundary of with that leaf forced to "on", with the three valued rules: a union is in if one side is in, an intersection is out if one side is out, and a difference is an intersection with the complement, which swaps in and out.
A general CAD model is a B-rep whose faces are planes, quadrics, tori and NURBS patches. The same plan applies face by face: the section of a plane or a quadric face is a line or a conic, trimmed to the face boundary, and the section of a NURBS face is a curve that a surface-surface intersection method traces to a tolerance. The pieces are then linked into loops by their end points.
Example
A ball of radius 10 at the origin has a straight hole of radius 2 drilled through it. The hole has the axis direction through the origin, so it leans from the vertical. The tree is . Slice it at with tol .
Line L1 gives two conics. For the ball, : the circle , which is . For the cylinder, and
which is after multiplying by 25.
| leaf | kind | center | squared semi-axes | ||
|---|---|---|---|---|---|
| ball | ellipse | 1 | 84 and 84 | ||
| cylinder | ellipse | and |
The cylinder gives the ellipse , with semi-axes 2.5 along and 2 along . The closed form agrees: the axis meets the plane at , at , and a cylinder of radius cut by a plane at angle gives the semi-axes and . All the numbers in the table are exact fractions.
The point is in the hole: the ball conic is and the cylinder conic is , so the difference says out. The point has the scaled cylinder value and the ball value , so it is in the layer.
Line L13 gives for the outer circle () and for the hole (). The hole lies inside the disk, so all the vertices of both polygons are "on", and the result is two closed loops. On the next layer only the numbers change in line L1, and the error stays at most 0.01 on every layer.
The same ball as a mesh. A UV sphere of radius 10 with 16 rings and 32 segments is within about 0.096 of the true sphere in 3D. Slice it at : the section is a regular 32-gon with circumradius 9.641 and inradius 9.595, while the true circle has radius . The contour is off by up to 0.088. At , near the pole, the true radius is 0.999 and the mesh section has radius at most 0.508, so the contour is off by 0.49: the surface is almost flat there, and a small error in height becomes a large error in the layer. The direct section at is , exactly.
Correctness
Three facts make the method correct. First, substituting in gives term by term, so each leaf conic is the exact section of its leaf. Second, the section by a plane commutes with union, intersection and difference: , and the same for the other two. By induction on the tree, describes exactly the section of the solid. Third, the polygon of POLYLINE is the affine image of a regular -gon inscribed in the unit circle. Pairing each point of the circle with the point of the -gon on the same ray moves it by a factor between and 1. The affine map stretches no vector by more than , so the Hausdorff distance between the polygon and the ellipse is at most .
One caveat: CAD kernels use regularized Boolean operations, and regularization does not commute with the section. At a plane that only touches a face, the exact section can have a lower dimension part, such as the single point at the pole of a ball. The regularized layer drops it. The trimming of line L7 is a float test, and near a point where two conics cross, a kept run ends up to one edge before the crossing. The full proof is in the correctness proof.
What the tests check. They compare the sphere section with and the cylinder section with the semi-axes and on random rational input, exactly. They compare the 2D membership with the 3D membership on random trees and points, and they measure the Hausdorff distance of the polygons against tol.
Proof: The plane section of a quadric CSG solid is the same Boolean tree of exact conics, and the polygon output is within the tolerancefull
Setting. A leaf is a symmetric matrix , and the leaf solid is with . A tree is a leaf or with op in , and its solid is defined by the same recursion. For a height let , and identify with . Lines L1 and L2 build the tree with each leaf replaced by the matrix :
The set of a conic leaf is with , and is built from these sets by the same operations.
Claim.
- as point sets, and every entry of every is rational when and are rational.
- CLASSIFY returns the right type for an ellipse leaf, its center and the value at the center, and the squared semi-axes are and , where are the eigenvalues of the block.
- For an ellipse with largest semi-axis and a tolerance , the polygon of POLYLINE has vertices on the ellipse, with the least integer at least 3 such that , and its Hausdorff distance from the ellipse is at most tol.
- The algorithm stops after exact operations for the tree and float operations for the polygons.
Step 1 (one leaf). Let and . Write and split the indices into , and , with and . The terms with give . The terms with one index and the other in give , by symmetry of . The terms with both indices in give . This sum is term by term. So for every , and . The entries of are sums and products of entries of and of , so they are rational when the input is rational.
Step 2 (the tree). By induction on . For a leaf this is step 1. For an inner node, intersection with a fixed set distributes over the three operations:
With the induction hypothesis for and this gives . This proves claim 1.
The claim is about the plain set operations. A CAD kernel uses regularized operations, which take the closure of the interior of the result. Regularization does not commute with the section. The ball meets the plane in the single point , and its leaf conic is , which is that point. The regularized 2D set of a point is empty. So at a plane that touches a face, the exact set of claim 1 can have parts of lower dimension, and the printer must drop them. The membership test of the code is the set of claim 1.
Step 3 (CLASSIFY). Write the conic as with the block, and . If , the gradient is zero exactly at , which is the formula of the code by Cramer's rule. Substitute : , because and , so . If and , then is positive definite and is an ellipse with center if , the point if , and empty if . In the orthonormal eigenbasis of the set is , so the squared semi-axes are and . Their product is and their sum is , both rational. This proves claim 2. The other types are reported but give no loop in the code.
Step 4 (the polygon). Let the ellipse be with , unit vectors and . Then for every . The polygon has the vertices with , so its vertices are on , and is the image under of the regular -gon inscribed in the unit circle.
Pair each point of the unit circle with a point of along the same ray from the origin. On the arc between and , the point at angle from the middle of the arc, with , pairs with the point of the chord at distance from the origin, and . This pairing is a bijection between the circle and the boundary of , because every ray from the origin meets each of them once. For a pair the image points differ by , of length at most . So every point of has a point of within that distance, and every point of has a point of within it. The Hausdorff distance is at most , which is at most tol by the choice of . For tol the value is in , the smallest real with is , and is its ceiling, at least 3. The code adds 1 to while the float test fails, which only increases . This proves claim 3.
Step 5 (termination and cost). SECTION does a fixed number of exact operations on one leaf, and lines L1 and L2 visit each node once. CLASSIFY is a fixed number of operations. Membership of one point visits each node once. POLYLINE makes vertices for leaf , and the trimming test of line L7 classifies each vertex against the tree in time. No step loops without bound, so the algorithm stops. This proves claim 4.
What is not proved. The trimming of line L7 keeps the vertices that are on the boundary of the layer. It works with floats and a small , and near a point where two conics cross, the kept run ends at the last vertex before the crossing, up to one edge away from it. The exact crossing points are the roots of a quartic and are not computed here. The bound of claim 3 is for a full ellipse, not for a trimmed run.
Complexity
For one layer, line L1 does a fixed number of exact operations per leaf, so the conic tree costs , and layers cost . The rational numbers grow with the size of the input fractions and of , not with the number of layers, because each layer starts again from . Testing one point against costs .
The polygon of an ellipse with largest semi-axis has vertices, because . A tolerance 10 times smaller needs about times more vertices: for the counts are 22, 70 and 219 for tol 0.1, 0.01 and 0.001. Trimming tests each vertex against the tree, so output vertices over all layers cost . A mesh slicer runs in time linear in the number of triangles, but the mesh must be fine everywhere to be accurate on the worst layer.
For NURBS faces the cost depends on the intersection method and the tolerance, and no simple bound covers it.
Properties
- No tessellation error. The layer is the exact section of the model. For quadric solids it is exact in rational arithmetic.
- Error chosen per layer. The only approximation is the polygon output, with an error bound that the user sets, and it can change from layer to layer.
- No mesh repair. The input is a valid solid, so the gaps, flipped triangles and self intersections of bad STL files do not occur.
- Depends on the CAD kernel. The slicer needs the CAD model or a STEP file, and a surface intersection routine for each face type.
- Boundary cases. At a plane that touches a face, the exact section can contain points or curves of lower dimension, which regularization removes.
Variants and improvements
- B-rep slicing. Jamieson and Hacker (1995) cut each face of the B-rep inside the CAD system, which gives the section curves of planes, quadrics and spline faces.
- NURBS by ray casting. Starly and coauthors (2005) read NURBS faces from a STEP file and compute the contours as raster lines with ray casting, together with adaptive layer heights.
- Adaptive direct slicing. The exact model gives the surface normal at each contour point, so the cusp height of adaptive slicing can be computed from the true surface instead of from triangle normals.
- Implicit and volume models. A model given as an implicit surface or a signed distance field is sliced by contouring each plane of the field, for example with marching squares.
- Curved layers. When the layers are not planes, the same idea cuts the model with a family of surfaces. See curved layer printing.
When to use it
Use direct slicing when the CAD model is available and the surface quality matters: large parts with gently sloped faces, where the error of the mesh near the flat regions shows on the layers, or parts for which a fine STL file would be very large. It also helps when the mesh export produces bad geometry. Use mesh slicing when only a mesh exists (scans, models from other tools), when the slicer must accept any input, or when the printer software only reads STL.
Pitfalls
- Calling NURBS slicing exact. The section of a NURBS face is not a closed form curve. It is computed numerically to a tolerance. Direct slicing removes the error of the tessellation, not every error.
- Float conics. Computing the conic coefficients in floats loses the exact type at tangent planes. A sphere cut at its pole can come out as a tiny ellipse or as empty.
- Ignoring regularization. Point and curve parts of a section at a tangent plane must be removed before the path planner sees them.
- Too few vertices for the large axis. The vertex count must use the largest semi-axis. Using the smaller one breaks the bound on long thin ellipses, for example the section of a steep cylinder.
- Trimming by samples. A trimmed polygon run ends at a vertex near the crossing of two conics, not at the crossing. Compute the crossing points when the corners must be sharp.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-slicing/. The authors are listed in prov/YQA8PY.jsonl.
"""Direct slicing of a CSG solid built from quadric half-spaces.
A leaf of the tree is a symmetric 4 x 4 matrix Q. A point p = (x, y, z) is
inside the leaf when X^T Q X <= 0 with X = (x, y, z, 1). Spheres, cylinders,
cones and planes are leaves of this form. Inner nodes are ("union", A, B),
("inter", A, B) and ("diff", A, B).
The plane z = Z cuts each leaf in a conic, given by the symmetric 3 x 3 matrix
M with [x y 1] M [x y 1]^T = X^T Q X. With rational input every entry of M is
rational, so the section is exact. The only approximation is the optional
polyline that is made for the printer, and its error is bounded by tol.
"""
import math
from fractions import Fraction as F
# ---------------------------------------------------------------- leaves
def sphere(center, r2):
"""Ball |p - c|^2 - r2 <= 0. r2 is the squared radius."""
cx, cy, cz = (F(v) for v in center)
q = [[F(0)] * 4 for _ in range(4)]
for i in range(3):
q[i][i] = F(1)
q[0][3] = q[3][0] = -cx
q[1][3] = q[3][1] = -cy
q[2][3] = q[3][2] = -cz
q[3][3] = cx * cx + cy * cy + cz * cz - F(r2)
return q
def cylinder(point, axis, r2):
"""Infinite solid cylinder |p - a|^2 - ((p - a).u)^2 / |u|^2 - r2 <= 0."""
p = [F(v) for v in point]
a = [F(v) for v in axis]
n2 = sum(v * v for v in a)
if n2 == 0:
raise ValueError("zero axis")
# quadratic part I - a a^T / |a|^2
m = [[(F(1) if i == j else F(0)) - a[i] * a[j] / n2 for j in range(3)] for i in range(3)]
mp = [sum(m[i][j] * p[j] for j in range(3)) for i in range(3)]
q = [[F(0)] * 4 for _ in range(4)]
for i in range(3):
for j in range(3):
q[i][j] = m[i][j]
q[i][3] = q[3][i] = -mp[i]
q[3][3] = sum(p[i] * mp[i] for i in range(3)) - F(r2)
return q
def half_space(normal, offset):
"""Half-space n.p - offset <= 0, a quadric with no quadratic part."""
n = [F(v) for v in normal]
q = [[F(0)] * 4 for _ in range(4)]
for i in range(3):
q[i][3] = q[3][i] = n[i] / 2
q[3][3] = -F(offset)
return q
def quadric_value(q, p):
x = [F(p[0]), F(p[1]), F(p[2]), F(1)]
return sum(x[i] * q[i][j] * x[j] for i in range(4) for j in range(4))
def inside_3d(tree, p):
"""Exact membership of a 3D point, used as the reference."""
if tree[0] == "leaf":
return quadric_value(tree[1], p) <= 0
a, b = inside_3d(tree[1], p), inside_3d(tree[2], p)
return combine(tree[0], a, b)
def combine(op, a, b):
if op == "union":
return a or b
if op == "inter":
return a and b
if op == "diff":
return a and not b
raise ValueError(op)
# ---------------------------------------------------------------- section
def section(q, z):
"""The conic matrix M of the leaf q on the plane z = Z. Exact."""
z = F(z)
m = [[F(0)] * 3 for _ in range(3)]
for i in range(2):
for j in range(2):
m[i][j] = q[i][j]
m[i][2] = m[2][i] = q[i][2] * z + q[i][3]
m[2][2] = q[2][2] * z * z + 2 * q[2][3] * z + q[3][3]
return m
def slice_tree(tree, z):
"""Lines L1 and L2: replace every quadric leaf by its conic."""
if tree[0] == "leaf":
return ("leaf", section(tree[1], z)) # @line L1
return (tree[0], slice_tree(tree[1], z), slice_tree(tree[2], z))
def conic_value(m, p):
x = [F(p[0]), F(p[1]), F(1)]
return sum(x[i] * m[i][j] * x[j] for i in range(3) for j in range(3))
def inside_2d(tree2, p):
"""Exact membership of a point of the layer."""
if tree2[0] == "leaf":
return conic_value(tree2[1], p) <= 0
return combine(tree2[0], inside_2d(tree2[1], p), inside_2d(tree2[2], p))
def classify(m):
"""Line L5. Return (kind, center, fc, det) for a conic matrix.
det is the determinant of the 2 x 2 block, center solves the 2 x 2 system
when det != 0, and fc is the value of the conic at the center. Kinds:
"ellipse", "point", "empty" (positive definite block), "hyperbola",
"line pair", "parabolic" (det = 0), "complement" (negative definite block:
the region f <= 0 lies outside an ellipse, or is the whole plane).
"""
a, b, c = m[0][0], m[0][1], m[1][1]
d, e, f = m[0][2], m[1][2], m[2][2]
det = a * c - b * b
if det == 0: # @line L9
return ("parabolic", None, None, det)
cx = (b * e - c * d) / det
cy = (b * d - a * e) / det
fc = f + d * cx + e * cy # @line L10
if det > 0 and a > 0: # @line L11
kind = "ellipse" if fc < 0 else ("point" if fc == 0 else "empty")
elif det > 0: # @line L12
kind = "complement"
else:
kind = "line pair" if fc == 0 else "hyperbola"
return (kind, (cx, cy), fc, det)
def ellipse_axes(m):
"""Squared semi-axes and unit axis directions of an ellipse (floats).
The squared semi-axes are -fc / lambda_i, where lambda_i are the
eigenvalues of the 2 x 2 block.
"""
kind, center, fc, det = classify(m)
if kind != "ellipse":
raise ValueError("not an ellipse: " + kind)
a, b, c = float(m[0][0]), float(m[0][1]), float(m[1][1])
mean = (a + c) / 2
rad = math.hypot((a - c) / 2, b)
lam1, lam2 = mean - rad, mean + rad # lam1 <= lam2, both > 0
if b == 0 and a <= c:
v1 = (1.0, 0.0)
elif b == 0:
v1 = (0.0, 1.0)
else:
v1 = (lam1 - c, b)
n = math.hypot(*v1)
v1 = (v1[0] / n, v1[1] / n)
v2 = (-v1[1], v1[0])
s1, s2 = -float(fc) / lam1, -float(fc) / lam2 # s1 >= s2
return (float(center[0]), float(center[1])), s1, s2, v1, v2
def vertex_count(a, tol):
"""The least n >= 3 with a (1 - cos(pi / n)) <= tol."""
if tol >= a:
return 3
n = math.ceil(math.pi / math.acos(1 - tol / a))
n = max(3, n)
while a * (1 - math.cos(math.pi / n)) > tol: # guard against rounding
n += 1
return n
def ellipse_polyline(m, tol):
"""Line L6. A closed polygon with vertices on the ellipse and
Hausdorff distance at most tol from it."""
(cx, cy), s1, s2, v1, v2 = ellipse_axes(m)
a1, a2 = math.sqrt(s1), math.sqrt(s2)
n = vertex_count(a1, tol) # @line L13
pts = []
for k in range(n): # @line L14
t = 2 * math.pi * k / n
u, w = a1 * math.cos(t), a2 * math.sin(t)
pts.append((cx + u * v1[0] + w * v2[0], cy + u * v1[1] + w * v2[1]))
return pts
# ------------------------------------------------- boundary classification
IN, ON, OUT = -1, 0, 1
def _combine3(op, a, b):
if op == "union":
if IN in (a, b):
return IN
return OUT if a == b == OUT else ON
if op == "inter":
if OUT in (a, b):
return OUT
return IN if a == b == IN else ON
if op == "diff":
return _combine3("inter", a, -b)
raise ValueError(op)
def classify_point(tree2, p, leaf, eps):
"""Three-valued membership, with the given leaf forced to ON.
Other leaves are ON when |f| <= eps, so a point on two conics at once is
ON. Two ON values in a union give ON, which is right for contours that
cross but not for two solids that touch along a curve.
"""
if tree2[0] == "leaf":
if tree2 is leaf:
return ON
v = conic_value_float(tree2[1], p)
return ON if abs(v) <= eps else (IN if v < 0 else OUT)
return _combine3(tree2[0], classify_point(tree2[1], p, leaf, eps), classify_point(tree2[2], p, leaf, eps))
def conic_value_float(m, p):
x = (p[0], p[1], 1.0)
return sum(x[i] * float(m[i][j]) * x[j] for i in range(3) for j in range(3))
def leaves(tree2):
if tree2[0] == "leaf":
return [tree2]
return leaves(tree2[1]) + leaves(tree2[2])
def direct_slice(tree, z, tol, eps=1e-12):
"""DIRECT-SLICE. Return the exact conic tree of the layer and the
contour pieces as lists of points (open runs, or closed loops with the
first point repeated at the end)."""
tree2 = slice_tree(tree, z) # @line L2
contours = [] # @line L3
for leaf in leaves(tree2): # @line L4
kind = classify(leaf[1])[0] # @line L5
if kind != "ellipse":
continue # points, empty sets and unbounded conics give no loop here
poly = ellipse_polyline(leaf[1], tol) # @line L6
keep = [classify_point(tree2, p, leaf, eps) == ON for p in poly] # @line L7
if all(keep):
contours.append(poly + [poly[0]])
continue
n = len(poly)
start = keep.index(False)
run = []
for k in range(1, n + 1):
i = (start + k) % n
if keep[i]:
run.append(poly[i])
elif run:
contours.append(run)
run = []
if run:
contours.append(run)
return tree2, contours # @line L8
# --------------------------------------------- mesh slice, for comparison
def uv_sphere_section_radii(r, rings, segments, z):
"""Slice a UV-sphere mesh of radius r at height z (|z| < r, z not at a
ring). Return (min, max) distance from the axis to the polygon of the
section. The true section is a circle of radius sqrt(r^2 - z^2)."""
lats = [math.pi * k / rings - math.pi / 2 for k in range(rings + 1)]
zs = [r * math.sin(t) for t in lats]
k = max(i for i in range(rings) if zs[i] < z)
r0, r1 = r * math.cos(lats[k]), r * math.cos(lats[k + 1])
t = (z - zs[k]) / (zs[k + 1] - zs[k])
rho = r0 + t * (r1 - r0) # the section is a regular polygon with this circumradius
return rho * math.cos(math.pi / segments), rho
test_direct_slicing.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/direct-slicing/. The authors are listed in prov/YQA8PY.jsonl.
import math
import random
from fractions import Fraction as F
from direct_slicing import (
classify,
cylinder,
direct_slice,
ellipse_axes,
ellipse_polyline,
half_space,
inside_2d,
inside_3d,
section,
slice_tree,
sphere,
uv_sphere_section_radii,
vertex_count,
)
def test_sphere_slice_is_the_closed_form_circle() -> None:
rng = random.Random(1)
for _ in range(200):
c = [F(rng.randint(-20, 20), rng.randint(1, 5)) for _ in range(3)]
r2 = F(rng.randint(1, 400), rng.randint(1, 4))
z = F(rng.randint(-100, 100), rng.randint(1, 7))
kind, center, fc, det = classify(section(sphere(c, r2), z))
want = r2 - (z - c[2]) ** 2
if want > 0:
assert kind == "ellipse"
assert center == (c[0], c[1])
assert det == 1 and -fc == want # radius^2 = R^2 - (Z - c_z)^2, exactly
elif want == 0:
assert kind == "point" and center == (c[0], c[1])
else:
assert kind == "empty"
def test_sphere_pole_gives_a_point() -> None:
kind, center, fc, _ = classify(section(sphere((0, 0, 0), 25), 5))
assert kind == "point" and center == (0, 0) and fc == 0
kind, _, fc, _ = classify(section(sphere((0, 0, 0), 25), 3))
assert kind == "ellipse" and -fc == 16
def test_cylinder_slice_is_the_closed_form_ellipse() -> None:
rng = random.Random(2)
for _ in range(200):
p = [F(rng.randint(-10, 10)) for _ in range(3)]
a = [F(rng.randint(-4, 4)) for _ in range(2)] + [F(rng.choice([-3, -2, -1, 1, 2, 3]))]
r2 = F(rng.randint(1, 50), rng.randint(1, 3))
z = F(rng.randint(-30, 30), rng.randint(1, 4))
kind, center, fc, det = classify(section(cylinder(p, a, r2), z))
assert kind == "ellipse"
t = (z - p[2]) / a[2] # the axis meets the plane at p + t a
assert center == (p[0] + t * a[0], p[1] + t * a[1])
n2 = sum(v * v for v in a)
# squared semi-axes r^2 and r^2 |a|^2 / a_z^2
s1, s2 = r2 * n2 / a[2] ** 2, r2
assert det == a[2] ** 2 / n2 # eigenvalues 1 and a_z^2 / |a|^2
assert fc * fc / det == s1 * s2 # product of the squared semi-axes
trace = section(cylinder(p, a, r2), z)[0][0] + section(cylinder(p, a, r2), z)[1][1]
assert -fc * trace / det == s1 + s2 # sum of the squared semi-axes
_, f1, f2, _, _ = ellipse_axes(section(cylinder(p, a, r2), z))
assert math.isclose(f1, float(s1), rel_tol=1e-9) and math.isclose(f2, float(s2), rel_tol=1e-9)
def test_vertical_cylinder_has_the_same_circle_on_every_layer() -> None:
q = cylinder((1, 2, 0), (0, 0, 1), 9)
for z in range(-5, 6):
kind, center, fc, det = classify(section(q, z))
assert (kind, center, -fc, det) == ("ellipse", (1, 2), 9, 1)
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.3:
k = rng.randrange(3)
if k == 0:
q = sphere([rng.randint(-3, 3) for _ in range(3)], rng.randint(1, 16))
elif k == 1:
q = cylinder([rng.randint(-3, 3) for _ in range(3)], [rng.randint(-2, 2), rng.randint(-2, 2), rng.randint(1, 2)], rng.randint(1, 9))
else:
q = half_space([rng.randint(-2, 2) for _ in range(3)], rng.randint(-3, 3))
return ("leaf", q)
op = rng.choice(["union", "inter", "diff"])
return (op, random_tree(rng, depth - 1), random_tree(rng, depth - 1))
def test_layer_membership_equals_solid_membership() -> None:
rng = random.Random(3)
for _ in range(60):
tree = random_tree(rng, 3)
z = F(rng.randint(-12, 12), 4)
tree2 = slice_tree(tree, z)
for _ in range(40):
x, y = F(rng.randint(-24, 24), 4), F(rng.randint(-24, 24), 4)
assert inside_2d(tree2, (x, y)) == inside_3d(tree, (x, y, z))
def dist_point_segment(p, a, b):
ax, ay = b[0] - a[0], b[1] - a[1]
t = ((p[0] - a[0]) * ax + (p[1] - a[1]) * ay) / (ax * ax + ay * ay)
t = max(0.0, min(1.0, t))
return math.hypot(p[0] - a[0] - t * ax, p[1] - a[1] - t * ay)
def test_polyline_error_is_within_tolerance() -> None:
q = cylinder((0, 0, 0), (1, 1, 2), 4)
m = section(q, F(1, 3))
(cx, cy), s1, s2, v1, v2 = ellipse_axes(m)
a1, a2 = math.sqrt(s1), math.sqrt(s2)
for tol in (0.5, 0.1, 0.01, 0.001):
poly = ellipse_polyline(m, tol)
n = len(poly)
assert n == vertex_count(a1, tol)
for p in poly: # vertices lie on the ellipse
assert abs(float(sum(x * float(m[i][j]) * y for i, x in enumerate((p[0], p[1], 1.0)) for j, y in enumerate((p[0], p[1], 1.0))))) < 1e-9
worst = 0.0
for k in range(20 * n): # ellipse to polygon
t = 2 * math.pi * k / (20 * n)
u, w = a1 * math.cos(t), a2 * math.sin(t)
e = (cx + u * v1[0] + w * v2[0], cy + u * v1[1] + w * v2[1])
worst = max(worst, min(dist_point_segment(e, poly[i], poly[(i + 1) % n]) for i in range(n)))
assert worst <= tol + 1e-12
if n > 3: # one vertex fewer would break the bound
assert a1 * (1 - math.cos(math.pi / (n - 1))) > tol
def test_trimmed_contours_lie_on_the_boundary() -> None:
# a ball minus a vertical hole: the layer is an annulus with two loops
tree = ("diff", ("leaf", sphere((0, 0, 0), 100)), ("leaf", cylinder((0, 0, 0), (0, 0, 1), 9)))
tree2, contours = direct_slice(tree, 6, 0.01)
assert len(contours) == 2
radii = sorted(round(math.hypot(*c[0]), 9) for c in contours)
assert radii == [3.0, 8.0] # 8 = sqrt(100 - 36)
# two overlapping balls: each circle keeps only its outer arc
tree = ("union", ("leaf", sphere((0, 0, 0), 25)), ("leaf", sphere((6, 0, 0), 25)))
tree2, contours = direct_slice(tree, 0, 0.001)
assert len(contours) == 2
for run in contours:
for p in run:
d0, d1 = math.hypot(p[0], p[1]), math.hypot(p[0] - 6, p[1])
assert min(abs(d0 - 5), abs(d1 - 5)) < 1e-9 # on one circle
assert min(d0, d1) >= 5 - 1e-9 # and not inside the other ball
def test_mesh_slice_has_chordal_error_and_direct_slice_has_none() -> None:
lo, hi = uv_sphere_section_radii(10.0, 16, 32, 2.5)
true = math.sqrt(100 - 2.5**2)
assert 0.08 < true - lo < 0.09 # the mesh section misses the circle by 0.0876
lo, hi = uv_sphere_section_radii(10.0, 16, 32, -9.95)
assert math.sqrt(100 - 9.95**2) - hi > 0.4 # near the pole the error is ten times larger
kind, center, fc, _ = classify(section(sphere((0, 0, 0), 100), F(5, 2)))
assert kind == "ellipse" and -fc == F(375, 4) # exactly true^2
History
Guduri, Crawford and Beaman (1992, 1993) described the exact contours of CSG solids built from quadric primitives at the Solid Freeform Fabrication Symposium in Austin. Jamieson and Hacker (1995) sliced the B-rep inside the CAD system and avoided the STL file, which gave the method its name. Later work moved the method to exchange formats: Starly, Lau, Sun, Lau and Bradbury (2005) sliced NURBS models read from STEP files. Most printer software still slices meshes, because the input is usually an STL or 3MF file.
References
- Sashidhar Guduri, Richard H. Crawford and Joseph J. Beaman, A method to generate exact contour files for solid freeform fabrication, Solid Freeform Fabrication Symposium 1992, University of Texas at Austin, 95 to 101, exact contours of CSG solids built from quadric primitives
- Sashidhar Guduri, Richard H. Crawford and Joseph J. Beaman, Direct generation of contour files from constructive solid geometry representations, Solid Freeform Fabrication Symposium 1993, University of Texas at Austin, 291 to 302, the contours of a layer computed from the CSG tree without a tessellation (general locator)
- Ron Jamieson and Herbert Hacker, Direct slicing of CAD models for rapid prototyping, Rapid Prototyping Journal 1(2), 1995, 4 to 12, slicing the B-rep model inside the CAD system, with the plane section of each face, instead of an STL file
- Binil Starly, Alan Lau, Wei Sun, Wing Lau and Tom Bradbury, Direct slicing of STEP based NURBS models for layered manufacturing, Computer-Aided Design 37(4), 2005, 387 to 397, the contours of NURBS faces read from a STEP file, computed by ray casting along raster lines, with adaptive layer thickness
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YQA8PY Edit this page History Report an error Markdown