Algorithm Search⌘K

Algorithmadvanced

Tree support generation

Also called branching supports.

Builds supports as trees that start at the overhang points and merge downward within the critical angle, as in Vanek and coauthors, which saves material.

Time
O(n^2 log n) worst
Space
O(n^2) extra
Where
n = number of points that need support
Properties
deterministicexactiterative
Origin
Juraj Vanek, Jorge A. Garcia Galicia, Bedrich Benes, 2014

Tree support generation builds the supports of a 3D print as trees. Each point of the part that needs support is a leaf. Branches go down from the leaves, merge where they meet, and end in a few trunks on the build plate. Each branch is a straight strut that is no more tilted than the printer can build, so the struts themselves need no support. Compared with a vertical pillar under each point, a tree uses much less material. The method was made popular by the Clever Support paper of Vanek, Garcia Galicia and Benes (2014). Its main step is a sweep from the top down: the two points whose support cones meet highest are merged first, at the point where their cones meet. This page gives that greedy merge with exact arithmetic, for supports that stand on the plate. It solves one form of the support structure generation problem heuristically, with no claim of optimal length.

In plain words

Some parts of a print hang over empty space, and the printer cannot put material on air. So each such point needs something below it. The simple answer is a straight pillar from the point to the plate. That works, but it uses a lot of material if there are many points.

A printer can build a strut that leans a little, up to a limit. So the support of a point can be any strut inside an upside-down cone below it. If the cones of two points meet, both points can share one strut below the meeting point, like two branches of a tree. Start at the top and always join the two branches that can meet highest, as long as this saves material. At the end, every branch that is still alone goes straight down to the plate.

The problem

The input is a set of points p1,…,pnp_1, \dots, p_n with z>0z > 0 that need support, and a cone slope k>0k > 0. A strut from aa down to bb is allowed if az>bza_z > b_z and its horizontal length is at most k (az−bz)k\,(a_z - b_z). The slope k=tan⁡βk = \tan\beta comes from the largest angle β\beta from the vertical that the printer can build without support. For material extrusion a common rule of thumb is β=45∘\beta = 45^\circ, so k=1k = 1. It is a rule of thumb, not a law, and it depends on the material, the speed and the cooling.

The output is a set of nodes, which includes the input points, and a set of allowed struts. Each node has at most one strut below it, and the path of struts down from each input point ends on the plate z=0z = 0. The cost is the total length of the struts. Here the struts may cross the part: this version does not test them against the mesh. Real supports must avoid the part or land on it, see the variants below.

Which points need support. The points come from the mesh of the part. A facet with outward normal nn faces down if nz<0n_z < 0. It is tilted from the horizontal by the angle φ\varphi with cos⁡φ=−nz/∥n∥\cos\varphi = -n_z / \|n\|, and it needs support if φ<90∘−β\varphi < 90^\circ - \beta, that is, if

nz<0andnz2>sin⁡2 ⁣β  ∥n∥2.n_z < 0 \quad\text{and}\quad n_z^2 > \sin^2\!\beta\; \|n\|^2.

For β=45∘\beta = 45^\circ this is 2nz2>∥n∥22 n_z^2 > \|n\|^2, an exact test on integers. A facet at exactly 45∘45^\circ passes as self-supporting. The code samples each overhang facet on a grid of barycentric points, and it adds every vertex that is strictly lower than all its neighbours, because such a point starts a new island in the layer where it appears. Points on the plate need nothing.

The algorithm

MERGE(p,q)(p, q), for pz≥qzp_z \ge q_z, finds the highest point mm that lies in both cones. Let DD be the horizontal distance of pp and qq. If D≤k (pz−qz)D \le k\,(p_z - q_z), then qq lies in the cone of pp, and the highest common point is qq itself. Otherwise the cones meet first on the vertical plane through pp and qq, at horizontal distance s=(k(pz−qz)+D)/2s = (k(p_z - q_z) + D)/2 from pp and at height (pz+qz−D/k)/2(p_z + q_z - D/k)/2.

  1. TREE-SUPPORT(P, k) ▷ points P that need support, cone slope k
  2. 1A ← P; E ← empty ▷ active points, struts
  3. 2H ← max-heap of MERGE(p, q) for the pairs of A that save length
  4. 3while H is not empty do
  5. 4(m, p, q) ← extract the event with the highest m_z
  6. 5if p ∉ A or q ∉ A then continue ▷ stale event
  7. 6remove p and q from A
  8. 7if m = q then add strut (p, q) to E ▷ q lies in the cone of p
  9. 8else add struts (p, m) and (q, m) to E ▷ reuse m if it is already in A
  10. 9add m to A
  11. 10for each r ∈ A with r ≠ m do
  12. 11if MERGE(m, r) saves length then insert it into H
  13. 12for each p ∈ A do add strut (p, (p_x, p_y, 0)) to E ▷ trunks to the plate
  14. 13return E
  15. MERGE(p, q) ▷ p_z ≥ q_z
  16. 14D ← horizontal distance of p and q
  17. 15if D ≤ k (p_z − q_z) then return (q, |p − q| < p_z)
  18. 16s ← (k (p_z − q_z) + D) / 2
  19. 17m_xy ← p_xy + (q_xy − p_xy) · s / D, rounded to a fine grid
  20. 18m_z ← min(p_z − |m − p|_xy / k, q_z − |m − q|_xy / k)
  21. 19saves ← m_z > 0 and |p − m| + |q − m| + m_z < p_z + q_z
  22. 20return (m, saves)

The test "saves length" compares the struts of a merge with the cheapest way to finish both points, two trunks of lengths pzp_z and qzq_z. In the case of line L15, pp goes to qq, and qq still needs its own support, so the test is ∣p−q∣<pz|p - q| < p_z. The heap holds events for pairs, and line L5 skips events whose points were already merged. Each merge happens at the height of its event, and a new point mm can only merge lower than mzm_z, because any common point lies in the cone of mm. So the events come out in decreasing height, which is the sweep of a horizontal plane from the top down.

Exact arithmetic. The horizontal distances are square roots, so they are not rational. Line L17 rounds mm to a grid, and line L18 then sets mzm_z with an upper bound of each square root (from math.isqrt) in place of the root. This lowers mm a little, and it keeps mm exactly inside both cones, so every strut is allowed. Line L19 compares a sum of two square roots with a rational C=pz+qz−mzC = p_z + q_z - m_z exactly: A+B<C\sqrt{A} + \sqrt{B} < C holds if and only if C>0C > 0, C2−A−B>0C^2 - A - B > 0 and 4AB<(C2−A−B)24AB < (C^2 - A - B)^2. A test in floating point can accept a merge that makes the tree longer when the two sides are almost equal, or reject a strut that is exactly at the limit angle.

Example

Take k=1k = 1 and the points a=(0,0,6)a = (0, 0, 6), b=(4,0,6)b = (4, 0, 6), c=(3,0,3)c = (3, 0, 3) and d=(12,0,4)d = (12, 0, 4). Vertical pillars would have length 6+6+3+4=196 + 6 + 3 + 4 = 19.

step event value
L2 (a,b)(a, b) D=4>0D = 4 > 0, s=2s = 2, m=(2,0,4)m = (2, 0, 4); 28+4≈9.66<122\sqrt8 + 4 \approx 9.66 < 12, saves
L2 (b,c)(b, c) and (a,c)(a, c) D=1≤3D = 1 \le 3 and D=3≤3D = 3 \le 3: cc is in both cones, events at height 3
L2 (b,d)(b, d) D=8D = 8, s=5s = 5, m=(9,0,1)m = (9, 0, 1); 50+18+1≈12.31>10\sqrt{50} + \sqrt{18} + 1 \approx 12.31 > 10, not inserted
L4 to L9 (a,b)(a, b) at height 4 struts a→ma \to m and b→mb \to m, A={c,d,m}A = \{c, d, m\} with m=(2,0,4)m = (2, 0, 4)
L10, L11 (m,c)(m, c) D=1≤1D = 1 \le 1: cc is in the cone of mm, and 2<4\sqrt2 < 4, so it saves
L4 to L9 (m,c)(m, c) at height 3 strut m→cm \to c, A={c,d}A = \{c, d\}
L4, L5 (b,c)(b, c) and (a,c)(a, c) stale, skipped
L11 (c,d)(c, d) D=9D = 9, mz=(4+3−9)/2<0m_z = (4 + 3 - 9)/2 < 0, not inserted
L12 trunks c→(3,0,0)c \to (3, 0, 0) and d→(12,0,0)d \to (12, 0, 0)

The tree is a→(2,0,4)←ba \to (2, 0, 4) \leftarrow b, then (2,0,4)→c→(3,0,0)(2, 0, 4) \to c \to (3, 0, 0), and the separate trunk d→(12,0,0)d \to (12, 0, 0). Its length is 28+2+3+4=52+7≈14.072\sqrt8 + \sqrt2 + 3 + 4 = 5\sqrt2 + 7 \approx 14.07, against 19 for pillars. Every strut leans at most 45∘45^\circ: for example a→ma \to m goes 2 across and 2 down.

On 200 random integer points in [0,60]2×[1,30][0, 60]^2 \times [1, 30] (seed 1, k=1k = 1), the code of this page builds 333 struts of total length about 1206, against 3076 for pillars, in about 1.5 s of Python. This is one toy measurement and says nothing about real parts.

Correctness

Every strut is allowed: the struts of line L7 join pp to a point qq inside its cone with qz<pzq_z < p_z (otherwise D≤0D \le 0 and p=qp = q), the struts of line L8 go to a point that line L18 places inside both cones and strictly below both, and the trunks of line L12 are vertical. Each node gets exactly one strut below it, when it leaves the active set, and every node in the active set at the end gets a trunk. So the path down from each input point is unique and ends on the plate. The total length never exceeds the length of vertical pillars, because every merge is accepted only when it lowers the sum of the strut length built so far and the heights of the active points. The full proof is below.

The method is a heuristic. It does not find the shortest tree. The shortest tree is a Steiner tree with a slope rule and with free points on the plate, and the Euclidean Steiner tree problem is NP-hard already in the plane.

Proof: Greedy cone merging gives a support forest of allowed struts, never longer than vertical pillarsfull

Claim. Let PP be a finite set of nn points with rational coordinates and z>0z > 0, and let k>0k > 0 be rational. Then TREE-SUPPORT(P,k)(P, k) stops, and its output EE has these properties:

  1. every strut (a,b)∈E(a, b) \in E is allowed: az>bza_z > b_z and ∥axy−bxy∥≤k (az−bz)\|a_{xy} - b_{xy}\| \le k\,(a_z - b_z);
  2. every node has at most one strut below it, and the path of struts down from each point of PP ends at a node with z=0z = 0;
  3. the total length of EE is at most ∑p∈Ppz\sum_{p \in P} p_z.

Notation. For rational x≥0x \ge 0 let ⌈x⌉∗\lceil\sqrt{x}\rceil_* be the rational upper bound that the code uses, so ⌈x⌉∗≥x\lceil\sqrt{x}\rceil_* \ge \sqrt{x}. Line L18 uses ∣m−p∣xy|m - p|_{xy} in this rounded form. Let Φ\Phi be the length of the struts in EE plus ∑a∈Aaz\sum_{a \in A} a_z.

Step 1 (MERGE returns an allowed point). Let pz≥qzp_z \ge q_z and let D=∥pxy−qxy∥D = \|p_{xy} - q_{xy}\|.

Case L15: D≤k (pz−qz)D \le k\,(p_z - q_z) (the code tests the squares, which is the same because both sides are non-negative). Then m=qm = q. If D>0D > 0 then pz−qz≥D/k>0p_z - q_z \ge D/k > 0. If D=0D = 0 and pz=qzp_z = q_z, then p=qp = q, which cannot happen for two active points, because two active points never coincide (Step 3). If D=0D = 0 and pz>qzp_z > q_z, the strut is vertical. So the strut (p,q)(p, q) is allowed.

Case L16 to L18: D>k (pz−qz)≥0D > k\,(p_z - q_z) \ge 0. Line L18 gives mz≤pz−⌈hp⌉∗/km_z \le p_z - \lceil\sqrt{h_p}\rceil_*/k with hp=∥mxy−pxy∥2h_p = \|m_{xy} - p_{xy}\|^2. So k (pz−mz)≥⌈hp⌉∗≥hp=∥mxy−pxy∥k\,(p_z - m_z) \ge \lceil\sqrt{h_p}\rceil_* \ge \sqrt{h_p} = \|m_{xy} - p_{xy}\|, and the same holds for qq. It remains to show mz<qzm_z < q_z (and so mz<pzm_z < p_z). If mxy≠qxym_{xy} \ne q_{xy}, then ⌈hq⌉∗≥hq>0\lceil\sqrt{h_q}\rceil_* \ge \sqrt{h_q} > 0 and mz≤qz−hq/k<qzm_z \le q_z - \sqrt{h_q}/k < q_z. If mxy=qxym_{xy} = q_{xy}, then hp=D2h_p = D^2 and mz≤pz−D/k<pz−(pz−qz)=qzm_z \le p_z - D/k < p_z - (p_z - q_z) = q_z. In both cases the struts (p,m)(p, m) and (q,m)(q, m) are allowed.

Step 2 (the saving test is exact). In case L15 the code tests ∣p−q∣2<pz2|p - q|^2 < p_z^2, which is ∣p−q∣<pz|p - q| < p_z because pz>0p_z > 0. Otherwise it tests A+B<C\sqrt{A} + \sqrt{B} < C with A=∣p−m∣2A = |p - m|^2, B=∣q−m∣2B = |q - m|^2 and C=pz+qz−mzC = p_z + q_z - m_z, by: C>0C > 0, d=C2−A−B>0d = C^2 - A - B > 0 and 4AB<d24AB < d^2. If A+B<C\sqrt{A} + \sqrt{B} < C, then C>0C > 0, and squaring gives A+B+2AB<C2A + B + 2\sqrt{AB} < C^2, so d>2AB≥0d > 2\sqrt{AB} \ge 0 and d2>4ABd^2 > 4AB. Conversely, if C>0C > 0, d>0d > 0 and 4AB<d24AB < d^2, then 2AB<d2\sqrt{AB} < d, so (A+B)2<C2(\sqrt{A} + \sqrt{B})^2 < C^2, and since both sides are non-negative, A+B<C\sqrt{A} + \sqrt{B} < C. So line L19 accepts exactly the merges with mz>0m_z > 0 that lower Φ\Phi.

Step 3 (invariants of the loop). Before each pass of line L3 these hold:

(a) every node in AA has z>0z > 0 and has no strut below it, and every node not in AA that is an input point or a merge point has exactly one strut below it;

(b) for every node xx, the path of struts down from xx ends at a node of AA;

(c) Φ≤∑p∈Ppz\Phi \le \sum_{p \in P} p_z;

(d) no two nodes of AA are equal points.

At the start A=PA = P (a set, so (d) holds), EE is empty, and Φ=∑pz\Phi = \sum p_z, so all four hold. Consider a pass that does not skip at line L5, with the event (m,p,q)(m, p, q). Both pp and qq are in AA, and the event was created by MERGE with "saves" true, so mz>0m_z > 0. If m=qm = q (line L7), pp leaves AA and gets the strut (p,q)(p, q), and qq stays in AA (lines L6 and L9 remove and add it again). If m≠qm \ne q (line L8), pp and qq leave AA with one strut each, and mm is in AA afterwards with no strut below it: either it is a new node, or it is a node of AA equal to mm, which line L8 reuses and which has no strut below it by (a). So (a) holds, and (d) holds because a point equal to a node of AA is never added as a new node. A path from any node that used to end at pp or qq now continues by one strut to mm, which is in AA, so (b) holds. By Step 2, Φ\Phi goes down in both cases: by pz−∣p−q∣p_z - |p - q| in the first case and by pz+qz−mz−∣p−m∣−∣q−m∣p_z + q_z - m_z - |p - m| - |q - m| in the second. (If mm is a reused node, its height was already in the sum, so the change is ∣p−m∣+∣q−m∣−pz−qz|p - m| + |q - m| - p_z - q_z, which is smaller than −mz<0-m_z < 0.) So (c) holds. Skipped passes change nothing.

Step 4 (termination). Each pass that does not skip makes ∣A∣|A| smaller by one, so at most n−1n - 1 passes merge. Each of them inserts at most ∣A∣≤n|A| \le n events, and line L2 inserts at most (n2)\binom{n}{2}. Every pass extracts one event. So the loop stops after at most (n2)+n(n−1)\binom{n}{2} + n(n - 1) passes.

Step 5 (the end). Line L12 adds one vertical strut from each node of AA to a new node with z=0z = 0. By (a) each node of AA has z>0z > 0, so these struts are allowed, and every node now has at most one strut below it. By (b), the path from each input point ends at a node of AA and then reaches z=0z = 0. The trunks add exactly ∑a∈Aaz\sum_{a \in A} a_z to the length and empty AA, so the final length equals the final value of Φ\Phi, which is at most ∑p∈Ppz\sum_{p \in P} p_z by (c). Together with Step 1 this proves parts 1, 2 and 3. ■\blacksquare

Complexity

Line L2 computes (n2)\binom{n}{2} events and puts them in a binary heap in O(n2log⁡n)O(n^2 \log n) time. There are at most n−1n - 1 merges, because each one makes the active set smaller by one, and each merge adds at most nn events. So the heap receives O(n2)O(n^2) events, and each is extracted at most once, in O(log⁡n)O(\log n) time. The total is O(n2log⁡n)O(n^2 \log n) time and O(n2)O(n^2) space for the heap. The exact arithmetic adds a factor that depends on the size of the numbers, which grow with the grid of line L17.

A faster version keeps only near pairs, for example the pairs within a distance from a grid or a k-d tree, because two points that are far apart compared with their heights cannot merge above the plate.

Properties

  • Every point is supported. Each input point has a path of allowed struts to the plate.
  • A forest. Each node has one strut below it, so the supports form trees with their roots on the plate.
  • Never longer than pillars. The total length is at most ∑i(pi)z\sum_i (p_i)_z, and strictly less if one merge happens.
  • Top-down order. Merges happen in decreasing height.
  • Exact decisions. The cone test, the saving test and the overhang test are exact on integer or rational input.
  • Heuristic. The length is not optimal, and the result depends on the order of merges.

Variants and improvements

  • Clever Support. Vanek, Garcia Galicia and Benes (2014) first choose the build orientation for a small overhang area, find the points that need support from the facets and from a scan of the layers, and then run the sweep. At each step they compare the meeting point of two cones with the point where a cone first hits the part, and they take the higher one. So a branch can also end on the part. They report that, on their test models and a MakerBot Replicator 2, the trees saved on average about 40% of the support material and about 29% of the print time compared with the supports of the printer software. These are measured numbers on their models.
  • Avoiding the part. A strut that would pass through the part must be bent or rerouted. Common tools test each strut against the mesh, or grow branches in a distance field of the part.
  • Branch thickness. Real branches get thicker toward the root, because they carry more weight. This changes the cost from length to volume.
  • Other support shapes. Pillars, lines and grids under the overhang, and scaffolds with horizontal bridges, are other answers to the same problem, see support structure generation.

When to use it

Use tree supports when a part has many small overhangs over open space, such as figures, organic shapes or parts with islands, and when support material and removal time matter. For large flat overhangs, a dense support under the whole area gives a better bottom surface, because a tree touches the part only at points. For parts that are mostly flat with small overhangs near the plate, simple pillars are often enough.

Pitfalls

  • Struts through the part. A support that ignores the mesh can pass through the part, which is not printable. This page's code has that limit on purpose.
  • Too few sample points. A facet sampled only at its vertices can sag between them. The sampling step must match the largest span that the material can bridge.
  • Floating point angle tests. A facet at exactly the critical angle is common in designed parts. Compare squares of exact numbers.
  • The angle is not a constant of nature. The self-supporting angle depends on the printer, the material and the speed. Make it a parameter.
  • Local minima. A vertex below all its neighbours needs support even if no facet near it is an overhang.
  • Thin trunks. A long thin trunk can bend or break during printing. Real tools set a minimum diameter and add a base.

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.

tree_support.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-support/. The authors are listed in prov/YRE332.jsonl.

"""Tree supports by greedy merging of support cones, after Vanek, Garcia Galicia and Benes (2014).

The points that need support are sampled on the overhang facets of a mesh and
at its local minimum vertices. Each point can be supported from below by a
strut inside its downward cone of slope k (horizontal distance at most k times
the drop). The method sweeps down: it always merges the two active points whose
cones meet highest, if the merge makes the support shorter, and it ends every
remaining active point with a vertical pillar to the plate z = 0.

This is a simplified version. Struts may pass through the part: the method
does not test the cones against the mesh and never lands a strut on the part.

All decisions are exact. Coordinates are int or Fraction. A merge point is
rounded to a grid of step 1/grid and then lowered so that it lies inside both
cones exactly; square roots are bounded above with math.isqrt.
"""

import heapq
import math
from fractions import Fraction


def sub(a, b):
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def is_overhang(p, q, r, s2):
    """Downward facet tilted less than the critical angle from the horizontal.

    s2 = sin^2 of the self-supporting angle measured from the vertical
    (1/2 for 45 degrees). The facet needs support if n_z < 0 and
    n_z^2 > s2 |n|^2. Facets on the plate (all z = 0) need none.
    """
    if p[2] == 0 and q[2] == 0 and r[2] == 0:
        return False
    n = cross(sub(q, p), sub(r, p))
    nn = n[0] * n[0] + n[1] * n[1] + n[2] * n[2]
    return n[2] < 0 and n[2] * n[2] > s2 * nn


def support_points(vertices, faces, s2, m):
    """Points that need support: a barycentric grid of step 1/m on each overhang
    facet, and every vertex strictly below all its neighbours. Points on the
    plate are left out."""
    pts = set()
    for a, b, c in faces:
        p, q, r = vertices[a], vertices[b], vertices[c]
        if not is_overhang(p, q, r, s2):
            continue
        for i in range(m + 1):
            for j in range(m + 1 - i):
                w = (Fraction(i, m), Fraction(j, m), Fraction(m - i - j, m))
                x = tuple(w[0] * p[t] + w[1] * q[t] + w[2] * r[t] for t in range(3))
                if x[2] > 0:
                    pts.add(x)
    nbrs = {i: set() for i in range(len(vertices))}
    for a, b, c in faces:
        nbrs[a] |= {b, c}
        nbrs[b] |= {a, c}
        nbrs[c] |= {a, b}
    for i, v in enumerate(vertices):
        if v[2] > 0 and nbrs[i] and all(vertices[j][2] > v[2] for j in nbrs[i]):
            pts.add(tuple(Fraction(x) for x in v))
    return sorted(pts)


def sqrt_up(x, prec=1 << 24):
    """A rational upper bound of sqrt(x) for a rational x >= 0, within about 1/prec."""
    x = Fraction(x)
    a, b = x.numerator, x.denominator
    r = math.isqrt(a * b * prec * prec)
    if r * r == a * b * prec * prec:
        return Fraction(r, b * prec)
    return Fraction(r + 1, b * prec)


def shorter(a2, b2, c):
    """Exact test sqrt(a2) + sqrt(b2) < c for rationals a2, b2 >= 0."""
    if c <= 0:
        return False
    d = c * c - a2 - b2
    return d > 0 and 4 * a2 * b2 < d * d


def dist2(a, b):
    d = sub(a, b)
    return d[0] * d[0] + d[1] * d[1] + d[2] * d[2]


def merge(p, q, k, grid):
    """Return (m, saves) for the points p and q with p[2] >= q[2]."""
    dz = p[2] - q[2]
    h2 = (q[0] - p[0]) ** 2 + (q[1] - p[1]) ** 2  # @line L14
    if h2 <= k * k * dz * dz:  # @line L15
        return q, shorter(dist2(p, q), 0, p[2])
    big_d = math.sqrt(h2)  # only to place m; feasibility is restored exactly below  # @line L16
    s = (float(k * dz) + big_d) / (2 * big_d)
    mx = Fraction(round(float(p[0] + (q[0] - p[0]) * s) * grid), grid)  # @line L17
    my = Fraction(round(float(p[1] + (q[1] - p[1]) * s) * grid), grid)
    hp = sqrt_up((mx - p[0]) ** 2 + (my - p[1]) ** 2)
    hq = sqrt_up((mx - q[0]) ** 2 + (my - q[1]) ** 2)
    mz = min(p[2] - hp / k, q[2] - hq / k)  # @line L18
    m = (mx, my, mz)
    saves = mz > 0 and shorter(dist2(p, m), dist2(q, m), p[2] + q[2] - mz)  # @line L19
    return m, saves  # @line L20


def tree_support(points, k=1, grid=1 << 10):
    """Return (nodes, struts). struts are (upper, lower) index pairs into nodes.

    nodes starts with the given points. Every point is the top of a path of
    struts that ends on the plate z = 0.
    """
    k = Fraction(k)
    nodes = [tuple(Fraction(x) for x in p) for p in points]
    active = set(range(len(nodes)))  # @line L1
    struts = []
    heap = []
    counter = 0

    def push(i, j):
        nonlocal counter
        a, b = (i, j) if nodes[i][2] >= nodes[j][2] else (j, i)
        m, saves = merge(nodes[a], nodes[b], k, grid)
        if saves:
            counter += 1
            heapq.heappush(heap, (-m[2], counter, a, b, m))

    order = sorted(active)
    for x in range(len(order)):  # @line L2
        for y in range(x + 1, len(order)):
            push(order[x], order[y])
    while heap:  # @line L3
        _, _, a, b, m = heapq.heappop(heap)  # @line L4
        if a not in active or b not in active:  # @line L5
            continue
        active -= {a, b}  # @line L6
        if m == nodes[b]:  # @line L7
            struts.append((a, b))
            new = b
        else:
            same = [r for r in active if nodes[r] == m]  # reuse an equal active point
            if same:
                new = same[0]
            else:
                nodes.append(m)  # @line L8
                new = len(nodes) - 1
            struts += [(a, new), (b, new)]
        active.add(new)  # @line L9
        for r in sorted(active - {new}):  # @line L10
            push(new, r)  # @line L11
    for a in sorted(active):  # @line L12
        p = nodes[a]
        nodes.append((p[0], p[1], Fraction(0)))
        struts.append((a, len(nodes) - 1))
    return nodes, struts  # @line L13


def total_length(nodes, struts):
    return sum(math.sqrt(float(dist2(nodes[a], nodes[b]))) for a, b in struts)


if __name__ == "__main__":
    pts = [(0, 0, 4), (2, 0, 4), (6, 0, 4)]
    nodes, struts = tree_support(pts)
    for a, b in struts:
        print([str(x) for x in nodes[a]], "->", [str(x) for x in nodes[b]])
    print(total_length(nodes, struts), sum(p[2] for p in pts))
test_tree_support.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tree-support/. The authors are listed in prov/YRE332.jsonl.

import math
import random
from fractions import Fraction as F

from tree_support import dist2, is_overhang, merge, shorter, sqrt_up, support_points, total_length, tree_support

# ---- 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 inverted_pyramid(apex_z, top_z):
    v = [(0, 0, top_z), (4, 0, top_z), (4, 4, top_z), (0, 4, top_z), (2, 2, apex_z)]
    f = [(0, 1, 2), (0, 2, 3), (4, 1, 0), (4, 2, 1), (4, 3, 2), (4, 0, 3)]
    return v, f


# ---- independent checks ----


def brute_overhang(p, q, r, angle_deg):
    """Float angle test, used away from ties only."""
    n = [((q[1] - p[1]) * (r[2] - p[2]) - (q[2] - p[2]) * (r[1] - p[1])),
         ((q[2] - p[2]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[2] - p[2])),
         ((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]))]
    n = [float(x) for x in n]
    tilt = math.degrees(math.acos(max(-1.0, min(1.0, -n[2] / math.sqrt(sum(x * x for x in n))))))
    return n[2] < 0 and tilt < 90 - angle_deg, tilt


def check_tree(points, nodes, struts, k):
    """Every given point has a path of struts down to z = 0, inside the cones."""
    down = {}
    for a, b in struts:
        assert a not in down  # one strut below each node: a forest
        down[a] = b
        p, q = nodes[a], nodes[b]
        dz = p[2] - q[2]
        h2 = (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
        assert dz > 0 and h2 <= k * k * dz * dz  # strictly down, inside the cone
    for i, p in enumerate(points):
        assert nodes[i] == tuple(F(x) for x in p)
        j, steps = i, 0
        while nodes[j][2] > 0:
            j = down[j]
            steps += 1
            assert steps <= len(nodes)
        assert nodes[j][2] == 0


def greedy_slow(points, k=1, grid=1 << 10):
    """Same greedy rule without a heap: rescan all pairs after each merge."""
    k = F(k)
    nodes = [tuple(F(x) for x in p) for p in points]
    active = list(range(len(nodes)))
    struts = []
    while True:
        best = None
        for x in range(len(active)):
            for y in range(x + 1, len(active)):
                i, j = active[x], active[y]
                a, b = (i, j) if nodes[i][2] >= nodes[j][2] else (j, i)
                m, saves = merge(nodes[a], nodes[b], k, grid)
                if saves and (best is None or m[2] > best[0]):
                    best = (m[2], a, b, m)
        if best is None:
            break
        _, a, b, m = best
        active.remove(a)
        active.remove(b)
        if m == nodes[b]:
            struts.append((a, b))
            active.append(b)
        else:
            same = [r for r in active if nodes[r] == m]
            if same:
                struts += [(a, same[0]), (b, same[0])]
            else:
                nodes.append(m)
                struts += [(a, len(nodes) - 1), (b, len(nodes) - 1)]
                active.append(len(nodes) - 1)
    for a in sorted(active):
        nodes.append((nodes[a][0], nodes[a][1], F(0)))
        struts.append((a, len(nodes) - 1))
    return nodes, struts


def random_points(rng, n):
    pts = set()
    while len(pts) < n:
        pts.add((rng.randint(0, 12), rng.randint(0, 12), rng.randint(1, 8)))
    return sorted(pts)


# ---- tests ----


def test_page_example():
    pts = [(0, 0, 6), (4, 0, 6), (3, 0, 3), (12, 0, 4)]
    nodes, struts = tree_support(pts)
    check_tree(pts, nodes, struts, 1)
    edges = {(tuple(nodes[a]), tuple(nodes[b])) for a, b in struts}
    assert ((0, 0, 6), (2, 0, 4)) in edges and ((4, 0, 6), (2, 0, 4)) in edges
    assert ((2, 0, 4), (3, 0, 3)) in edges  # (3, 0, 3) lies in the cone of (2, 0, 4)
    assert ((12, 0, 4), (12, 0, 0)) in edges and ((3, 0, 3), (3, 0, 0)) in edges
    assert abs(total_length(nodes, struts) - (4 * math.sqrt(2) + math.sqrt(2) + 3 + 4)) < 1e-9


def test_merge_point_equal_to_an_active_point():
    for pts in ([(0, 0, 4), (4, 0, 4), (2, 0, 2)], [(0, 0, 4), (4, 0, 4), (2, 0, 2), (2, 0, 1)]):
        nodes, struts = tree_support(pts)
        check_tree(pts, nodes, struts, 1)
        assert len(set(nodes)) == len(nodes)


def test_overhang_test_exact_at_45_degrees():
    s2 = F(1, 2)
    v, f = inverted_pyramid(1, 3)  # side faces at exactly 45 degrees
    assert not any(is_overhang(*(v[i] for i in face), s2) for face in f)
    v, f = inverted_pyramid(2, 3)  # shallower, 26.6 degrees from horizontal
    assert sum(is_overhang(*(v[i] for i in face), s2) for face in f) == 4
    v, f = box(0, 0, 0, 2, 2, 2)  # bottom face on the plate needs nothing
    assert not any(is_overhang(*(v[i] for i in face), s2) for face in f)


def test_overhang_against_float_angles():
    rng = random.Random(9)
    for _ in range(3000):
        p, q, r = [(rng.randint(-5, 5), rng.randint(-5, 5), rng.randint(1, 6)) for _ in range(3)]
        n = (((q[1] - p[1]) * (r[2] - p[2]) - (q[2] - p[2]) * (r[1] - p[1])),
             ((q[2] - p[2]) * (r[0] - p[0]) - (q[0] - p[0]) * (r[2] - p[2])),
             ((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])))
        if n == (0, 0, 0):
            continue
        want, tilt = brute_overhang(p, q, r, 45)
        if abs(tilt - 45) < 1e-6:
            continue
        assert is_overhang(p, q, r, F(1, 2)) == want


def test_support_points_of_meshes():
    v, f = box(0, 0, 2, 4, 4, 3)  # a hovering box
    pts = support_points(v, f, F(1, 2), 2)
    assert all(p[2] == 2 for p in pts)
    assert len(pts) == 9  # the 3 x 3 grid of step 2 on the bottom face
    v, f = inverted_pyramid(2, 3)
    pts = support_points(v, f, F(1, 2), 1)
    assert (2, 2, 2) in pts  # the apex is a local minimum
    nodes, struts = tree_support(pts)
    check_tree(pts, nodes, struts, 1)


def test_heap_matches_slow_greedy():
    rng = random.Random(21)
    for _ in range(40):
        pts = random_points(rng, rng.randint(2, 9))
        n1, s1 = tree_support(pts)
        n2, s2 = greedy_slow(pts)
        assert {(n1[a], n1[b]) for a, b in s1} == {(n2[a], n2[b]) for a, b in s2}


def test_all_points_supported_and_shorter_than_pillars():
    rng = random.Random(2)
    for _ in range(60):
        pts = random_points(rng, rng.randint(1, 14))
        k = rng.choice([F(1), F(1, 2), F(2)])
        nodes, struts = tree_support(pts, k)
        check_tree(pts, nodes, struts, k)
        assert total_length(nodes, struts) <= sum(p[2] for p in pts) + 1e-9


def test_random_meshes_supported():
    rng = random.Random(6)
    for _ in range(4):
        z0 = rng.randint(1, 3)
        v, f = box(0, 0, z0, rng.randint(2, 6), rng.randint(2, 6), z0 + 2)
        a = rng.randint(1, 2)
        v2, f2 = inverted_pyramid(z0 + 5, z0 + 5 + a)
        off = len(v)
        v = v + [(x + 8, y, z) for x, y, z in v2]
        f = f + [(i + off, j + off, l + off) for i, j, l in f2]
        pts = support_points(v, f, F(1, 2), 2)
        nodes, struts = tree_support(pts)
        check_tree(pts, nodes, struts, 1)


def test_exact_helpers():
    rng = random.Random(3)
    for _ in range(2000):
        x = F(rng.randint(0, 10 ** 6), rng.randint(1, 1000))
        u = sqrt_up(x)
        assert u * u >= x and u - F(1, 1 << 23) < math.sqrt(x) + 1e-9
        a2, b2 = F(rng.randint(0, 50)), F(rng.randint(0, 50))
        c = F(rng.randint(0, 200), 10)
        lhs = math.sqrt(a2) + math.sqrt(b2)
        if abs(lhs - c) > 1e-9:
            assert shorter(a2, b2, c) == (lhs < c)
    assert not shorter(9, 16, 7) and shorter(9, 16, F(7000001, 1000000))  # 3 + 4 = 7 is a tie

History

Early support generators for stereolithography and material extrusion placed vertical walls, lines or grids under every overhang. Vanek, Garcia Galicia and Benes presented Clever Support at the Symposium on Geometry Processing in 2014, published in Computer Graphics Forum. It showed that a sweep that merges support cones into trees saves much material and time on extrusion printers. Tree supports later became an option of common slicers. The trees of these tools differ from the paper in how they avoid the part and how they choose the merge points.

References

  1. Juraj Vanek, Jorge A. Garcia Galicia and Bedrich Benes, Clever Support, Efficient Support Structure Generation for Digital Fabrication, Computer Graphics Forum 33(5), 2014, 117 to 125 (Proceedings of SGP 2014), the detection of the points that need support, the sweep that merges cones, and the measurements of material and print time
  2. Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the chapters on material extrusion and on design for additive manufacturing (overhangs and supports)

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
  • at least three sources
  • a scene preset for the example