Algorithm Search⌘K

Data structureadvanced

Dexel representation

Also called depth element representation, tri-dexel.

Van Hook's solid model as a grid of rays, each holding the depth intervals where it is inside, which makes Boolean subtraction of the tool fast.

Time
O(k) booleanO(c k) cut
Space
O(M) extra
Where
M = number of intervals in the model; c = number of rays in the bounding box of one tool move; k = total number of intervals on the two rays
Properties
deterministicexact
Origin
Tim Van Hook, 1986

A dexel representation models a solid by a grid of parallel rays. For each ray it stores the depths where the ray enters and leaves the solid, as a sorted list of intervals. A single interval on a ray is a dexel, short for depth element. Van Hook (1986) introduced the structure to show NC milling in real time: the rays were the pixels of the screen, and cutting the stock was a subtraction of the tool's intervals from the stock's intervals, pixel by pixel. Unlike a z-map, which stores one height per line, a dexel ray can hold any number of intervals, so undercuts, holes across the ray direction and tilted tools are no problem. Each Boolean operation on two rays is one merge of two sorted lists, in time linear in the number of intervals. The model still samples the solid only on the rays, so details between rays are lost. A tri-dexel model uses three grids along xx, yy and zz to lower that loss.

In plain words

Push many thin straight wires through a block, all in the same direction, in a regular grid. On each wire, write down where it goes into the material and where it comes out. If the block has a hole across the wire, the wire goes in and out twice, and you write two pieces.

That list of pieces per wire is the whole model. To cut away the volume of a tool, find the piece of each wire that is inside the tool, and remove it from the pieces of the block. Joining two solids or keeping only their common part works the same way, wire by wire.

The model only knows the material on the wires. Anything thinner than the gap between wires can be missed.

The abstract type

The rays are the vertical lines through a grid of points qij=(x0+ih,y0+jh)q_{ij} = (x_0 + ih, y_0 + jh), 0≤i<nx0 \le i < n_x, 0≤j<ny0 \le j < n_y, all in the direction +z+z. A dexel list on a ray is I=[(l1,u1),…,(lm,um)]I = [(l_1, u_1), \dots, (l_m, u_m)] with

l1<u1<l2<u2<⋯<lm<um,l_1 < u_1 < l_2 < u_2 < \dots < l_m < u_m,

and stands for the union of the closed intervals [lk,uk][l_k, u_k]. Intervals do not touch: two intervals that share an end are one interval. The model stands for the set of points (qij,z)(q_{ij}, z) with zz in the list of ray (i,j)(i, j). The operations are:

  • BOX(z0,z1)\mathrm{BOX}(z_0, z_1): every ray holds [(z0,z1)][(z_0, z_1)].
  • COMBINE(I,J,op)\mathrm{COMBINE}(I, J, \mathrm{op}): the regularized result of a Boolean function on two rays, for union (a∨ba \vee b), intersection (a∧ba \wedge b) and difference (a∧¬ba \wedge \neg b).
  • CUT(c0,c1,r)\mathrm{CUT}(c_0, c_1, r): subtract the volume swept by a ball-end mill of radius rr whose ball center moves from c0c_0 to c1c_1, with or without its shank.
  • INSIDE(i,j,z)\mathrm{INSIDE}(i, j, z) and VOLUME\mathrm{VOLUME}: membership on a ray, and the estimate h2∑(uk−lk)h^2 \sum (u_k - l_k).

The results are regularized, as in regularized set operations: the result is the closure of the interior of the pointwise result. On a ray this drops pieces of length zero, such as the common end point of two touching intervals in an intersection.

Representation

Each ray stores its list as an array of pairs, or as a linked list as in Van Hook's paper, where each node held a near depth, a far depth and a color for display. The grid of rays is an nx×nyn_x \times n_y array of such lists. The space is linear in the total number of intervals. A block with no holes needs one interval per ray, which is the same as a z-map with a bottom. Each hole that a ray crosses adds one interval.

In the tri-dexel model of Benouamer and Michelucci (1997), the same solid is stored three times, with rays along xx, along yy and along zz. A surface that is parallel to the rays of one grid, such as a vertical wall in a zz grid, cuts the rays of the other two grids at a good angle. This allows a boundary to be rebuilt from the three grids with much less error than from one.

Operations

  1. COMBINE(I, J, op) ▷ two dexel lists; op(false, false) = false
  2. 1P ← the endpoints of I and of J, merged in increasing order, without repeats
  3. 2out ← empty list; i ← 1; j ← 1
  4. 3for each pair (p, p') of consecutive values in P do
  5. 4while i ≤ |I| and I[i].u ≤ p do i ← i + 1
  6. 5while j ≤ |J| and J[j].u ≤ p do j ← j + 1
  7. 6a ← (i ≤ |I| and I[i].l ≤ p); b ← (j ≤ |J| and J[j].l ≤ p)
  8. 7if op(a, b) then
  9. 8if out is not empty and last(out).u = p then last(out).u ← p'
  10. 9else append (p, p') to out
  11. 10return out
  12. CUT(D, c0, c1, r) ▷ ball centers c0, c1; radius r
  13. 11for each ray q in the xy box of the move, grown by r do
  14. 12S ← the segment of the ray inside the swept tool ▷ [lo, hi], or [lo, ∞) with a shank
  15. 13if S has positive length then D[q] ← COMBINE(D[q], [S], a and not b)

The endpoints cut the ray into open cells, and on each cell both inputs are constant. Lines L4 and L5 move each pointer to the first interval that is not over yet, and line L6 reads whether the current cell is inside it. Line L8 joins the cell to the previous output interval when they meet, so the output never has two touching intervals.

Line L12 needs the part of the ray inside the swept tool. Without the shank, the tool sweeps a capsule, the set of points within rr of the segment c0c1c_0 c_1, which is convex, so the part is one interval. Its lower end is the lowest point of the swept ball on the line, computed in closed form on the z-map page. Its upper end is the same quantity for the mirror image of the move in the plane z=0z = 0, with the sign changed. With the shank, the part runs up to +∞+\infty.

Exact arithmetic. COMBINE only compares endpoints, so with integer or rational endpoints it is exact, and the result of a long sequence of operations does not drift. The ends of the tool segment have square roots. The code computes them in floating point and the tests compare them with an exact rational test of membership in the swept tool, to one part in 10910^9. A ray that is tangent to the tool gives a segment of length about zero, and line L13 leaves the ray unchanged, which is the right regularized answer.

Example

Take the ray I=[(0,2),(4,6)]I = [(0, 2), (4, 6)] and J=[(1,5)]J = [(1, 5)], and compute I∖JI \setminus J, so op(a,b)=a∧¬b\mathrm{op}(a, b) = a \wedge \neg b. Line L1 gives P=(0,1,2,4,5,6)P = (0, 1, 2, 4, 5, 6).

cell ii after L4 aa jj after L5 bb op out
(0,1)(0, 1) 1 true 1 false true [(0,1)][(0, 1)]
(1,2)(1, 2) 1 true 1 true false [(0,1)][(0, 1)]
(2,4)(2, 4) 2 false 1 true false [(0,1)][(0, 1)]
(4,5)(4, 5) 2 true 1 true false [(0,1)][(0, 1)]
(5,6)(5, 6) 2 true 2 false true [(0,1),(5,6)][(0, 1), (5, 6)]

The union gives [(0,6)][(0, 6)], the intersection [(1,2),(4,5)][(1, 2), (4, 5)], and J∖IJ \setminus I gives [(2,4)][(2, 4)]. The union of the touching rays [(0,1)][(0, 1)] and [(1,2)][(1, 2)] is [(0,2)][(0, 2)], and their intersection is empty after regularization.

Now a cut that a z-map cannot store. The stock is the box [0,4]×[0,2]×[0,4][0, 4] \times [0, 2] \times [0, 4] on a grid with h=1h = 1, so every ray holds [(0,4)][(0, 4)]. A ball of radius 11 with no shank moves from (0,1,2)(0, 1, 2) to (4,1,2)(4, 1, 2), inside the block, as when a tool with a ball on a thin neck reaches under an overhang. The ray at (2,1)(2, 1) passes through the axis of the tunnel, and becomes [(0,1),(3,4)][(0, 1), (3, 4)]: two intervals. The ray at (2,0)(2, 0) is at distance 11 from the axis, so it only touches the tool at z=2z = 2, and it stays [(0,4)][(0, 4)]. With the shank, the ray at (2,1)(2, 1) becomes [(0,1)][(0, 1)], the open slot that a z-map would also show.

Correctness

The endpoints of both lists cut the ray into open cells. On each cell, each input is constant, because no endpoint lies inside it, so the pointwise result is constant too. Outside the endpoints both inputs are empty, and the result is empty because op(false,false)\mathrm{op}(\text{false}, \text{false}) is false. So the regularized result is the union of the closed cells where op is true. After lines L4 and L5, the pointers stand at the first interval of each list that ends after the cell starts. That interval contains the cell if it starts at or before the cell, and otherwise the cell is in a gap, which is what line L6 reads. Lines L7 to L9 output the true cells and merge neighbours, so the output is a valid dexel list. For the cut, the swept capsule is convex, so it meets a ray in one interval, and with a shank the interval is unbounded above. The full proof is in proofs/correctness.md.

Proof: The dexel merge computes regularized Boolean operations, and the cut subtracts the swept toolfull

Setting. A dexel is a finite list I=[(l1,u1),…,(lm,um)]I = [(l_1, u_1), \dots, (l_m, u_m)] of closed intervals with l1<u1<l2<u2<⋯<lm<uml_1 < u_1 < l_2 < u_2 < \dots < l_m < u_m, standing for the set ∣I∣=⋃k[lk,uk]|I| = \bigcup_k [l_k, u_k]. For a set X⊆RX \subseteq \mathbb{R} write reg⁡X=int⁡X‾\operatorname{reg} X = \overline{\operatorname{int} X}. For a Boolean function op\mathrm{op} of two arguments, the pointwise result is X={z:op(z∈∣I∣,z∈∣J∣)}X = \{z : \mathrm{op}(z \in |I|, z \in |J|)\}.

Claim. For dexels II and JJ and any op\mathrm{op} with op(false,false)=false\mathrm{op}(\text{false}, \text{false}) = \text{false}, COMBINE returns a dexel RR with ∣R∣=reg⁡X|R| = \operatorname{reg} X, in O(∣I∣+∣J∣)O(|I| + |J|) steps. CUT replaces each ray II by a dexel for reg⁡(∣I∣∖Sq)\operatorname{reg}(|I| \setminus S_q), where SqS_q is the part of the ray inside the swept tool.

Step 1 (cells). Let P=p1<⋯<pnP = p_1 < \dots < p_n be the distinct endpoints of II and JJ (line L1). On each open cell (ps,ps+1)(p_s, p_{s+1}), membership in ∣I∣|I| is constant: no endpoint of II lies inside the cell, so the cell lies inside one interval of II or outside all of them. The same holds for JJ, so XX is constant on each cell. Outside [p1,pn][p_1, p_n] the point is in neither set, and op(false,false)=false\mathrm{op}(\text{false}, \text{false}) = \text{false}, so XX has no points there. Hence XX equals the union of the open cells where op\mathrm{op} is true, plus possibly some points of PP. A finite set of points has no interior, and adding or removing isolated points does not change the closure of the interior, so reg⁡X\operatorname{reg} X is the union of the closed cells [ps,ps+1][p_s, p_{s+1}] where op\mathrm{op} is true.

Step 2 (the pointers). Fix the cell (p,p′)(p, p') of one pass of line L3. We show that line L6 sets aa to the membership of the cell in ∣I∣|I|. The loop of line L4 moves ii past the intervals with ui≤pu_i \le p. Since pp only increases from pass to pass, the pointer never needs to go back, and after line L4, ii is the first interval with ui>pu_i > p, or i>mi > m. If i>mi > m, every interval ends at or before pp, so the cell is outside ∣I∣|I|, and line L6 sets aa to false. Otherwise ui>pu_i > p, and uiu_i is an endpoint, so ui≥p′u_i \ge p'. If li≤pl_i \le p, the cell lies in [li,ui][l_i, u_i], and aa is true. If li>pl_i > p, then li≥p′l_i \ge p', the cell lies before interval ii and after interval i−1i - 1, and aa is false. The same argument holds for JJ and bb at line L5.

Step 3 (the output). Lines L7 to L9 append the closed cells with op(a,b)\mathrm{op}(a, b) true, in increasing order, and line L8 joins a cell to the last output interval when they share the endpoint pp. So the output covers exactly the union of Step 1. Two output intervals are never touching: a new interval is started only when the last one ends before pp, that is, at some ps′<pp_{s'} < p, and then there is a cell between them where op\mathrm{op} is false. Every output interval has positive length, since p<p′p < p'. So RR is a dexel and ∣R∣=reg⁡X|R| = \operatorname{reg} X.

Step 4 (cost). Line L1 merges two sorted lists of 2∣I∣2|I| and 2∣J∣2|J| numbers in linear time. The loop of line L3 runs n−1≤2(∣I∣+∣J∣)n - 1 \le 2(|I| + |J|) times, and the pointers ii and jj only move forward, so lines L4 and L5 take O(∣I∣+∣J∣)O(|I| + |J|) steps in total. Each pass appends or extends at most one interval. Every loop is finite, so COMBINE stops.

Step 5 (the cut). The swept tool is S=⋃t∈[0,1]T(c(t))S = \bigcup_{t \in [0,1]} T(c(t)). Without a shank, T(c)T(c) is the closed ball of radius rr about cc, and SS is the set of points at distance at most rr from the segment c0c1c_0 c_1, a capsule. It is convex, because the distance to a convex set is a convex function. A convex set meets a line in an interval, so Sq=[zlo,zhi]S_q = [z_{lo}, z_{hi}] or empty. Its lower end zloz_{lo} is the lowest point of the swept ball on the line, which is the closed form proved on the z-map page, Steps 3 to 5 of its proof. Its upper end is the lowest point of the mirror image of SS in the plane z=0z = 0, negated, and the mirror image is the capsule of the mirrored centers, so the same formula gives it. With a shank, Step 1 of the z-map proof shows that Sq=[zlo,∞)S_q = [z_{lo}, \infty). Line L13 then applies COMBINE with op(a,b)=a∧¬b\mathrm{op}(a, b) = a \wedge \neg b, which is false at (false, false), so by Steps 1 to 3 the ray becomes a dexel for reg⁡(∣I∣∖Sq)\operatorname{reg}(|I| \setminus S_q). A ray where SqS_q has length zero, a tangent line, is left as it is, which is the same set after regularization. Rays outside the box of line L11 are more than rr from the path in xx or in yy, so SqS_q is empty for them. ■\blacksquare

Remark (exactness). Steps 1 to 4 use only comparisons of endpoints, so with integer or rational endpoints COMBINE is exact. The ends of SqS_q involve square roots. The code computes them in floating point, and the tests compare them with an exact rational membership test, one part in 10910^9 on each side.

Complexity

COMBINE on lists of m1m_1 and m2m_2 intervals takes O(m1+m2)O(m_1 + m_2) time: the merge of line L1 is linear, the loop runs fewer than 2(m1+m2)2(m_1 + m_2) times, and the two pointers only move forward. The output has at most m1+m2m_1 + m_2 intervals for union, intersection and difference. A cut of one move visits the cc rays in its bounding box and does one COMBINE on each, so it costs O(c (m+1))O(c\,(m + 1)) for mm intervals per ray. For a block that the tool only cuts from above, mm stays 1, and a cut costs O(c)O(c), like a z-map. The space is the total number of intervals. A tri-dexel model keeps three grids, so for nn rays per side it stores 3n23n^2 rays in place of n2n^2, but far fewer than the n3n^3 cells of a voxel grid of the same resolution.

Variants

  • Image space dexels. Van Hook took the rays to be the pixels of the view, so the display is free: draw the near end of the first interval of each ray. The model must be rebuilt if the view changes.
  • Tri-dexel. Three orthogonal grids, as above. A boundary mesh can be built from them, for example with a variant of marching cubes that uses the exact crossing points on the rays.
  • Ray representation in solid modeling. The same structure, sampled by ray casting through a CSG tree, can serve for mass properties and for Boolean operations of solids (see CSG ray casting).
  • Depth layers in graphics. Depth peeling on the GPU builds the intervals of all pixels from a mesh, one layer per pass.
  • Run-length view. On a ray, a dexel list is a run-length encoding of a column of voxels with real end points.
  • Normals and colors. Store the surface normal and a tag of the cutting move at each end of an interval, to shade the result and to find the move that made a gouge.

When to use it

Use dexels for machining simulation when the z-map is not enough: 5-axis milling, tools that reach under an overhang, turning and mill-turn, and parts with holes across the view direction. Use them when Boolean operations must be fast and robust and an approximate result on a grid is acceptable. When an exact boundary is needed, as in a final B-rep of the machined part, use solid Boolean operations on a boundary representation instead, or rebuild a boundary from a tri-dexel model and accept its error.

Pitfalls

  • Touching intervals. If the code keeps [(0,1),(1,2)][(0, 1), (1, 2)] as two intervals, the number of intervals grows with each operation, and two lists for the same set compare as different. Merge them, as line L8 does.
  • Pieces of length zero. A tool that touches a ray at one point must not split an interval into two with a gap of length zero. Regularize the result.
  • Steep surfaces. A surface almost parallel to the rays is sampled badly, the same as in a z-map. Use three grids, or rays along the tool axis.
  • The view changes. Image space dexels belong to one view. Rotating the view needs new rays, so most simulators keep the dexels in object space and draw them separately.
  • Floating point drift. If the tool segments are rounded, a later pass of the same tool can leave slivers of 10−1510^{-15}. Drop intervals shorter than a stated tolerance, or keep the endpoints exact.
  • Memory. A part with many holes across the rays has many intervals per ray. Budget for the worst ray, not for the mean.

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.

dexel_representation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dexel-representation/. The authors are listed in prov/QH2CZJ.jsonl.

"""Dexel model: a grid of parallel rays, each with a sorted list of depth intervals.

A ray is a list of closed intervals [lo, hi] with lo < hi, sorted and pairwise
disjoint (they may not touch either; touching intervals are merged). The
Boolean operations are regularized: the result is the closure of the interior
of the pointwise result, so pieces of length zero disappear. They run by one
merge of the two endpoint lists, in time linear in the number of intervals.
With int or Fraction endpoints they are exact.

The cut of a ball-end mill along a straight move is a subtraction of one
interval per ray: the part of the ray inside the swept tool. With a shank the
interval goes up to infinity; without it the tool is the swept ball alone, a
capsule, and the stock that stays on a ray can be two intervals, an undercut.
That segment is computed in floating point and is a measured quantity.
"""

from math import ceil, floor, inf, sqrt


def _merge_sorted(xs, ys):
    """Merge two sorted lists into one sorted list without repeated values."""
    out, i, j = [], 0, 0
    while i < len(xs) or j < len(ys):
        if j == len(ys) or (i < len(xs) and xs[i] <= ys[j]):
            v, i = xs[i], i + 1
        else:
            v, j = ys[j], j + 1
        if not out or out[-1] != v:
            out.append(v)
    return out


def combine(I, J, op):
    """Regularized Boolean operation of two dexels.

    I and J are lists of (lo, hi) pairs, sorted, disjoint and not touching.
    op maps (in I, in J) to a bool, for example lambda a, b: a and not b.
    """
    ends_i = [e for iv in I for e in iv]
    ends_j = [e for iv in J for e in iv]
    P = _merge_sorted(ends_i, ends_j)  # @line L1
    out, i, j = [], 0, 0  # @line L2
    for p, p2 in zip(P, P[1:]):  # @line L3
        while i < len(I) and I[i][1] <= p:  # @line L4
            i += 1  # @line L4
        while j < len(J) and J[j][1] <= p:  # @line L5
            j += 1  # @line L5
        a = i < len(I) and I[i][0] <= p  # @line L6
        b = j < len(J) and J[j][0] <= p  # @line L6
        if op(a, b):  # @line L7
            if out and out[-1][1] == p:  # @line L8
                out[-1] = (out[-1][0], p2)  # @line L8
            else:
                out.append((p, p2))  # @line L9
    return out  # @line L10


def union(I, J):
    return combine(I, J, lambda a, b: a or b)


def intersection(I, J):
    return combine(I, J, lambda a, b: a and b)


def difference(I, J):
    return combine(I, J, lambda a, b: a and not b)


def _lowest(q, c0, c1, r):
    """Lowest z of the capsule swept by a ball of radius r from c0 to c1, on the vertical line at q."""
    ax, ay = c0[0] - q[0], c0[1] - q[1]
    bx, by, s = c1[0] - c0[0], c1[1] - c0[1], c1[2] - c0[2]
    k, b2, r2 = ax * bx + ay * by, bx * bx + by * by, r * r - ax * ax - ay * ay
    if b2 == 0:
        if r2 < 0:
            return None
        return c0[2] + (0 if s >= 0 else s) - sqrt(r2)
    disc = k * k + b2 * r2
    if disc < 0:
        return None
    lo, hi = max(0.0, (-k - sqrt(disc)) / b2), min(1.0, (-k + sqrt(disc)) / b2)
    if lo > hi:
        return None
    t = min(max((-k - s * sqrt(disc / (b2 + s * s))) / b2, lo), hi)
    dx, dy = ax + t * bx, ay + t * by
    return c0[2] + t * s - sqrt(max(0.0, r * r - dx * dx - dy * dy))


def tool_segment(q, c0, c1, r, shank):
    """The (lo, hi) part of the vertical line at q inside the swept tool, or None.

    The capsule is convex, so the part is one interval. Its top is the lowest
    point of the mirror image in the plane z = 0, negated. With a shank the
    top is infinity.
    """
    lo = _lowest(q, c0, c1, r)
    if lo is None:
        return None
    if shank:
        return (lo, inf)
    m0, m1 = (c0[0], c0[1], -c0[2]), (c1[0], c1[1], -c1[2])
    return (lo, -_lowest(q, m0, m1, r))


class DexelModel:
    """An nx by ny grid of vertical rays with spacing h; ray (i, j) is at (x0 + i h, y0 + j h)."""

    def __init__(self, nx, ny, h, x0=0.0, y0=0.0):
        self.nx, self.ny, self.h, self.x0, self.y0 = nx, ny, h, x0, y0
        self.rays = [[[] for _ in range(ny)] for _ in range(nx)]

    @classmethod
    def box(cls, nx, ny, h, zlo, zhi, x0=0.0, y0=0.0):
        m = cls(nx, ny, h, x0, y0)
        for i in range(nx):
            for j in range(ny):
                m.rays[i][j] = [(zlo, zhi)]
        return m

    def point(self, i, j):
        return (self.x0 + i * self.h, self.y0 + j * self.h)

    def inside(self, i, j, z):
        return any(lo <= z <= hi for lo, hi in self.rays[i][j])

    def boolean(self, other, op):
        """Apply op ray by ray to two models on the same grid."""
        out = DexelModel(self.nx, self.ny, self.h, self.x0, self.y0)
        for i in range(self.nx):
            for j in range(self.ny):
                out.rays[i][j] = combine(self.rays[i][j], other.rays[i][j], op)
        return out

    def cut_ball_move(self, c0, c1, r, shank=True):
        """Subtract the volume swept by a ball-end tool from c0 to c1 (ball centers)."""
        x_lo, x_hi = min(c0[0], c1[0]) - r, max(c0[0], c1[0]) + r
        y_lo, y_hi = min(c0[1], c1[1]) - r, max(c0[1], c1[1]) + r
        i0, i1 = max(0, ceil((x_lo - self.x0) / self.h)), min(self.nx - 1, floor((x_hi - self.x0) / self.h))
        j0, j1 = max(0, ceil((y_lo - self.y0) / self.h)), min(self.ny - 1, floor((y_hi - self.y0) / self.h))
        for i in range(i0, i1 + 1):  # @line L11
            for j in range(j0, j1 + 1):  # @line L11
                seg = tool_segment(self.point(i, j), c0, c1, r, shank)  # @line L12
                if seg is not None and seg[0] < seg[1]:  # @line L13
                    self.rays[i][j] = difference(self.rays[i][j], [seg])  # @line L13

    def volume(self):
        """Sum of interval lengths times h^2: the column estimate of the volume."""
        return sum(hi - lo for col in self.rays for ray in col for lo, hi in ray) * self.h * self.h

    def max_intervals(self):
        return max(len(ray) for col in self.rays for ray in col)
test_dexel_representation.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dexel-representation/. The authors are listed in prov/QH2CZJ.jsonl.

import random
from fractions import Fraction as F
from math import inf

from dexel_representation import (DexelModel, combine, difference, intersection,
                                  tool_segment, union)

OPS = {
    "union": (union, lambda a, b: a or b),
    "intersection": (intersection, lambda a, b: a and b),
    "difference": (difference, lambda a, b: a and not b),
}
EPS = 1e-9


def rand_dexel(rng, n_max=4, span=12):
    """A random valid dexel with Fraction endpoints (sorted, disjoint, not touching)."""
    k = rng.randint(0, n_max)
    pts = sorted(rng.sample(range(span * 2), 2 * k))
    return [(F(pts[2 * m], 2), F(pts[2 * m + 1], 2)) for m in range(k)]


def member(I, z):
    return any(lo <= z <= hi for lo, hi in I)


def valid(I):
    return all(lo < hi for lo, hi in I) and all(I[m][1] < I[m + 1][0] for m in range(len(I) - 1))


def check_against_pointwise(I, J, fn, op):
    R = fn(I, J)
    assert valid(R)
    ends = sorted({e for iv in I + J for e in iv})
    if not ends:
        assert R == []
        return
    probes = [ends[0] - 1, ends[-1] + 1] + [(a + b) / 2 for a, b in zip(ends, ends[1:])]
    for z in probes:  # interior points of the open cells: exact agreement
        assert member(R, z) == op(member(I, z), member(J, z))
    for m, e in enumerate(ends):  # endpoints: the closure of the interior
        left = (ends[m - 1] + e) / 2 if m > 0 else e - 1
        right = (ends[m + 1] + e) / 2 if m + 1 < len(ends) else e + 1
        want = op(member(I, left), member(J, left)) or op(member(I, right), member(J, right))
        assert member(R, e) == want


def test_small_cases():
    a, b = [(F(0), F(2)), (F(4), F(6))], [(F(1), F(5))]
    assert union(a, b) == [(0, 6)]
    assert intersection(a, b) == [(1, 2), (4, 5)]
    assert difference(a, b) == [(0, 1), (5, 6)]
    assert difference(b, a) == [(2, 4)]
    # touching pieces merge in a union and vanish in an intersection
    assert union([(F(0), F(1))], [(F(1), F(2))]) == [(0, 2)]
    assert intersection([(F(0), F(1))], [(F(1), F(2))]) == []
    assert difference([(F(0), F(2))], [(F(0), F(2))]) == []
    assert union([], []) == [] and difference([(F(0), F(1))], []) == [(0, 1)]


def test_booleans_against_pointwise_membership():
    rng = random.Random(41)
    for _ in range(1500):
        I, J = rand_dexel(rng), rand_dexel(rng)
        for fn, op in OPS.values():
            check_against_pointwise(I, J, fn, op)


def test_xor_and_identities():
    rng = random.Random(9)
    for _ in range(300):
        I, J, K = rand_dexel(rng), rand_dexel(rng), rand_dexel(rng)
        assert union(difference(I, J), intersection(I, J)) == I
        assert difference(I, union(J, K)) == difference(difference(I, J), K)
        x = combine(I, J, lambda a, b: a != b)
        assert x == union(difference(I, J), difference(J, I))


def removed(p, c0, c1, r, shank):
    """Exact test (Fractions): is p in the swept ball-end tool?"""
    def min_quad(a, b, lo, hi):
        bb = sum(x * x for x in b)
        t = lo if bb == 0 else min(max(-sum(x * y for x, y in zip(a, b)) / bb, lo), hi)
        return sum((x + t * y) ** 2 for x, y in zip(a, b))
    v = tuple(c1[i] - c0[i] for i in range(3))
    w = tuple(c0[i] - p[i] for i in range(3))
    if min_quad(w, v, F(0), F(1)) <= r * r:
        return True
    if not shank:
        return False
    s, dz = v[2], p[2] - c0[2]
    if s == 0:
        lo, hi = (F(0), F(1)) if dz >= 0 else (F(1), F(0))
    elif s > 0:
        lo, hi = F(0), min(F(1), dz / s)
    else:
        lo, hi = max(F(0), dz / s), F(1)
    return lo <= hi and min_quad(w[:2], v[:2], lo, hi) <= r * r


def test_tool_segment_against_exact_membership():
    rng = random.Random(13)
    for _ in range(300):
        c0 = tuple(F(rng.randint(-12, 12), 4) for _ in range(3))
        c1 = tuple(F(rng.randint(-12, 12), 4) for _ in range(3))
        if rng.random() < 0.2:
            c1 = (c0[0], c0[1], c1[2])
        r = F(rng.randint(2, 8), 4)
        for _ in range(6):
            q = (F(rng.randint(-16, 16), 4), F(rng.randint(-16, 16), 4))
            for shank in (False, True):
                seg = tool_segment(tuple(map(float, q)), tuple(map(float, c0)), tuple(map(float, c1)), float(r), shank)
                at = lambda z: removed((q[0], q[1], F(z)), c0, c1, r, shank)
                if seg is None:
                    assert not at(-100) and not at(0) and not at(100)
                    continue
                lo, hi = seg
                assert not at(lo - EPS)
                if shank:
                    assert hi == inf and at(1000) and at(lo + EPS)
                    continue
                assert not at(hi + EPS)
                if hi - lo > 1e-6:  # not a tangent line, which meets the tool in one point
                    assert at(lo + EPS) and at(hi - EPS)


def test_cut_against_exact_membership():
    rng = random.Random(29)
    for _ in range(4):
        m = DexelModel.box(9, 9, 0.5, -2.0, 2.0)
        r = F(rng.randint(3, 6), 4)
        path = [tuple(F(rng.randint(0, 16), 4) for _ in range(2)) + (F(rng.randint(-8, 8), 4),) for _ in range(3)]
        shank = rng.random() < 0.5
        for c0, c1 in zip(path, path[1:]):
            m.cut_ball_move(tuple(map(float, c0)), tuple(map(float, c1)), float(r), shank)
        for i in range(9):
            for j in range(9):
                q = (F(i, 2), F(j, 2))
                for lo, hi in m.rays[i][j]:
                    assert valid(m.rays[i][j])
                    mid = (F(lo) + F(hi)) / 2
                    gone = any(removed((q[0], q[1], mid), a, b, r, shank) for a, b in zip(path, path[1:]))
                    assert not gone
                    for e, d in ((lo, -EPS), (hi, EPS)):
                        if -2.0 < e < 2.0:  # an end made by the tool: just outside is removed
                            p = (q[0], q[1], F(e + d))
                            assert any(removed(p, a, b, r, shank) for a, b in zip(path, path[1:]))


def test_undercut_needs_two_intervals():
    # a ball with no shank moves inside the block: a closed tunnel
    m = DexelModel.box(5, 3, 1.0, 0.0, 4.0)
    m.cut_ball_move((0.0, 1.0, 2.0), (4.0, 1.0, 2.0), 1.0, shank=False)
    assert m.rays[2][1] == [(0.0, 1.0), (3.0, 4.0)]
    assert m.max_intervals() == 2
    # the ray at distance r from the path is only touched at z = 2: a cut of length zero
    assert m.rays[2][0] == [(0.0, 4.0)]
    # the same move with a shank opens the tunnel to the top
    m2 = DexelModel.box(5, 3, 1.0, 0.0, 4.0)
    m2.cut_ball_move((0.0, 1.0, 2.0), (4.0, 1.0, 2.0), 1.0, shank=True)
    assert m2.rays[2][1] == [(0.0, 1.0)]


def test_box_volume_and_model_boolean():
    a = DexelModel.box(4, 4, 1.0, 0.0, 3.0)
    b = DexelModel.box(4, 4, 1.0, 1.0, 5.0)
    assert a.volume() == 48.0
    assert a.boolean(b, lambda x, y: x or y).volume() == 16 * 5.0
    assert a.boolean(b, lambda x, y: x and y).volume() == 16 * 2.0
    assert a.boolean(b, lambda x, y: x and not y).volume() == 16 * 1.0
    assert a.inside(0, 0, 0.0) and not a.inside(0, 0, 3.5)

History

Anderson (1978) stored one height per grid point for NC simulation. Van Hook (1986) generalized this to lists of depth intervals per pixel, called them dexels, and used them for a shaded display of NC milling in real time on the hardware of the time, with the tool subtracted pixel by pixel. Ray representations of solids came up in solid modeling around the same time, as the output of ray casting through CSG trees. Benouamer and Michelucci (1997) used three orthogonal grids of rays, the triple ray or tri-dexel representation, to convert CSG models to boundary representations. Later work on the simulation of multi-axis machining uses the tri-dexel model as a stock model.

References

  1. Tim Van Hook, Real-time shaded NC milling display, Computer Graphics 20(4) (SIGGRAPH 86), 1986, 15 to 20, the dexel structure (near and far depth per pixel, linked lists per pixel) and the subtraction of the tool in image space
  2. Mohand Ourabah Benouamer and Dominique Michelucci, Bridging the gap between CSG and Brep via a triple ray representation, ACM Symposium on Solid Modeling and Applications 1997, the triple ray representation, three orthogonal grids of ray intervals, and the conversion to a boundary representation
  3. Byoung K. Choi and Robert B. Jerard, Sculptured Surface Machining, Theory and Applications, Kluwer, 1998, the part on controlling accuracy and quality, on stock models for NC verification
  4. Robert O. Anderson, Detecting and eliminating collisions in NC machining, Computer-Aided Design 10(4), 1978, 231 to 237, the earlier single-height grid that dexels extend

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.boolean
  • a full proof of time.cut
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/QH2CZJ/text.yaml