Algorithm Search⌘K

Algorithmcore

Adaptive slicing

Also called adaptive layer thickness.

Chooses each layer thickness from the local slope of the surface so the cusp height stays below a bound, thin layers on sloped parts and thick ones elsewhere.

Time
O(L r n) worst
Space
O(n) extra
Where
L = number of layers; n = number of facets; r = number of allowed thicknesses
Properties
deterministicexactiterative
Origin
Atanas Dolenc, Ismo Mäkelä, 1994

Adaptive slicing chooses the thickness of each layer of a printed part from the slope of the surface at that height. On a surface that is close to horizontal, a thick layer leaves a large step, so the layer must be thin. On a vertical wall, the step is zero, so the layer can be as thick as the machine allows. The measure is the cusp height t ∣cos⁡θ∣t\,|\cos\theta| of Dolenc and Mäkelä (1994), where tt is the layer thickness and θ\theta is the angle between the surface normal and the build direction (see staircase effect). The method on this page goes up from the bottom of a triangle mesh and gives each layer the largest allowed thickness for which every facet in the layer has cusp height at most a bound cc. The layers it returns are then cut by triangle mesh slicing.

In plain words

A printer builds a part as a stack of flat layers. Where the surface slopes gently, each layer sticks out past the one above it, and the surface looks like a flight of stairs. Thin layers make small stairs but take a long time to print. Thick layers are fast but rough.

Adaptive slicing uses thin layers only where they help. At each height it looks at the part of the surface that the next layer would cover. It tries the thickest layer first. If any piece of surface in that layer would have a step that is too tall, it tries the next thinner layer, and so on. On steep walls it can use thick layers, and near the top of a dome it uses thin ones.

The problem

The input is a closed triangle mesh with outward facet normals nfn_f (not necessarily of unit length), a finite set of allowed thicknesses t1<t2<⋯<trt_1 < t_2 < \dots < t_r, and a cusp bound c>0c > 0. The build direction is +z+z. The output is a sequence of layer boundaries z0<z1<⋯<zLz_0 < z_1 < \dots < z_L with z0z_0 the lowest point of the mesh, zLz_L at or above the highest point, and each zi−zi−1z_i - z_{i-1} an allowed thickness.

A facet ff lies in the layer from zz to z+tz + t if it meets the open slab z<Z<z+tz < Z < z + t, that is, if zmin⁡(f)<z+tz_{\min}(f) < z + t and zmax⁡(f)>zz_{\max}(f) > z. Its cusp height in that layer is

cusp(f,t)=t ∣cos⁡θf∣=t ∣nf,z∣∥nf∥.\text{cusp}(f, t) = t\,|\cos\theta_f| = t\,\frac{|n_{f,z}|}{\|n_f\|}.

A layer is feasible if every facet in it has cusp(f,t)≤c\text{cusp}(f, t) \le c. Both sides are non-negative, so the test is the same as

t2 nf,z2≤c2 ∥nf∥2,t^2\, n_{f,z}^2 \le c^2\, \|n_f\|^2,

which uses no square root and is exact for integer or rational input. A facet that only touches the slab at zz or at z+tz + t does not count. A horizontal facet that lies at a layer boundary is reproduced exactly, but a horizontal facet strictly inside a layer has cusp height tt.

The algorithm

  1. ADAPTIVE-SLICE(M, T, c) ▷ mesh M, thicknesses t_1 < ... < t_r, bound c
  2. 1z ← zmin(M)
  3. 2while z < zmax(M) do
  4. 3t ← t_1 ▷ fallback if nothing is feasible
  5. 4for s ← t_r, t_(r-1), ..., t_1 do
  6. 5if FEASIBLE(z, s) then t ← s; break
  7. 6z ← z + t; output z ▷ one layer from z − t to z
  8. 7return the outputs
  9. FEASIBLE(z, s)
  10. 8for each facet f with normal n do
  11. 9if zmin(f) < z + s and zmax(f) > z and s² n_z² > c² |n|² then
  12. 10return false
  13. 11return true

Line L4 tries the thicknesses from the largest down. Line L5 stops at the first feasible one, which is the largest feasible one, because feasibility is monotone in the thickness (see Correctness). If even t1t_1 is not feasible, for example because a horizontal facet lies inside the layer and t1>ct_1 > c, line L3 keeps t1t_1. The layer then breaks the bound, and a slicer should report it. The last layer can end above the top of the part.

Exact arithmetic. The only decision is the comparison of line L9. With integer or rational vertices, the normal nn is exact, and so are nz2n_z^2 and ∥n∥2\|n\|^2. In floating point, the usual code computes ∣cos⁡θ∣=∣nz∣/∥n∥|\cos\theta| = |n_z| / \|n\| with a square root and compares t ∣cos⁡θ∣t\,|\cos\theta| with cc. When the two sides are equal or nearly equal, as for a facet whose slope exactly allows a given thickness, rounding can pick the next thinner layer or accept a layer that breaks the bound by one rounding error. The squared form decides these ties exactly.

Example

Take a house: the box [0,4]×[0,4]×[0,2][0, 4] \times [0, 4] \times [0, 2] with a pyramid roof whose apex is (2,2,3)(2, 2, 3), as 14 triangles. The allowed thicknesses are 14,12,1\tfrac14, \tfrac12, 1, and c=14c = \tfrac14. The walls have nz=0n_z = 0. The bottom face is horizontal at z=0z = 0 and never lies inside a slab. A roof facet such as (0,0,2),(4,0,2),(2,2,3)(0, 0, 2), (4, 0, 2), (2, 2, 3) has n=(0,−4,8)n = (0, -4, 8), so nz2=64n_z^2 = 64, ∥n∥2=80\|n\|^2 = 80 and ∣cos⁡θ∣=2/5≈0.894|\cos\theta| = 2/\sqrt5 \approx 0.894.

zz ss tried facets in the slab test of line L9 layer
00 11 walls 0≤116⋅640 \le \tfrac1{16} \cdot 64 00 to 11
11 11 walls (the roof starts at z=2z = 2, so it does not meet (1,2)(1, 2)) holds 11 to 22
22 11 walls, roof 1⋅64=64>116⋅80=51 \cdot 64 = 64 > \tfrac1{16} \cdot 80 = 5 no
22 12\tfrac12 walls, roof 14⋅64=16>5\tfrac14 \cdot 64 = 16 > 5 no
22 14\tfrac14 walls, roof 116⋅64=4≤5\tfrac1{16} \cdot 64 = 4 \le 5 22 to 94\tfrac94
94\tfrac94, 52\tfrac52, 114\tfrac{11}4 11, 12\tfrac12, 14\tfrac14 roof as at z=2z = 2 three layers of 14\tfrac14

The output is 1,2,94,52,114,31, 2, \tfrac94, \tfrac52, \tfrac{11}4, 3: six layers. The cusp height on the roof is 14⋅0.894≈0.224≤0.25\tfrac14 \cdot 0.894 \approx 0.224 \le 0.25. Uniform layers of 14\tfrac14 would need 12 layers for the same bound, and uniform layers of 1 would need 3 layers but leave a cusp of 0.8940.894 on the roof.

On a mesh of a sphere of radius 10 with 168 facets and all vertices exactly on the sphere (rational points), with c=120c = \tfrac1{20} and the thicknesses 120,110,15,310\tfrac1{20}, \tfrac1{10}, \tfrac15, \tfrac3{10}, the code of this page returns 243 layers: 160 of 120\tfrac1{20} near the poles, 64 of 110\tfrac1{10}, one of 15\tfrac15 and 18 of 310\tfrac3{10} near the equator. Uniform layers of 120\tfrac1{20} would need 400. This is a measurement on one toy mesh, not a general ratio.

Correctness

Monotonicity. If the layer from zz with thickness ss is feasible and s′<ss' < s, then the layer from zz with thickness s′s' is feasible. The open slab (z,z+s′)(z, z + s') is inside (z,z+s)(z, z + s), so it meets fewer facets, and each of them has s′2nz2≤s2nz2≤c2∥n∥2s'^2 n_z^2 \le s^2 n_z^2 \le c^2 \|n\|^2.

Each layer. FEASIBLE(z,s)(z, s) returns true exactly when no facet meets the open slab with a cusp height above cc, because line L9 is the exact squared form of the definition. Line L4 tries the thicknesses in decreasing order, and line L5 stops at the first feasible one. So the chosen tt is the largest feasible thickness. If none is feasible, then t=t1t = t_1, and by monotonicity no thickness smaller than t1t_1 would have helped among the allowed ones.

Termination. Each pass of line L2 adds at least t1>0t_1 > 0 to zz, so the loop stops after at most ⌈(zmax⁡−zmin⁡)/t1⌉\lceil (z_{\max} - z_{\min}) / t_1 \rceil layers, and the last output is at or above zmax⁡z_{\max}.

So every layer has cusp height at most cc on every facet in it, except the layers of thickness t1t_1 where no allowed thickness meets the bound, and each layer is as thick as the bound allows at its start. The full proof is below.

Not a minimum. The greedy rule does not always give the fewest layers, because the problem lacks the greedy choice property: a thinner layer now can put the next layer start at a better height. Take thicknesses 1,2,41, 2, 4, c=1c = 1, a part of height 9 with vertical walls and two bands of facets with ∣cos⁡θ∣=13|\cos\theta| = \tfrac13 at heights 2 to 3 and 7 to 8. A layer of 4 that meets a band has cusp 43>1\tfrac43 > 1. Greedy takes 2,2,2,2,42, 2, 2, 2, 4, which is 5 layers. The sequence 2,1,4,22, 1, 4, 2 is feasible: the layer from 3 to 7 meets neither band, since both only touch its boundary. It has 4 layers. The tests find such cases by comparing the greedy count with an exhaustive search.

Proof: Greedy adaptive slicing keeps the cusp bound in every feasible layer and stopsfull

Claim. Let MM be a triangle mesh with exact (integer or rational) vertices, let 0<t1<⋯<tr0 < t_1 < \dots < t_r be the allowed thicknesses and let c>0c > 0. For a height zz and a thickness ss, call the layer (z,s)(z, s) feasible if every facet ff with zmin⁡(f)<z+sz_{\min}(f) < z + s and zmax⁡(f)>zz_{\max}(f) > z has s ∣nf,z∣/∥nf∥≤cs\,|n_{f,z}| / \|n_f\| \le c. Then ADAPTIVE-SLICE(M,T,c)(M, T, c) stops after at most ⌈(zmax⁡(M)−zmin⁡(M))/t1⌉\lceil (z_{\max}(M) - z_{\min}(M)) / t_1 \rceil layers, the last output is at least zmax⁡(M)z_{\max}(M), and each layer (z,t)(z, t) that it outputs satisfies:

  1. if some allowed thickness gives a feasible layer at zz, then tt is the largest such thickness, and the layer (z,t)(z, t) is feasible;
  2. otherwise t=t1t = t_1.

Step 1 (the test is exact). For a facet with normal n≠0n \ne 0 and s>0s > 0, both s ∣nz∣/∥n∥s\,|n_z| / \|n\| and cc are non-negative. For non-negative reals aa and bb, a≤ba \le b if and only if a2≤b2a^2 \le b^2. So s ∣nz∣/∥n∥≤cs\,|n_z| / \|n\| \le c if and only if s2nz2≤c2∥n∥2s^2 n_z^2 \le c^2 \|n\|^2, after multiplying by ∥n∥2>0\|n\|^2 > 0. Both sides are polynomials in the exact input, so line L9 decides the condition without error. Line L9 also checks the slab condition exactly as in the definition. So FEASIBLE(z,s)(z, s) returns false if and only if some facet in the open slab breaks the bound, that is, if and only if the layer (z,s)(z, s) is not feasible. (A facet with n=0n = 0, a degenerate triangle, has nz=0n_z = 0 and ∥n∥=0\|n\| = 0, so line L9 never rejects it, which is the right answer for a facet of zero area.)

Step 2 (monotonicity). Let (z,s)(z, s) be feasible and 0<s′<s0 < s' < s. A facet in the slab (z,z+s′)(z, z + s') has zmin⁡(f)<z+s′<z+sz_{\min}(f) < z + s' < z + s and zmax⁡(f)>zz_{\max}(f) > z, so it is also in the slab (z,z+s)(z, z + s). Then s′2nz2≤s2nz2≤c2∥n∥2s'^2 n_z^2 \le s^2 n_z^2 \le c^2 \|n\|^2. So (z,s′)(z, s') is feasible. In other words, the set of allowed thicknesses that are feasible at zz is {t1,…,tq}\{t_1, \dots, t_q\} for some q∈{0,…,r}q \in \{0, \dots, r\}.

Step 3 (one layer). Fix one pass of the loop of line L2, with current height zz. Lines L4 and L5 call FEASIBLE with tr,tr−1,…t_r, t_{r-1}, \dots in this order and stop at the first true answer. By Steps 1 and 2, the calls return false for tr,…,tq+1t_r, \dots, t_{q+1} and true for tqt_q if q≥1q \ge 1. So if q≥1q \ge 1, the pass sets t=tqt = t_q, the largest feasible thickness, and the layer (z,tq)(z, t_q) is feasible. If q=0q = 0, no call returns true, and tt keeps the value t1t_1 of line L3. This proves parts 1 and 2 for this layer.

Step 4 (termination and cover). Let z(0)=zmin⁡(M)z^{(0)} = z_{\min}(M) and let z(i)z^{(i)} be the value of zz after ii passes. Each pass adds an allowed thickness, so z(i)≥z(0)+i t1z^{(i)} \ge z^{(0)} + i\, t_1. The loop runs only while z<zmax⁡(M)z < z_{\max}(M). So if ii passes have run, then z(i−1)<zmax⁡(M)z^{(i-1)} < z_{\max}(M), and z(0)+(i−1)t1<zmax⁡(M)z^{(0)} + (i - 1) t_1 < z_{\max}(M), which gives i<(zmax⁡−zmin⁡)/t1+1i < (z_{\max} - z_{\min}) / t_1 + 1, that is i≤⌈(zmax⁡−zmin⁡)/t1⌉i \le \lceil (z_{\max} - z_{\min}) / t_1 \rceil. When the loop stops, z≥zmax⁡(M)z \ge z_{\max}(M), so the last output is at least zmax⁡(M)z_{\max}(M). If zmax⁡(M)=zmin⁡(M)z_{\max}(M) = z_{\min}(M), the loop does not run, and the output is empty, which is correct for a flat mesh. Each call of FEASIBLE scans a finite list, so each pass stops. ■\blacksquare

Complexity

FEASIBLE scans all nn facets in O(n)O(n) time. Each layer calls it at most rr times, so the total time is O(Lrn)O(L r n), with ⌈H/tr⌉≤L≤⌈H/t1⌉\lceil H / t_r \rceil \le L \le \lceil H / t_1 \rceil for the height HH of the part. The extra space is O(n)O(n) for the heights and the squared normals of the facets.

Two changes make it faster. Sort the facets by zmin⁡z_{\min} and keep an active list, as in triangle mesh slicing, so that FEASIBLE looks only at the facets near zz. And give each facet its own largest allowed thickness, the largest tit_i with ti2nz2≤c2∥n∥2t_i^2 n_z^2 \le c^2 \|n\|^2. Then a layer of thickness ss is feasible if ss is at most the minimum of these values over the facets in the slab, which a sweep can maintain.

Properties

  • Bound per layer. Every layer meets the cusp bound unless no allowed thickness does, and then it has the smallest thickness.
  • Largest step. Each layer is the thickest feasible layer at its start.
  • Not minimal. The number of layers is not always the minimum (see the example above).
  • Exact. The only test is an exact comparison of squared integers or rationals.
  • Uses only normals. The test looks at facet normals and heights, not at the true curvature of the design surface.

Variants and improvements

  • Fewest layers. If all thicknesses are multiples of a unit qq, the heights that a layer can start at are zmin⁡+jqz_{\min} + jq. Dynamic programming over these heights, from the top down, by the principle of optimality, gives the fewest feasible layers in O((H/q) r n)O((H/q)\, r\, n) time. The tests of this page use this as the exhaustive reference.
  • Stepwise uniform refinement. Sabourin, Houser and Bøhn (1996) slice first at the largest thickness and then reslice each thick slab uniformly into thinner layers where the surface needs it.
  • Local adaptive slicing. Tyberg and Bøhn (1998) let different parts of the same layer have different thicknesses, so a steep part next to a flat part does not force thin layers on both.
  • Other error measures. Some methods bound the area or the volume between the staircase and the surface, not the cusp height. Others use the curvature of the CAD surface, see surface curvature, so that the thickness changes before a slope change, not after.
  • Machine limits. Real printers have a range of thicknesses and can have rules on how fast the thickness can change from one layer to the next. These add constraints to line L4.

When to use it

Use it when a part has both steep walls and gentle slopes, and print time matters. On a part that is all vertical walls, uniform thick layers are as good. On a part that is all gentle slopes, adaptive slicing gives thin layers everywhere and saves little. The cusp height is a geometric measure. It does not include the rounding of the edges of real beads, so it is an upper bound on one kind of surface error, not a model of the printed surface. The choice of build orientation changes the slopes, so the two decisions interact.

Pitfalls

  • Facets that only touch the slab. A facet whose top is at zz does not lie in the layer above zz. With a closed slab, every layer would see the facets of the layer below, and the thickness would drop one layer too early.
  • Horizontal facets. A horizontal face inside a layer has cusp height tt. If t1>ct_1 > c, no thickness works there. The fallback must be visible to the user.
  • Square roots in the test. Ties between t ∣cos⁡θ∣t\,|\cos\theta| and cc are common, because both come from round numbers. Compare the squares.
  • Small sloped facets. A tiny facet with a gentle slope forces a thin layer, even if it is a meshing artifact. Clean or merge such facets first, or weight the test by facet area.
  • The last layer. It can go above the top of the part. Either accept that or let the last layer be thinner if the machine allows it.

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.

adaptive_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-slicing/. The authors are listed in prov/BT4MQH.jsonl.

"""Adaptive slicing with a cusp height bound.

Each layer of thickness t on a facet with unit normal n leaves a cusp of height
t |n_z| (Dolenc and Makela 1994). The method goes up from the bottom of the
mesh and gives each layer the largest allowed thickness for which every facet
that meets the open slab of the layer has cusp height at most c. If no allowed
thickness works, it uses the smallest one.

All tests are exact: with an integer or Fraction normal n, the condition
t |n_z| / |n| <= c is t^2 n_z^2 <= c^2 |n|^2.
"""

from fractions import Fraction


def facet_data(vertices, faces):
    """Return (zmin, zmax, nz^2, |n|^2) for each face, with n the cross product."""
    out = []
    for a, b, c in faces:
        p, q, r = vertices[a], vertices[b], vertices[c]
        u = (q[0] - p[0], q[1] - p[1], q[2] - p[2])
        w = (r[0] - p[0], r[1] - p[1], r[2] - p[2])
        n = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
        zs = (p[2], q[2], r[2])
        out.append((min(zs), max(zs), n[2] * n[2], n[0] * n[0] + n[1] * n[1] + n[2] * n[2]))
    return out


def feasible(facets, z, t, c):
    """True if every facet that meets the open slab (z, z + t) has cusp height <= c."""
    for lo, hi, nz2, nn in facets:  # @line L8
        if lo < z + t and hi > z and t * t * nz2 > c * c * nn:  # @line L9
            return False  # @line L10
    return True  # @line L11


def adaptive_slice(vertices, faces, thicknesses, c):
    """Return the layer tops z_1 < z_2 < ... for the mesh, from its lowest point up.

    thicknesses: allowed layer thicknesses (positive int or Fraction).
    c: cusp height bound (positive int or Fraction).
    """
    ts = sorted(set(Fraction(t) for t in thicknesses))
    if not ts or ts[0] <= 0 or c <= 0:
        raise ValueError("thicknesses and the cusp bound must be positive")
    facets = facet_data(vertices, faces)
    zlo = min(v[2] for v in vertices)
    zhi = max(v[2] for v in vertices)
    z = Fraction(zlo)  # @line L1
    tops = []
    while z < zhi:  # @line L2
        t = ts[0]  # @line L3
        for s in reversed(ts):  # @line L4
            if feasible(facets, z, s, c):  # @line L5
                t = s
                break
        z = z + t  # @line L6
        tops.append(z)
    return tops  # @line L7


def max_cusp_ratio(facets, z, t):
    """Largest t^2 nz^2 / |n|^2 over the facets in the open slab (the squared cusp height)."""
    best = Fraction(0)
    for lo, hi, nz2, nn in facets:
        if lo < z + t and hi > z:
            best = max(best, Fraction(t * t * nz2, 1) / nn)
    return best


if __name__ == "__main__":
    v = [(0, 0, 0), (4, 0, 0), (4, 4, 0), (0, 4, 0), (0, 0, 2), (4, 0, 2), (4, 4, 2), (0, 4, 2), (2, 2, 3)]
    f = [(0, 2, 1), (0, 3, 2), (0, 1, 5), (0, 5, 4), (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6),
         (3, 0, 4), (3, 4, 7), (4, 5, 8), (5, 6, 8), (6, 7, 8), (7, 4, 8)]
    tops = adaptive_slice(v, f, [Fraction(1, 4), Fraction(1, 2), 1], Fraction(1, 4))
    print([str(z) for z in tops])
test_adaptive_slicing.py 224 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-slicing/. The authors are listed in prov/BT4MQH.jsonl.

import math
import random
from fractions import Fraction as F
from functools import lru_cache

import pytest

from adaptive_slicing import adaptive_slice, facet_data, feasible, max_cusp_ratio

# ---- meshes ----


def ring_solid(rings, cap_low, cap_high):
    """Closed mesh from rings (z, [(x, y), ...]) with z increasing, counterclockwise points."""
    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)
            f += [(a, b, cc), (a, cc, d)]
    lo, hi = len(v), len(v) + 1
    v += [cap_low, 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


def circle_points():
    ws = [F(0), F(1, 4), F(1, 2), F(1), F(2), F(4), None, F(-4), F(-2), F(-1), F(-1, 2), F(-1, 4)]
    pts = []
    for w in ws:
        if w is None:
            pts.append((F(-1), F(0)))
        else:
            pts.append(((1 - w * w) / (1 + w * w), 2 * w / (1 + w * w)))
    return pts


def rational_sphere(radius):
    """Vertices exactly on the sphere x^2 + y^2 + z^2 = radius^2."""
    rings = []
    for u in [F(4), F(2), F(4, 3), F(1), F(3, 4), F(1, 2), F(1, 4)]:  # z increases
        z, rho = (1 - u * u) / (1 + u * u), 2 * u / (1 + u * u)
        rings.append((radius * z, [(radius * rho * x, radius * rho * y) for x, y in circle_points()]))
    return ring_solid(rings, (0, 0, -radius), (0, 0, radius))


def cone(radius, height):
    pts = circle_points()
    rings = [(0, [(radius * x, radius * y) for x, y in pts])]
    return ring_solid(rings, (0, 0, 0), (0, 0, height))


def roof_house():
    v = [(0, 0, 0), (4, 0, 0), (4, 4, 0), (0, 4, 0), (0, 0, 2), (4, 0, 2), (4, 4, 2), (0, 4, 2), (2, 2, 3)]
    f = [(0, 2, 1), (0, 3, 2), (0, 1, 5), (0, 5, 4), (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6),
         (3, 0, 4), (3, 4, 7), (4, 5, 8), (5, 6, 8), (6, 7, 8), (7, 4, 8)]
    return v, f


# ---- independent checks ----


def cusp_ok_brute(vertices, faces, z, t, c):
    """Direct check of every face: the cusp t |cos theta| is at most c.

    The normal is computed at a different corner, (c - b) x (a - b), and the
    slab test uses the vertex heights directly.
    """
    for i, j, k in faces:
        a, b, cc = vertices[i], vertices[j], vertices[k]
        zs = [a[2], b[2], cc[2]]
        if not (min(zs) < z + t and max(zs) > z):
            continue
        u = [cc[m] - b[m] for m in range(3)]
        w = [a[m] - b[m] for m in range(3)]
        n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]
        if t * t * n[2] * n[2] > c * c * sum(x * x for x in n):
            return False
    return True


def check_layers(vertices, faces, ts, c, tops):
    ts = sorted(F(t) for t in ts)
    z = F(min(p[2] for p in vertices))
    zhi = max(p[2] for p in vertices)
    assert tops[-1] >= zhi and (len(tops) == 1 or tops[-2] < zhi)
    for top in tops:
        t = top - z
        assert t in ts
        larger = [s for s in ts if s > t]
        if cusp_ok_brute(vertices, faces, z, t, c):
            for s in larger:  # the choice is the largest feasible one
                assert not cusp_ok_brute(vertices, faces, z, s, c)
        else:
            assert t == ts[0]  # fallback only when nothing is feasible
            assert not any(cusp_ok_brute(vertices, faces, z, s, c) for s in ts)
        z = top


# ---- tests ----


def test_page_example_house():
    v, f = roof_house()
    tops = adaptive_slice(v, f, [F(1, 4), F(1, 2), 1], F(1, 4))
    assert tops == [1, 2, F(9, 4), F(5, 2), F(11, 4), 3]
    check_layers(v, f, [F(1, 4), F(1, 2), 1], F(1, 4), tops)
    # roof normal (0, -4, 8): t = 1/2 fails, t = 1/4 holds
    assert F(1, 2) ** 2 * 64 > F(1, 4) ** 2 * 80
    assert F(1, 4) ** 2 * 64 <= F(1, 4) ** 2 * 80


def test_sphere_cusp_bound_holds():
    v, f = rational_sphere(10)
    assert all(x * x + y * y + z * z == 100 for x, y, z in v)
    ts = [F(1, 20), F(1, 10), F(1, 5), F(3, 10)]
    c = F(1, 20)
    tops = adaptive_slice(v, f, ts, c)
    check_layers(v, f, ts, c, tops)
    facets = facet_data(v, f)
    z = F(-10)
    for top in tops:
        assert max_cusp_ratio(facets, z, top - z) <= c * c
        z = top
    thick = [b - a for a, b in zip([F(-10)] + tops, tops)]
    assert min(thick) == F(1, 20) and max(thick) == F(3, 10)  # thin near the poles, thick at the equator
    assert len(tops) < 20 * 20  # fewer layers than uniform slicing with t = 1/20


def test_cone_cusp_bound_holds():
    v, f = cone(6, 8)
    ts = [F(1, 10), F(1, 5), F(3, 10), F(2, 5)]
    for c in [F(1, 10), F(3, 20), F(1, 4)]:
        tops = adaptive_slice(v, f, ts, c)
        check_layers(v, f, ts, c, tops)


def test_fallback_to_thinnest_layer():
    v, f = roof_house()
    tops = adaptive_slice(v, f, [F(1, 2), 1], F(1, 10))
    check_layers(v, f, [F(1, 2), 1], F(1, 10), tops)
    assert tops == [1, 2, F(5, 2), 3]


def test_horizontal_face_inside_a_layer():
    # a box from z = 0 to z = 1: its top face lies inside the slab (0, 2)
    v = [(x, y, z) for z in (0, 1) for y in (0, 1) for x in (0, 1)]
    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)]
    facets = facet_data(v, f)
    assert not feasible(facets, 0, 2, F(1, 4))  # the top face is inside (0, 2)
    assert feasible(facets, 0, 1, F(1, 4))  # but on the boundary of (0, 1)
    assert adaptive_slice(v, f, [F(1, 2), 1, 2], F(1, 4)) == [1]


def greedy_count(facets, ts, c, zlo, zhi):
    z, n = zlo, 0
    while z < zhi:
        t = ts[0]
        for s in reversed(ts):
            if feasible(facets, z, s, c):
                t = s
                break
        z, n = z + t, n + 1
    return n


def optimum_count(facets, ts, c, zlo, zhi):
    @lru_cache(maxsize=None)
    def best(z):
        if z >= zhi:
            return 0
        return 1 + min(best(z + s) for s in ts if s == ts[0] or feasible(facets, z, s, c))

    return best(zlo)


def test_greedy_is_not_always_minimal():
    # two bands with |cos theta| = 1/3 at heights 2 to 3 and 7 to 8, walls elsewhere
    facets = [(0, 9, 0, 1), (2, 3, 1, 9), (7, 8, 1, 9)]
    ts, c = [1, 2, 4], 1
    assert greedy_count(facets, ts, c, 0, 9) == 5  # 2, 2, 2, 2, 4
    assert optimum_count(facets, ts, c, 0, 9) == 4  # 2, 1, 4, 2


def test_greedy_against_exhaustive_minimum():
    rng = random.Random(4)
    worse = 0
    for _ in range(3000):
        ts = rng.choice([[1, 2], [1, 3], [1, 2, 4], [2, 3, 5]])
        hi = rng.randint(3, 12)
        facets = [(0, hi, 0, 1)]
        for _ in range(rng.randint(1, 4)):
            lo = rng.randint(0, hi - 1)
            facets.append((lo, rng.randint(lo + 1, min(hi, lo + 3)), 1, rng.choice([1, 4, 9, 16, 25])))
        g = greedy_count(facets, ts, 1, 0, hi)
        o = optimum_count(facets, ts, 1, 0, hi)
        assert g >= o
        worse += g > o
    assert worse > 0


def test_float_cusp_matches_exact_on_sphere():
    v, f = rational_sphere(10)
    for lo, hi, nz2, nn in facet_data(v, f):
        cos_float = abs(math.sqrt(float(nz2) / float(nn)))
        assert abs(cos_float ** 2 - float(F(nz2) / nn)) < 1e-12


def test_bad_parameters():
    v, f = roof_house()
    with pytest.raises(ValueError):
        adaptive_slice(v, f, [], F(1, 4))
    with pytest.raises(ValueError):
        adaptive_slice(v, f, [F(1, 4)], 0)

History

Dolenc and Mäkelä published the cusp height and an adaptive choice of the layer thickness in Computer-Aided Design in 1994. Sabourin, Houser and Bøhn published stepwise uniform refinement in the Rapid Prototyping Journal in 1996, and Tyberg and Bøhn published local adaptive slicing in the same journal in 1998. Later work changed the error measure and the source of the slope (the mesh or the exact CAD surface), and many current slicers have an adaptive layer height option.

References

  1. Atanas Dolenc and Ismo Mäkelä, Slicing procedures for layered manufacturing techniques, Computer-Aided Design 26(2), 1994, 119 to 126, the definition of the cusp height and the choice of the layer thickness from it
  2. Emmanuel Sabourin, Scott A. Houser and Jan Helge Bøhn, Adaptive slicing using stepwise uniform refinement, Rapid Prototyping Journal 2(4), 1996, 20 to 26, the method that slices at the largest thickness and then reslices the slabs that need it
  3. Justin Tyberg and Jan Helge Bøhn, Local adaptive slicing, Rapid Prototyping Journal 4(3), 1998, 118 to 127, the layer thickness chosen separately for each part of a layer
  4. Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the chapters on the process chain and on design for additive manufacturing (layer thickness and stair stepping)

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.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