Algorithm Search⌘K

Algorithmcore

Triangle mesh slicing

Also called plane mesh slicing, contour construction.

Intersects each triangle with the planes it spans and links the segments into oriented polygons with a hash of endpoints, in O(n log k + k + m) time.

Time
O(n log k + k + m log m) worstO(n log k + k + m) expected
Space
O(n + k) extra
Where
k = number of slicing planes; m = number of triangle-plane segments; n = number of triangles
Properties
deterministicexactiterative
Origin
Rodrigo Minetto, Neri Volpato, Jorge Stolfi, Rodrigo M. M. H. Gregori, Murilo V. G. da Silva, 2017

Triangle mesh slicing cuts a closed triangle mesh with the horizontal planes z=Z1<Z2<⋯<Zkz = Z_1 < Z_2 < \dots < Z_k and returns, for each plane, the closed polygons where the plane meets the solid. Each triangle that crosses a plane gives one segment. The segments of one plane are then linked end to end into loops. The method on this page is the one of Minetto, Volpato, Stolfi, Gregori and da Silva (2017). It puts each triangle into the bucket of the first plane above its lowest vertex with a binary search, sweeps the planes from the bottom up with a list of active triangles, and links the segments with a hash table keyed by the crossed mesh edge. It runs in O(nlog⁡k+k+m)O(n \log k + k + m) expected time for nn triangles and mm segments, which matches their lower bound. It is the first step of most slicers for additive manufacturing.

In plain words

Think of a model made of many small flat triangles, like a paper shell. You cut it with flat horizontal knives at different heights, and for each knife you want the outline of the cut.

A triangle meets a knife only if the knife is between its lowest and its highest corner. So go up through the knives one by one, and keep a list of the triangles that the current knife can touch. Add a triangle when the knives reach its lowest corner, and drop it when they pass its highest corner.

Each touched triangle gives one short straight piece of the outline. Pieces from neighbouring triangles meet on their common edge, so a table keyed by edges gives the next piece. Follow the pieces until you come back to the start, and you have one closed outline.

The problem

The input is a mesh with vertices v1,…,vN∈R3v_1, \dots, v_N \in \mathbb{R}^3 and nn triangles given as index triples, an indexed face set. The mesh is closed, oriented and edge-manifold: each edge belongs to exactly two triangles, and they traverse it in opposite directions. Each triangle is listed counterclockwise as seen from outside, so its normal (vb−va)×(vc−va)(v_b - v_a) \times (v_c - v_a) points out by the right-hand rule. The input also has plane heights Z1<⋯<ZkZ_1 < \dots < Z_k.

The output is, for each jj, a set of closed polygons in the plane z=Zjz = Z_j. They are the boundary of the cross-section of the solid, with the solid on the left of each directed segment: outer loops run counterclockwise as seen from above, and holes run clockwise. This is the convention of polygon orientation and of polygons with holes. The total shoelace area of the loops of one plane is then the area of the cross-section.

Degenerate cases. A vertex can lie exactly at a plane height, an edge can lie in a plane, and a whole face can lie in a plane. Real models have many such cases, because layer heights are round numbers and so are the coordinates of flat faces. The rule of this page treats them as part of the input: a vertex with z=Zjz = Z_j counts as above the plane. This is the same as moving the plane to Zj−εZ_j - \varepsilon for an infinitely small ε>0\varepsilon > 0, a simple form of simulation of simplicity. With the rule, a triangle crosses the plane exactly when zmin⁡(t)<Zj≤zmax⁡(t)z_{\min}(t) < Z_j \le z_{\max}(t), it has then exactly one vertex alone on its side, and it gives exactly one segment. A face that lies in the plane gives no segment.

The algorithm

For a triangle tt and a height zz, CROSS(t,z)(t, z) marks each vertex as above (zv≥zz_v \ge z) or below (zv<zz_v < z). In the cyclic order of tt, exactly one edge eoute_{\text{out}} goes from an above vertex to a below vertex, and exactly one edge eine_{\text{in}} goes from below to above. CROSS returns eoute_{\text{out}}, the point pp where eoute_{\text{out}} meets the plane, and eine_{\text{in}}. An edge key is the unordered pair of its vertex indices. For the edge from aa to bb, p=a+(b−a) (z−za)/(zb−za)p = a + (b - a)\,(z - z_a)/(z_b - z_a), and za≠zbz_a \ne z_b because one end is above and the other below. The segment of tt runs from pp to the point on eine_{\text{in}}.

  1. SLICE(V, T, Z) ▷ mesh (V, T), heights Z[1] < ... < Z[k]
  2. 1B[1..k+1] ← empty lists
  3. 2for each triangle t ∈ T do
  4. 3j ← number of i with Z[i] ≤ zmin(t) ▷ binary search
  5. 4append t to B[j + 1] ▷ first plane above zmin(t)
  6. 5A ← empty list ▷ active triangles
  7. 6for j ← 1 to k do
  8. 7A ← A + B[j]
  9. 8remove from A each t with zmax(t) < Z[j]
  10. 9S ← empty hash table ▷ edge key → (point, edge key)
  11. 10for each t ∈ A do
  12. 11(e_out, p, e_in) ← CROSS(t, Z[j])
  13. 12S[e_out] ← (p, e_in)
  14. 13P[j] ← LINK(S)
  15. 14return P[1..k]
  16. LINK(S)
  17. 15C ← empty list
  18. 16while S is not empty do
  19. 17e0 ← any key of S; e ← e0; L ← empty loop
  20. 18repeat
  21. 19(p, e') ← S[e]; delete S[e]; append p to L; e ← e'
  22. 20until e = e0
  23. 21append L to C
  24. 22return C

Lines L1 to L4 put each triangle into the bucket of the first plane strictly above its lowest vertex. Line L8 drops the triangles whose highest vertex is below the plane. After line L8, a triangle is in AA exactly when zmin⁡(t)<Zj≤zmax⁡(t)z_{\min}(t) < Z_j \le z_{\max}(t), so every triangle in AA crosses the plane. Line L12 files the segment of tt under the edge where it starts. The segment that follows it in the loop starts where it ends, on the edge eine_{\text{in}}, so line L19 finds it with one lookup.

The key is the edge and not the point. A vertex on the plane is the crossing point of several edges, so points are not unique keys there, but edges are. The loop then contains the vertex more than once, and a triangle with a vertex on the plane and an edge with both ends at the same side can give a segment of length zero. A later pass can remove repeated points. They do not change the area or the orientation of the loop.

Exact arithmetic. The only predicate is the comparison zv≥Zjz_v \ge Z_j of two input numbers, so the topology of the loops is exact even in floating point, if each plane height is one stored number and each vertex has one stored zz. The points are constructions. With integer or rational input and exact geometric computation they are exact rationals, as in the code of this page. In floating point they are rounded, and the result depends on the direction of the edge. For the edge from a=(0.1,0.2,0)a = (0.1, 0.2, 0) to b=(0.7,0.9,1)b = (0.7, 0.9, 1) and z=0.3z = 0.3, the formula from aa gives (0.28,0.41000000000000003)(0.28, 0.41000000000000003), and the same formula from bb gives (0.27999999999999997,0.4100000000000001)(0.27999999999999997, 0.4100000000000001). A slicer that links segments by equal points then breaks a loop at such an edge. Edge keys avoid this, and so does computing each crossing point once per edge.

Example

Take the tetrahedron with v0=(0,0,0)v_0 = (0, 0, 0), v1=(6,0,2)v_1 = (6, 0, 2), v2=(0,6,4)v_2 = (0, 6, 4) and v3=(2,2,8)v_3 = (2, 2, 8), with the faces t0=(0,2,1)t_0 = (0, 2, 1), t1=(0,1,3)t_1 = (0, 1, 3), t2=(1,2,3)t_2 = (1, 2, 3) and t3=(0,3,2)t_3 = (0, 3, 2), all counterclockwise from outside (the signed volume is +36+36). The planes are Z=(1,2,4,6)Z = (1, 2, 4, 6).

step value
L1 to L4 zmin⁡=0,0,2,0z_{\min} = 0, 0, 2, 0. Buckets: B[1]={t0,t1,t3}B[1] = \{t_0, t_1, t_3\}, and B[3]={t2}B[3] = \{t_2\} because Z[2]=2≤zmin⁡(t2)Z[2] = 2 \le z_{\min}(t_2)
j=1j = 1, L10 to L12 S[{0,1}]=((3,0),{0,2})S[\{0,1\}] = ((3, 0), \{0,2\}), S[{0,3}]=((14,14),{0,1})S[\{0,3\}] = ((\tfrac14, \tfrac14), \{0,1\}), S[{0,2}]=((0,32),{0,3})S[\{0,2\}] = ((0, \tfrac32), \{0,3\})
j=1j = 1, LINK from {0,1}\{0,1\}: (3,0)→(0,32)→(14,14)(3, 0) \to (0, \tfrac32) \to (\tfrac14, \tfrac14), back to {0,1}\{0,1\}. Area 2716\tfrac{27}{16}
j=2j = 2 v1v_1 is on the plane and counts as above. t2t_2 is not active. Loop (6,0)→(0,3)→(12,12)(6, 0) \to (0, 3) \to (\tfrac12, \tfrac12), area 274\tfrac{27}{4}
j=3j = 3, L7 A={t0,t1,t3,t2}A = \{t_0, t_1, t_3, t_2\}. No triangle is dropped, since zmax⁡(t0)=4≥4z_{\max}(t_0) = 4 \ge 4
j=3j = 3, L11 t0t_0 gives a segment of length zero at v2=(0,6)v_2 = (0, 6). t1t_1 starts at (1,1)(1, 1), t2t_2 at (143,23)(\tfrac{14}{3}, \tfrac23), t3t_3 at (0,6)(0, 6)
j=3j = 3, LINK (0,6)→(0,6)→(1,1)→(143,23)(0, 6) \to (0, 6) \to (1, 1) \to (\tfrac{14}{3}, \tfrac23), area 99
j=4j = 4, L8 t0t_0 is dropped, since zmax⁡(t0)=4<6z_{\max}(t_0) = 4 < 6. Loop (32,32)→(103,43)→(1,4)(\tfrac32, \tfrac32) \to (\tfrac{10}{3}, \tfrac43) \to (1, 4), area 94\tfrac94

All four loops are counterclockwise, as outer loops must be. At j=1j = 1 the cut points lie on the edges v0v1v_0v_1, v0v2v_0v_2 and v0v3v_0v_3 at the fractions 12\tfrac12, 14\tfrac14 and 18\tfrac18, and the shoelace formula on them gives 2716\tfrac{27}{16} directly. At j=3j = 3 the loop is the triangle v2v_2, (1,1)(1, 1), (143,23)(\tfrac{14}{3}, \tfrac23) of area 9, with v2v_2 written twice.

Correctness

After line L8 the active list holds exactly the triangles with zmin⁡<Zj≤zmax⁡z_{\min} < Z_j \le z_{\max}, because the planes increase, so a triangle that is dropped never crosses a later plane. Each such triangle has one or two above vertices and one or two below vertices, so its cyclic order has exactly one edge from above to below and one from below to above. A crossing edge belongs to two triangles that traverse it in opposite directions, so it is eoute_{\text{out}} of one of them and eine_{\text{in}} of the other. The map from a segment to the segment that starts at its end edge is therefore a permutation of the segments of the plane, and LINK writes out its cycles, which are closed loops. A computation with the cross product shows that the outward normal of the triangle points to the right of its segment, so the solid is on the left. The full proof is below.

Proof: The bucket and sweep slicer returns closed loops with the solid on their leftfull

Claim. Let (V,T)(V, T) be a closed, oriented, edge-manifold triangle mesh: each edge {a,b}\{a, b\} belongs to exactly two triangles, one of them has bb right after aa in its cyclic order and the other has aa right after bb. Let Z1<⋯<ZkZ_1 < \dots < Z_k, and let all coordinates be exact numbers. Then SLICE(V,T,Z)(V, T, Z) stops, and for each jj:

  1. every triangle tt with zmin⁡(t)<Zj≤zmax⁡(t)z_{\min}(t) < Z_j \le z_{\max}(t) gives exactly one segment, and no other triangle gives one;
  2. LINK partitions these segments into closed loops, where each segment ends at the start of the next one;
  3. the horizontal part of the outward normal of each triangle points to the right of its segment, or the segment has length zero.

Here a vertex counts as above the plane z=Zjz = Z_j when zv≥Zjz_v \ge Z_j and below when zv<Zjz_v < Z_j.

Step 1 (the active list). Fix a triangle tt and let j0j_0 be the bucket of line L4, so j0−1j_0 - 1 is the number of planes with Zi≤zmin⁡(t)Z_i \le z_{\min}(t). Since the heights increase, Zj>zmin⁡(t)Z_j > z_{\min}(t) holds exactly for j≥j0j \ge j_0. The triangle enters AA at step j0j_0 (line L7) and stays until the first step jj with zmax⁡(t)<Zjz_{\max}(t) < Z_j (line L8). It never comes back, because zmax⁡(t)<Zjz_{\max}(t) < Z_j implies zmax⁡(t)<Zj′z_{\max}(t) < Z_{j'} for all j′>jj' > j. So after line L8 of step jj, t∈At \in A if and only if j≥j0j \ge j_0 and Zj≤zmax⁡(t)Z_j \le z_{\max}(t), that is, if and only if zmin⁡(t)<Zj≤zmax⁡(t)z_{\min}(t) < Z_j \le z_{\max}(t). If j0=k+1j_0 = k + 1, the triangle is in the bucket B[k+1]B[k+1], which the loop never reads, and indeed it crosses no plane.

Step 2 (one segment per active triangle). Let t=(a,b,c)t = (a, b, c) be active at step jj. The vertex of height zmin⁡(t)z_{\min}(t) is below and the vertex of height zmax⁡(t)z_{\max}(t) is above, so both labels occur. Go around the cycle a→b→c→aa \to b \to c \to a. The label changes an even number of times, at least once, and at most three times, so exactly twice: once from above to below (the edge eoute_{\text{out}}) and once from below to above (the edge eine_{\text{in}}). So CROSS is well defined, and on each of these two edges the heights of the ends differ, so the crossing point is defined. A triangle that is not active has all three labels equal and gives no segment. This proves part 1.

Step 3 (the successor map). Let EjE_j be the set of edges with one end above and one end below. For every edge e∈Eje \in E_j, both triangles of ee are active, since each has a vertex above and a vertex below. The two triangles traverse ee in opposite directions, so ee goes from above to below in exactly one of them and from below to above in the other. So ee is eoute_{\text{out}} of exactly one segment and eine_{\text{in}} of exactly one segment. Line L12 therefore never writes a key twice, and the keys of SS are exactly EjE_j. Define σ(e)=ein\sigma(e) = e_{\text{in}} of the segment filed under ee. Each e′∈Eje' \in E_j is eine_{\text{in}} of exactly one segment, so σ\sigma is a bijection of the finite set EjE_j, a permutation.

The end point of the segment filed under ee is the crossing point of the edge σ(e)\sigma(e), and the segment filed under σ(e)\sigma(e) starts at the crossing point of the same edge. The crossing point of an edge depends only on the edge and the plane: the formula of line L11 applied from either end gives the same exact point, because a+(b−a)λ=b+(a−b)(1−λ)a + (b - a)\lambda = b + (a - b)(1 - \lambda) with λ=(z−za)/(zb−za)\lambda = (z - z_a)/(z_b - z_a) and 1−λ=(z−zb)/(za−zb)1 - \lambda = (z - z_b)/(z_a - z_b). So each segment ends where its successor starts.

Step 4 (LINK). Each pass of the repeat loop of lines L18 to L20 starts at a key e0e_0 and visits e0,σ(e0),σ2(e0),…e_0, \sigma(e_0), \sigma^2(e_0), \dots, deleting each key it reads. A permutation of a finite set is a union of disjoint cycles, so the sequence returns to e0e_0 after the length ℓ\ell of the cycle of e0e_0, and the keys σ(e0),…,σℓ−1(e0)\sigma(e_0), \dots, \sigma^{\ell-1}(e_0) are different from e0e_0 and from each other. They are all still in SS: a key leaves SS only when it is read, and the keys read in earlier passes belong to other cycles. So line L19 never reads a missing key, the pass stops with e=e0e = e_0, and it has deleted exactly one cycle. Each pass deletes at least one key, so the outer loop stops after at most ∣Ej∣|E_j| passes, and the passes write out every cycle once. By Step 3 consecutive points of a pass are the start and end of one segment, and the last segment ends at the first point. This proves part 2.

Step 5 (orientation). Let tt be active, with the outward normal n=(b−a)×(c−a)n = (b - a) \times (c - a) for its cyclic order (a,b,c)(a, b, c). A cyclic shift does not change nn, so let aa be the vertex that is alone on its side. Write pp and qq for the start and the end of the segment, d=q−pd = q - p, and h=Zjh = Z_j.

Case 1: aa is below and bb, cc are above. Then a→ba \to b goes from below to above, so q=a+s(b−a)q = a + s(b - a), and c→ac \to a goes from above to below, so p=a+r(c−a)p = a + r(c - a), with s,r∈(0,1]s, r \in (0, 1]. Then (q−a)×(p−a)=sr n(q - a) \times (p - a) = s r\, n. Also (q−a)×(p−a)=(q−p+p−a)×(p−a)=d×w(q - a) \times (p - a) = (q - p + p - a) \times (p - a) = d \times w with w=p−aw = p - a. Here dz=0d_z = 0 because pp and qq lie in the plane, and wz=h−za>0w_z = h - z_a > 0. With d=(dx,dy,0)d = (d_x, d_y, 0),

d×w=(dywz,  −dxwz,  dxwy−dywx).d \times w = (d_y w_z,\; -d_x w_z,\; d_x w_y - d_y w_x).

So (nx,ny)=wzsr (dy,−dx)(n_x, n_y) = \frac{w_z}{s r}\,(d_y, -d_x), a positive multiple of dd turned clockwise by a right angle.

Case 2: aa is above and bb, cc are below. Then p=a+s(b−a)p = a + s(b - a) on the edge a→ba \to b, and q=a+r(c−a)q = a + r(c - a) on the edge c→ac \to a, with s,r∈[0,1)s, r \in [0, 1). If za=hz_a = h, then s=r=0s = r = 0, p=q=ap = q = a, and the segment has length zero. Otherwise s,r>0s, r > 0 and (p−a)×(q−a)=sr n(p - a) \times (q - a) = s r\, n. Now (p−a)×(q−a)=w×(q−p)=−d×w(p - a) \times (q - a) = w \times (q - p) = -d \times w with w=p−aw = p - a and wz=h−za<0w_z = h - z_a < 0. So (nx,ny)=−wzsr (dy,−dx)(n_x, n_y) = \frac{-w_z}{s r}\,(d_y, -d_x), again a positive multiple of dd turned clockwise.

In both cases the outward direction lies to the right of dd, so the inside of the solid lies to the left. This proves part 3.

Remark (area). Parts 2 and 3 say that the loops of plane jj are the boundary of the cross-section at height Zj−εZ_j - \varepsilon, traversed with the region on the left. By Green's theorem the sum of their shoelace areas is then the area of that cross-section. This step uses Green's theorem and is not proved here. The tests check the identity exactly on a cube, a tetrahedron and a square frame with a hole, and they check the inside and outside of random sample points against a vertical ray count in the mesh.

Termination. The loops of lines L2 and L6 are over finite lists, line L8 and line L10 scan the finite list AA, and Step 4 shows that LINK stops. ■\blacksquare

Complexity

Lines L1 to L4 take O(nlog⁡k)O(n \log k) time for the binary searches and O(n+k)O(n + k) for the buckets. In the loop of line L6, every triangle is added once. At plane jj, line L8 scans ∣A∣|A| triangles, and each of them is either dropped, which happens once per triangle, or kept and gives a segment. So all scans together take O(n+k+m)O(n + k + m) time. Lines L10 to L22 do O(1)O(1) hash operations per segment. With hashing, each operation takes O(1)O(1) expected time (see universal hashing), so the total is O(nlog⁡k+k+m)O(n \log k + k + m) expected time. With a balanced search tree in place of the hash table, the same steps take O(nlog⁡k+k+mlog⁡m)O(n \log k + k + m \log m) time in the worst case.

When the planes are evenly spaced, Zj=Z1+(j−1) hZ_j = Z_1 + (j - 1)\,h, line L3 is the arithmetic ⌊(zmin⁡−Z1)/h⌋+1\lfloor (z_{\min} - Z_1)/h \rfloor + 1, clamped to the range from 00 to kk, and the first term becomes O(n)O(n). Minetto et al. state O(n+k+m)O(n + k + m) for this case, and also when the triangles come sorted by their lowest vertex. They also prove a lower bound of Ω(nlog⁡k+k+m)\Omega(n \log k + k + m) in the worst case for planes with arbitrary spacing, so the method is asymptotically optimal. The extra space is O(n+k)O(n + k) for the buckets and the active list, and the table SS of one plane holds at most nn entries. The output itself has size O(m)O(m).

Properties

  • Exact. With integer or rational coordinates, every point and every area is exact, also when planes pass through vertices, edges or faces.
  • Closed loops. On a closed, oriented, edge-manifold mesh, every loop is closed, and every segment is in exactly one loop.
  • Oriented. The solid is on the left of every segment. Outer loops are counterclockwise and holes are clockwise as seen from +z+z, so the sum of signed areas is the area of the cross-section.
  • One sided rule. A vertex on the plane counts as above, so the result is the cross-section at Zj−εZ_j - \varepsilon. The plane through the bottom face of a cube gives nothing, and the plane through the top face gives the full square.
  • Output sensitive. The cost depends on mm, not on nkn k.
  • Only one predicate. The topology depends only on comparisons of input heights.

Variants and improvements

  • One plane at a time. The simplest slicer tests every triangle against every plane, in Θ(nk)\Theta(nk) time. It is the brute force that the tests of this page compare against.
  • Sorted triangles. Sorting the triangles by zmin⁡z_{\min} and sweeping gives O(nlog⁡n+k+m)O(n \log n + k + m). The buckets of line L4 replace the sort and give nlog⁡kn \log k in place of nlog⁡nn \log n.
  • Interval structures. Each triangle is the interval [zmin⁡,zmax⁡)[z_{\min}, z_{\max}), and a plane needs all intervals that contain it, a stabbing query in an interval tree or a segment tree. This also allows planes in any order, at a cost of O(log⁡n)O(\log n) per plane.
  • Edge numbers. If the mesh is stored with numbered edges, for example in a doubly connected edge list, the table SS can be an array indexed by the edge number, a direct address table. Resetting only the entries in use gives the bound in the worst case.
  • Meshes from STL. STL files store each triangle with its own three points and no shared indices. Vertex welding must first merge equal points into shared vertices. If the file has gaps or flipped faces, mesh repair and consistent orientation come first, or the loops do not close.
  • Variable layers. Adaptive slicing chooses the heights ZjZ_j from the surface slope. The method of this page then slices at those heights unchanged.

When to use it

Use it to turn a mesh into layer outlines for additive manufacturing, for the planar toolpaths of machining, or for cross-section views. It needs a watertight, consistently oriented mesh with shared vertices. If the mesh may have holes or self-intersections, repair it first, or use a method that does not rely on edge adjacency, such as sampling an inside test on a grid and tracing the result with marching squares. If you need only one plane, test each triangle once and skip the buckets.

Pitfalls

  • Linking by points. Floating point crossing points depend on the direction of the edge, and a vertex on the plane is the end of several segments. Key the table by the edge.
  • Epsilon shifts. Moving every plane by a fixed small number, such as 10−610^{-6}, makes vertex hits rarer but not impossible, and the right value depends on the scale of the model. The symbolic rule handles every case.
  • Rules that differ between triangles. If one triangle counts a vertex as above and its neighbour counts it as below, the loop breaks. The rule must depend on the vertex only.
  • Unwelded meshes. A mesh read from STL has no shared vertices, so the edge keys of neighbouring triangles never match.
  • Wrong orientation. One flipped face reverses its segment, and the successor lookup fails at both of its ends. Check orientation before slicing.
  • Zero-length segments. Faces with a vertex on the plane give repeated points. They are harmless for areas, but they can upset an offset or a toolpath step that expects distinct points.

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.

triangle_mesh_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triangle-mesh-slicing/. The authors are listed in prov/ETJZAW.jsonl.

"""Slice a closed triangle mesh by horizontal planes into closed, oriented contours.

The method is the plane sweep of Minetto, Volpato, Stolfi, Gregori and da Silva
(2017). Each triangle goes into the bucket of the first plane above its lowest
vertex (binary search), the planes are swept from the bottom up with a list of
active triangles, and the segments of one plane are linked into loops with a
hash table keyed by the crossed mesh edge.

Input: vertices as (x, y, z) tuples of int or Fraction, faces as index triples
in counterclockwise order seen from outside (outward normal by the right-hand
rule), and strictly increasing plane heights. The mesh must be closed, oriented
and edge-manifold. A vertex at the height of a plane counts as above it, so the
plane z = Z acts as the plane z = Z - epsilon for a tiny epsilon > 0.

Output: for each plane, a list of loops, each a list of (x, y) points. Outer
loops are counterclockwise seen from above and holes are clockwise.
"""

from bisect import bisect_right
from fractions import Fraction


def crossing(vertices, face, z):
    """Return (e_out, p, e_in) for the face at height z, or None.

    e_out is the edge that goes from above to below in the face order, p its
    crossing point, and e_in the edge that goes from below to above. Edges are
    keys (min index, max index).
    """
    above = [vertices[v][2] >= z for v in face]
    if all(above) or not any(above):
        return None
    e_out = e_in = p = None
    for i in range(3):
        a, b = face[i], face[(i + 1) % 3]
        if above[i] and not above[(i + 1) % 3]:
            e_out, p = (min(a, b), max(a, b)), edge_point(vertices[a], vertices[b], z)
        elif not above[i] and above[(i + 1) % 3]:
            e_in = (min(a, b), max(a, b))
    return e_out, p, e_in


def edge_point(a, b, z):
    """Exact (x, y) where the segment ab meets the plane of height z (a[2] != b[2])."""
    t = Fraction(z - a[2]) / (b[2] - a[2])
    return (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)


def link(segments):
    """Link segments {e_out: (p, e_in)} into loops of points."""
    loops = []  # @line L15
    while segments:  # @line L16
        e0 = next(iter(segments))  # @line L17
        e, loop = e0, []
        while True:  # @line L18
            p, e = segments.pop(e)  # @line L19
            loop.append(p)
            if e == e0:  # @line L20
                break
        loops.append(loop)  # @line L21
    return loops  # @line L22


def slice_mesh(vertices, faces, planes):
    """Return one list of loops for each plane height, in the order of planes."""
    k = len(planes)
    if any(planes[i] >= planes[i + 1] for i in range(k - 1)):
        raise ValueError("plane heights must be strictly increasing")
    zmin = [min(vertices[v][2] for v in f) for f in faces]
    zmax = [max(vertices[v][2] for v in f) for f in faces]
    buckets = [[] for _ in range(k + 1)]  # @line L1
    for t in range(len(faces)):  # @line L2
        j = bisect_right(planes, zmin[t])  # @line L3
        buckets[j].append(t)  # @line L4
    active = []  # @line L5
    result = []
    for j in range(k):  # @line L6
        active.extend(buckets[j])  # @line L7
        active = [t for t in active if zmax[t] >= planes[j]]  # @line L8
        segments = {}  # @line L9
        for t in active:  # @line L10
            e_out, p, e_in = crossing(vertices, faces[t], planes[j])  # @line L11
            segments[e_out] = (p, e_in)  # @line L12
        result.append(link(segments))  # @line L13
    return result  # @line L14


def signed_area(loop):
    """Shoelace signed area of a closed loop of (x, y) points."""
    s = 0
    for i in range(len(loop)):
        (x0, y0), (x1, y1) = loop[i], loop[(i + 1) % len(loop)]
        s += x0 * y1 - x1 * y0
    return Fraction(s) / 2


if __name__ == "__main__":
    cube_v = [(x, y, z) for z in (0, 2) for y in (0, 2) for x in (0, 2)]
    cube_f = [(0, 2, 1), (1, 2, 3), (4, 5, 6), (5, 7, 6), (0, 1, 4), (1, 5, 4),
              (2, 6, 3), (3, 6, 7), (0, 4, 2), (2, 4, 6), (1, 3, 5), (3, 7, 5)]
    for z, loops in zip([0, 1, 2], slice_mesh(cube_v, cube_f, [0, 1, 2])):
        print(z, [[(str(x), str(y)) for x, y in lp] for lp in loops], [str(signed_area(lp)) for lp in loops])
test_triangle_mesh_slicing.py 284 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/triangle-mesh-slicing/. The authors are listed in prov/ETJZAW.jsonl.

import random
from collections import Counter
from fractions import Fraction

import pytest

from triangle_mesh_slicing import crossing, edge_point, signed_area, slice_mesh

# ---- meshes ----


def box(x0, y0, z0, x1, y1, z1):
    v = [(x, y, z) for z in (z0, z1) for y in (y0, y1) for x in (x0, x1)]
    f = [(0, 2, 1), (1, 2, 3), (4, 5, 6), (5, 7, 6), (0, 1, 4), (1, 5, 4),
         (2, 6, 3), (3, 6, 7), (0, 4, 2), (2, 4, 6), (1, 3, 5), (3, 7, 5)]
    return v, f


def tetrahedron():
    v = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
    f = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)]
    return v, f


def ring_solid(rings, cap_low, cap_high, rng=None):
    """Closed mesh from horizontal rings of points around the z axis.

    rings is a list of (z, [(x, y), ...]) with z strictly increasing and the
    points in counterclockwise order. The caps are fans from (0, 0, cap_low)
    and (0, 0, cap_high). If rng is given, each quad gets a random diagonal.
    """
    v, f = [], []
    c = len(rings[0][1])
    for z, pts in rings:
        v.extend((x, y, z) for x, y in pts)
    idx = lambda i, j: i * c + (j % c)
    for i in range(len(rings) - 1):
        for j in range(c):
            a, b, cc, d = idx(i, j), idx(i, j + 1), idx(i + 1, j + 1), idx(i + 1, j)
            if rng is not None and rng.random() < 0.5:
                f += [(a, b, d), (b, cc, d)]
            else:
                f += [(a, b, cc), (a, cc, d)]
    lo, hi = len(v), len(v) + 1
    v += [(0, 0, cap_low), (0, 0, cap_high)]
    top = len(rings) - 1
    for j in range(c):
        f.append((lo, idx(0, j + 1), idx(0, j)))
        f.append((hi, idx(top, j), idx(top, j + 1)))
    return v, f


DIRS = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)]


def random_ring_solid(rng):
    heights = sorted(rng.sample(range(0, 12), 4))
    rings = [(z, [(r * dx, r * dy) for dx, dy in DIRS for r in [rng.randint(1, 4)]]) for z in heights]
    low = heights[0] - rng.randint(0, 2)
    high = heights[-1] + rng.randint(0, 2)
    return ring_solid(rings, low, high, rng)


def frame():
    """Square frame [0,4]^2 minus [1,3]^2, height 2 (a torus, genus 1)."""
    outer = [(0, 0), (4, 0), (4, 4), (0, 4)]
    inner = [(1, 1), (3, 1), (3, 3), (1, 3)]
    v = [(x, y, z) for z in (0, 2) for x, y in outer + inner]
    O = lambda z, j: (0 if z == 0 else 8) + j % 4
    I = lambda z, j: (0 if z == 0 else 8) + 4 + j % 4
    f = []
    for j in range(4):
        f += [(O(0, j), O(0, j + 1), O(2, j + 1)), (O(0, j), O(2, j + 1), O(2, j))]  # outer walls
        f += [(I(0, j + 1), I(0, j), I(2, j)), (I(0, j + 1), I(2, j), I(2, j + 1))]  # inner walls
        f += [(O(2, j), O(2, j + 1), I(2, j + 1)), (O(2, j), I(2, j + 1), I(2, j))]  # top
        f += [(O(0, j + 1), O(0, j), I(0, j)), (O(0, j + 1), I(0, j), I(0, j + 1))]  # bottom
    return v, f


def check_closed_oriented(v, f):
    directed = Counter()
    for a, b, c in f:
        for e in ((a, b), (b, c), (c, a)):
            directed[e] += 1
    assert all(n == 1 for n in directed.values())
    assert all(directed[(b, a)] == 1 for a, b in directed)
    # signed volume by the divergence theorem must be positive
    vol = 0
    for a, b, c in f:
        p, q, r = v[a], v[b], v[c]
        vol += (p[0] * (q[1] * r[2] - q[2] * r[1]) - p[1] * (q[0] * r[2] - q[2] * r[0])
                + p[2] * (q[0] * r[1] - q[1] * r[0]))
    assert vol > 0


# ---- independent checks ----


def brute_segments(v, f, z):
    """Directed segments of every face at height z, without buckets or a sweep."""
    out = Counter()
    for face in f:
        lo = min(v[i][2] for i in face)
        hi = max(v[i][2] for i in face)
        if not (lo < z <= hi):
            continue
        ends = {}
        for i in range(3):
            a, b = face[i], face[(i + 1) % 3]
            sa, sb = v[a][2] >= z, v[b][2] >= z
            if sa != sb:
                ends["out" if sa else "in"] = edge_point(v[a], v[b], z)
        out[(ends["out"], ends["in"])] += 1
    return out


def loop_segments(loops):
    out = Counter()
    for lp in loops:
        for i in range(len(lp)):
            out[(lp[i], lp[(i + 1) % len(lp)])] += 1
    return out


def orient2d(a, b, c):
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def on_segment(p, a, b):
    return (orient2d(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
            and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))


def winding(p, loops):
    w = 0
    for lp in loops:
        for i in range(len(lp)):
            a, b = lp[i], lp[(i + 1) % len(lp)]
            if a[1] <= p[1] < b[1] and orient2d(a, b, p) > 0:
                w += 1
            elif b[1] <= p[1] < a[1] and orient2d(a, b, p) < 0:
                w -= 1
    return w


def inside_by_vertical_ray(v, f, p, z):
    """Parity of the faces above (p, z - eps) on the vertical line through p.

    Returns None if the line meets a face boundary, so the sample is skipped.
    """
    count = 0
    for face in f:
        a, b, c = (v[i] for i in face)
        a2, b2, c2 = a[:2], b[:2], c[:2]
        area = orient2d(a2, b2, c2)
        if any(on_segment(p, s, t) for s, t in ((a2, b2), (b2, c2), (c2, a2))):
            return None
        if area == 0:
            continue
        u, w, x = orient2d(b2, c2, p), orient2d(c2, a2, p), orient2d(a2, b2, p)
        if (u > 0 and w > 0 and x > 0) or (u < 0 and w < 0 and x < 0):
            h = (Fraction(u) * a[2] + Fraction(w) * b[2] + Fraction(x) * c[2]) / area
            if h >= z:
                count += 1
    return count % 2 == 1


# ---- tests ----


def test_page_example_cube():
    v, f = box(0, 0, 0, 2, 2, 2)
    out = slice_mesh(v, f, [0, 1, 2])
    assert out[0] == []
    assert [signed_area(lp) for lp in out[1]] == [4]
    assert [signed_area(lp) for lp in out[2]] == [4]
    assert len(out[1][0]) == 8  # each side face gives one segment


def test_meshes_are_closed_and_oriented():
    for v, f in [box(0, 0, 0, 2, 2, 2), tetrahedron(), frame()]:
        check_closed_oriented(v, f)
    rng = random.Random(5)
    for _ in range(10):
        check_closed_oriented(*random_ring_solid(rng))


def test_tetrahedron_area_exact():
    v, f = tetrahedron()
    zs = [Fraction(i, 7) for i in range(-1, 9)]
    for z, loops in zip(zs, slice_mesh(v, f, zs)):
        want = (1 - z) ** 2 / 2 if 0 < z <= 1 else 0
        assert sum(signed_area(lp) for lp in loops) == want
        assert len(loops) == (1 if 0 < z <= 1 else 0)


def test_frame_has_a_hole():
    v, f = frame()
    out = slice_mesh(v, f, [Fraction(1, 2), 1, 2])
    for loops in out:
        areas = sorted(signed_area(lp) for lp in loops)
        assert areas == [-4, 16]  # hole clockwise, outer counterclockwise
        assert sum(areas) == 12
    # Euler characteristic of the torus
    edges = {tuple(sorted(e)) for a, b, c in f for e in ((a, b), (b, c), (c, a))}
    assert len(v) - len(edges) + len(f) == 0


def test_against_direct_slicing():
    rng = random.Random(11)
    for _ in range(25):
        v, f = random_ring_solid(rng)
        zs = sorted({vz for _, _, vz in v} | {Fraction(rng.randrange(-6, 45), 3) for _ in range(6)})
        out = slice_mesh(v, f, zs)
        for z, loops in zip(zs, out):
            assert loop_segments(loops) == brute_segments(v, f, z)


def test_every_contour_is_closed_and_consistent():
    rng = random.Random(3)
    for _ in range(25):
        v, f = random_ring_solid(rng)
        zs = sorted({vz for _, _, vz in v})  # planes through vertices only
        for z, loops in zip(zs, slice_mesh(v, f, zs)):
            for lp in loops:
                assert len(lp) >= 2
            segs = loop_segments(loops)
            starts = Counter(s for s, _ in segs.elements())
            ends = Counter(e for _, e in segs.elements())
            assert starts == ends  # every point is entered as often as it is left


def test_point_membership_against_vertical_rays():
    rng = random.Random(7)
    checked = 0
    for _ in range(8):
        v, f = random_ring_solid(rng)
        zs = sorted({vz for _, _, vz in v} | {Fraction(rng.randrange(0, 36), 3) for _ in range(3)})
        for z, loops in zip(zs, slice_mesh(v, f, zs)):
            for _ in range(15):
                p = (Fraction(rng.randrange(-4500, 4500), 997), Fraction(rng.randrange(-4500, 4500), 997))
                inside = inside_by_vertical_ray(v, f, p, z)
                if inside is None:
                    continue
                if any(on_segment(p, lp[i], lp[(i + 1) % len(lp)]) for lp in loops for i in range(len(lp))):
                    continue
                assert winding(p, loops) == (1 if inside else 0)
                checked += 1
    assert checked > 500


def test_vertex_on_plane_counts_as_above():
    v, f = tetrahedron()
    face = (0, 1, 3)  # vertices at z = 0, 0, 1
    assert crossing(v, face, 0) is None
    e_out, p, e_in = crossing(v, face, 1)
    assert p == (0, 0)  # both crossing points are the apex
    assert edge_point(v[0], v[3], 1) == (0, 0)


def test_planes_must_increase():
    v, f = box(0, 0, 0, 1, 1, 1)
    with pytest.raises(ValueError):
        slice_mesh(v, f, [1, 1])


def test_float_points_depend_on_edge_direction():
    """Why loops are linked by edge keys and not by rounded points."""
    rng = random.Random(1)
    differ = 0
    for _ in range(2000):
        a = (rng.random(), rng.random(), rng.random())
        b = (rng.random(), rng.random(), rng.random() + 1.0)
        z = rng.uniform(a[2], b[2])
        ta = (z - a[2]) / (b[2] - a[2])
        tb = (z - b[2]) / (a[2] - b[2])
        pa = (a[0] + (b[0] - a[0]) * ta, a[1] + (b[1] - a[1]) * ta)
        pb = (b[0] + (a[0] - b[0]) * tb, b[1] + (a[1] - b[1]) * tb)
        if pa != pb:
            differ += 1
    assert differ > 0

History

Slicers have cut triangle meshes into layers since the first stereolithography machines of the late 1980s, which read the STL format. For a long time the usual method tested each triangle against each plane, or sorted the triangles and swept, and linked the segments by comparing end points. Minetto, Volpato, Stolfi, Gregori and da Silva published the bucket and sweep method in Computer-Aided Design in 2017. They proved the O(nlog⁡k+k+m)O(n \log k + k + m) bound, the matching lower bound, and the linear bound for evenly spaced planes. In 2018 Minetto and Stolfi published a corrigendum that states the bounds of the hash-based loop step as expected time.

References

  1. Rodrigo Minetto, Neri Volpato, Jorge Stolfi, Rodrigo M. M. H. Gregori and Murilo V. G. da Silva, An optimal algorithm for 3D triangle mesh slicing, Computer-Aided Design 92, 2017, 1 to 10, the slicing algorithm with buckets and a sweep, the lower bound, and the linking of segments with a hash table
  2. Rodrigo Minetto and Jorge Stolfi, Corrigendum to An optimal algorithm for 3D triangle mesh slicing, Computer-Aided Design 98, 2018, 39, the correction that the bounds of the loop step hold in expected time
  3. Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the chapter on the generalized additive manufacturing process chain (STL input and slicing)
  4. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, A K Peters, 2010, the chapter on mesh data structures (face sets, shared vertices and halfedges)

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example