Algorithmadvanced
Parting line generation
Also called parting curve computation.
Finds the curve on a part where the two mold halves meet, from the silhouette in the parting direction, chosen to be flat and to avoid undercuts.
- Time
- O(N) worst
- Space
- O(N) extra
- Where
- N = total number of vertex places in all faces (twice the number of edges)
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- M. W. Fu, A. Y. C. Nee, J. Y. H. Fuh, 2002
Parting line generation finds, for a part and a chosen parting direction , the closed curves on the part where the two halves of a mold meet. One half of the mold moves along and the other along . Each face of the part must be formed by the half that it faces, so the faces split into upper faces, with , and lower faces, with , and the parting line runs along the edges between the two sets. For a polyhedral part these are the silhouette edges for the direction . The algorithm on this page computes the face signs exactly, finds the edges between an upper and a lower face, and chains them into oriented loops in time. On a convex polyhedron in general position the result is one simple closed cycle, and the page proves this. On other parts there can be several loops, and the planner must choose among them or change the part. This page differs from mold parting direction, which chooses , and from undercut detection, which finds the faces that neither half can release.
In plain words
A plastic or cast part is made in a mold with two halves that come apart. Each surface of the part must be formed by the half on its side, so that the half can pull away. Surfaces that face up go to the upper half, and surfaces that face down go to the lower half. The line where the two kinds of surfaces meet is where the halves touch. That is the parting line.
The algorithm looks at each face once to see which way it faces. Then it walks around the region of upward faces and records its border, one loop at a time. On a simple convex part there is exactly one loop. On a part with holes or pockets there can be more, and the designer must choose.
The problem
Input. A closed, oriented polyhedral surface (a manifold mesh): vertices with integer coordinates and faces as lists of vertex indices, counterclockwise seen from outside, each edge in exactly two faces. A parting direction with integer coordinates. A rule zero_side that puts each face with on the lower side (the default) or the upper side.
Output. The boundary of the union of the upper faces, as a list of closed loops of vertices. Each loop is oriented with the upper faces on its left, seen from outside, and each edge between an upper and a lower face is in exactly one loop.
Faces with . A vertical face has zero draft and can go to either half. The rule zero_side makes the choice explicit. With the default, the loops run along the top edges of vertical walls. With the other choice, they run along the bottom edges. A real design gives such faces a draft first (see draft angle analysis).
The algorithm
The algorithm uses the half-edges of the mesh, as in a doubly connected edge list. The twin of the half-edge is , which lies in the other face of the edge. For a half-edge of a face , is the next half-edge of .
PARTING-LOOPS(V, F, d, zero_side)- 1
for each face f: n_f ← Newell normal of f; s_f ← sign(n_f · d), or zero_side if n_f · d = 0 - 2
for each half-edge h = (u, v) of each face f: face[h] ← f; succ[h] ← the half-edge after h in f - 3
B ← the half-edges h = (u, v) of upper faces whose twin (v, u) lies in a lower face - 4
for each h ∈ B: g ← succ[h] - 5
while the twin of g lies in an upper face: g ← succ[twin of g] - 6
next[h] ← g - 7
for each h ∈ B not yet used: follow next from h until it returns, mark the half-edges used, and record their start vertices as one loop - 8
return the loops
Line L1. The Newell normal of a face with vertices has the components and the two cyclic shifts of it. For a planar face it is the outward normal times twice the area. On integer input it is an integer vector, so the sign of is exact. A normal from the first three vertices fails on a face whose first three vertices are collinear, and a floating point normal can give the wrong sign on a face that is almost vertical.
Lines L4 to L6. Let be a boundary half-edge in the upper face . The next boundary half-edge starts at . Line L4 takes the half-edge of that leaves . If its twin is in an upper face , the boundary does not go that way, and line L5 crosses into and takes the half-edge of that leaves . This turns around through the upper faces, until it reaches a half-edge whose other side is lower. At a vertex where the upper region touches itself, with two boundary arcs through one vertex, the turn takes the first exit in the order around , so the loops never cross.
Example
The square pyramid with base at and apex , and . The vertices are , , , and .
| face | vertices | Newell normal | side | |
|---|---|---|---|---|
| base | 0, 3, 2, 1 | lower | ||
| 0, 1, 4 | upper | |||
| 1, 2, 4 | upper | |||
| 2, 3, 4 | upper | |||
| 3, 0, 4 | lower |
Line L3 finds the half-edges , in face , in face , and , in face . Lines L4 to L6:
| first (L4) | turns at L5 | ||
|---|---|---|---|
| , twin in | , twin in base | ||
| , twin in | , twin in base | ||
| , twin in | none | ||
| , twin in | , twin in ; then , twin in | ||
| , twin in base | none |
Line L7 gives one loop : three edges of the base and two slanted edges to the apex. The loop is not planar, so the mold needs a stepped parting surface. Its projection along is the boundary of the projection of the pyramid, as the theorem below says. The tests check this example, a box with vertical walls under both zero_side rules, and random cases.
Correctness
Theorem 1. PARTING-LOOPS returns loops in which every edge between an upper and a lower face occurs exactly once, oriented with the upper face on its left, and every loop is closed.
The sign at line L1 is exact. Line L3 keeps exactly one half-edge of each edge between an upper and a lower face: the half-edge in the upper face. The turn at lines L4 to L6 ends, because the edge of has a lower face on its other side, so the turn around meets a lower face before it can come back to . The map is a bijection of : the turn the other way around undoes it. So is a permutation of the finite set , its cycles are closed, and line L7 records each cycle once.
Theorem 2. Let be a convex polyhedron and a direction with for every face. Then the silhouette edges form one simple closed cycle, and PARTING-LOOPS returns exactly one loop, with no repeated vertex.
The proof projects along . The projection maps the union of the upper faces one to one onto the projected polygon , because each line parallel to leaves through an upper face and meets no other upper face. Each silhouette edge lies in a supporting plane of that is parallel to , so it projects into the boundary of . A point of off the silhouette has only upper faces around it, so no supporting plane parallel to passes through it, and it projects into the interior of . So the projection maps the silhouette onto the boundary of the convex polygon , a simple closed curve, without folds. The silhouette edge page proves the weaker fact that the edges form closed loops on any closed mesh. The full proofs are below.
Proof: PARTING-LOOPS returns the boundary loops of the upper faces, and one simple cycle on a convex polyhedronfull
We use the definitions of the page. The mesh is closed and oriented: each half-edge lies in exactly one face, its twin lies in exactly one other face, and the faces around each vertex form one cycle (a manifold vertex). A face is upper if and lower if , after line L1. is the set of half-edges of upper faces whose twins lie in lower faces.
Lemma 1 (exact signs). For a planar face with vertices in counterclockwise order seen from outside, the Newell vector equals , which is twice the vector area of the face and points outward. On integer input it is an integer vector, so line L1 computes the sign of with no error.
Proof. Expand the first component of : it is . The term of the Newell sum is . The first two terms cancel in the cyclic sum. The other components are the same with the coordinates shifted. The vector is the vector area of a closed polygon, which for a planar polygon is its area times its unit normal, with the orientation of the vertex order.
Lemma 2 (the turn ends). For in the upper face , the loop of lines L4 and L5 ends after at most steps, at a half-edge of an upper face whose twin lies in a lower face.
Proof. Let be the faces around in the order in which the loop visits them. Line L4 takes the half-edge of that leaves . If the twin lies in an upper face , line L5 sets , the half-edge of that leaves , and so on. Each step crosses one edge at and moves to the next face in the cyclic order around . The faces around form one cycle, and the edge is in it, with on one side and the lower face of on the other. Going around from , the loop reaches the edge from the side of the lower face only after it has passed that lower face, so it stops at the latest at the edge just before the lower face. Every face it visits is upper, since it only crosses into a face when that face is upper.
Lemma 3 (next is a permutation of ). The map is a bijection from to .
Proof. By Lemma 2, . Define by the same turn in the opposite direction: for in the upper face , take the half-edge of that enters ; while its twin lies in an upper face, cross into that face and take its half-edge that enters . This visits, in reverse order, exactly the upper faces that the turn from to visited, because both turns move between the same consecutive faces around and both stop at the first lower face. So , and is injective. An injective map of a finite set to itself is a bijection.
Theorem 1. PARTING-LOOPS returns loops that are closed, in which every edge between an upper face and a lower face occurs exactly once, with the upper face on its left.
Proof. Each edge between an upper and a lower face has exactly one half-edge in an upper face, and line L3 keeps exactly that one, with the upper face on its left by the orientation of the faces. By Lemma 3, is a permutation of , so splits into disjoint cycles. Line L7 starts at each half-edge not yet used and follows . In a permutation the orbit of returns to before it repeats any other element, so line L7 records exactly the cycle of and marks it used. Each half-edge of is in exactly one recorded cycle. Consecutive half-edges and share the vertex , so the start vertices form a closed loop.
Theorem 2. Let be a convex polyhedron (a bounded 3-dimensional convex polytope) whose faces are its facets, and let with for every facet . Let be the union of the silhouette edges. Then is homeomorphic to a circle. So the silhouette edges form one simple cycle, and PARTING-LOOPS returns one loop with no repeated vertex.
Proof. Write . Let be the union of the closed upper facets and the union of the closed lower facets. Let be the orthogonal projection onto the plane through the origin normal to , and . is a convex polygon with nonempty interior in , since has nonempty interior.
Step 1: . A point in the relative interior of an edge lies in exactly the two facets of that edge, and a point in the relative interior of a facet lies only in that facet. So a point of that is not a vertex lies on an edge between an upper and a lower facet. If a vertex is in , the facets around in cyclic order include both kinds, so the sign changes at least twice around , at edges between consecutive facets, and these are silhouette edges through . So , and is clear.
Step 2: restricted to is a homeomorphism onto . Take . The line meets in a segment with a highest point in the direction . For small , . The facets not through have slack at , so some facet through has , that is : is upper and . If another point with of the segment lay on an upper facet , then and , which contradicts . So each has exactly one preimage in . The map is a continuous bijection from a compact set to a Hausdorff space, so it is a homeomorphism.
Step 3: . Let lie on an edge between the upper facet and the lower facet . Set . The two coefficients are positive, and are not parallel, so , and . For every , . Since , , so the nonzero linear function on has its maximum over at , and .
Step 4: . Let . By Step 1, every facet through is upper. Suppose . Then some , , has for all , so for all , since . So is in the normal cone of at , which is the cone generated by the normals of the facets through : with , not all zero. Then , which contradicts .
Step 5. By Steps 2 to 4, is a homeomorphism that maps into and into . It is onto , so every point of has its preimage in . So is a homeomorphism from onto , the boundary of a convex polygon with nonempty interior, which is a simple closed curve. A graph whose underlying space is homeomorphic to a circle is connected and has degree 2 at every vertex, so it is one simple cycle.
The algorithm. Each vertex of has exactly two silhouette edges, one half-edge in entering it and one leaving it, so has no choice to make and follows the cycle. The cycle is connected, so by Theorem 1 line L7 records it as one loop, and each vertex of the cycle appears once.
Complexity
Let be the sum of the face sizes, which is for edges. Line L1 costs , line L2 builds two hash maps of entries, and line L3 is one pass. In lines L4 to L6, the turns around a vertex that start from different boundary half-edges cover disjoint runs of upper faces around , so the total number of steps at line L5 is at most the sum of the vertex degrees, . Line L7 visits each half-edge of once. So the time is expected with hashing, or worst case with a mesh structure that stores the twins. The extra space is . On integer input with coordinates of bits, the Newell normal has bits more, so each operation is constant time on the real RAM.
Properties
- Exact. The face signs come from integer arithmetic, so a face that is almost vertical gets the right side.
- Local. The side of a face depends only on its normal, not on the rest of the part. So the loops are candidates, not a check that the halves can come apart: a face can face up and still be blocked by another part of the part. That is an undercut.
- Deterministic. The loops come out in the order of their first boundary half-edge in the face list.
- One loop for convex parts. By Theorem 2. For a non-convex part the number of loops is not fixed: a part with a through hole along has at least two.
Variants and improvements
- Smooth surfaces. On a NURBS or other smooth part, the parting line is the silhouette curve where , traced as a curve on each face. This page covers polyhedra and tessellated parts.
- Choosing among loops. Fu, Nee and Fuh classify the faces by their visibility and moldability for the parting direction, and among the edge loops they choose the one with the largest projected area on the plane normal to as the main parting line. The other loops are inner parting lines, for example around a through hole, where a core closes the hole.
- Flat parting lines. A planar parting line makes a cheap mold. When a loop runs along vertical faces, the zero-draft faces can move to the other side, which moves the loop down the wall, and the planner chooses the position that makes the loop flat or stepped least often.
- Parting surface. The mold also needs a parting surface, which extends the parting line outward to the edge of the mold block. A flat loop gives a flat surface. A loop like the one in the example needs a ruled or stepped surface.
- Choice of the direction. The direction comes first, from mold parting direction. Ahn and coauthors test one direction for a two-piece cast and find all valid directions of a polyhedron. The algorithm on this page then gives the line for the chosen direction.
- Undercuts. If a face is blocked from both and , no choice of loop helps. Undercut detection finds such faces, and the mold needs side cores.
When to use it
Use it after the parting direction is fixed, on a tessellated part or a polyhedral model, to get the candidate parting lines in linear time. Use exact integer or rational coordinates, or snap the input to a grid, so that faces close to vertical get a reliable side. Do not use the loops as a proof that the mold works. Check undercuts and draft separately.
Pitfalls
- Vertical faces. A face with must go to one side by a fixed rule. A test with a tolerance puts some vertical faces up and some down at random, and the loops then zigzag over the walls.
- Pinched loops. At a vertex where the upper region touches itself, two boundary arcs meet. A chaining rule that takes any boundary edge at can join the arcs into a loop that crosses itself. Lines L4 to L6 turn around in the order of the faces, which gives non-crossing loops. In the random terrain tests of the implementation, several loops repeat a vertex for this reason.
- Open or bad meshes. An edge with one face, or two faces that use the same half-edge, breaks the twin map. The implementation raises an error instead of returning wrong loops.
- Orientation. If the faces are clockwise from outside, all normals flip, and the upper and lower sides swap. A test of the signed volume finds this.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parting-line-generation/. The authors are listed in prov/D4D190.jsonl.
"""Parting line candidates of a closed polyhedral mesh for a parting direction.
The mesh is a closed, oriented 2-manifold: `verts` is a list of integer
points (x, y, z) and `faces` is a list of vertex index lists, each in
counterclockwise order seen from outside. A face is *upper* when its outward
normal n has n . d > 0 and *lower* when n . d < 0. A face with n . d = 0 goes
to the side given by `zero_side` (-1, the lower side, by default).
The parting line candidates are the boundary loops of the union of the upper
faces. Each loop is a list of vertex indices; the loop closes from the last
vertex back to the first, and the upper faces are on its left when seen from
outside. All arithmetic is on integers, so the face signs are exact.
"""
from typing import Dict, List, Sequence, Set, Tuple
Point = Tuple[int, int, int]
HalfEdge = Tuple[int, int]
def newell_normal(verts: Sequence[Point], face: Sequence[int]) -> Point:
"""Return twice the area vector of a planar face (Newell's method).
For a planar polygon in counterclockwise order seen from outside, this
is an outward normal whose length is twice the area. Exact on integers.
Cost: O(k) for a face with k vertices.
"""
nx = ny = nz = 0
k = len(face)
for i in range(k):
x0, y0, z0 = verts[face[i]]
x1, y1, z1 = verts[face[(i + 1) % k]]
nx += (y0 - y1) * (z0 + z1)
ny += (z0 - z1) * (x0 + x1)
nz += (x0 - x1) * (y0 + y1)
return (nx, ny, nz)
def face_signs(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> List[int]:
"""Return +1 for each upper face and -1 for each lower face.
A face with n . d = 0 gets `zero_side`. Cost: O(total face size).
"""
if zero_side not in (1, -1):
raise ValueError("zero_side must be +1 or -1")
signs = []
for f in faces: # @line L1
n = newell_normal(verts, f)
dot = n[0] * d[0] + n[1] * d[1] + n[2] * d[2]
signs.append(1 if dot > 0 else -1 if dot < 0 else zero_side)
return signs
def _half_edge_maps(faces: Sequence[Sequence[int]]) -> Tuple[Dict[HalfEdge, int], Dict[HalfEdge, HalfEdge]]:
"""Map each half-edge to its face, and to the next half-edge of that face.
Cost: O(total face size) expected time with hashing.
"""
owner: Dict[HalfEdge, int] = {}
succ: Dict[HalfEdge, HalfEdge] = {}
for fi, f in enumerate(faces): # @line L2
k = len(f)
for i in range(k):
h = (f[i], f[(i + 1) % k])
if h in owner:
raise ValueError("half-edge %r is used by two faces; the mesh is not oriented" % (h,))
owner[h] = fi
succ[h] = (f[(i + 1) % k], f[(i + 2) % k])
for (u, v) in owner:
if (v, u) not in owner:
raise ValueError("edge %r has no twin; the mesh is not closed" % ((u, v),))
return owner, succ
def silhouette_edges(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> Set[Tuple[int, int]]:
"""Return the edges (u, v), u < v, between an upper face and a lower face.
Cost: O(total face size).
"""
signs = face_signs(verts, faces, d, zero_side)
owner, _ = _half_edge_maps(faces)
out = set()
for (u, v), f in owner.items():
if signs[f] > 0 and signs[owner[(v, u)]] < 0:
out.add((min(u, v), max(u, v)))
return out
def parting_loops(verts: Sequence[Point], faces: Sequence[Sequence[int]], d: Point, zero_side: int = -1) -> List[List[int]]:
"""Return the boundary loops of the union of the upper faces.
Each loop is a list of vertex indices with the upper faces on its left.
The loops are in a fixed order (by their first half-edge in face order),
so the result is deterministic. Cost: O(total face size).
"""
signs = face_signs(verts, faces, d, zero_side) # @line L1
owner, succ = _half_edge_maps(faces) # @line L2
boundary: List[HalfEdge] = []
for fi, f in enumerate(faces): # @line L3
if signs[fi] < 0:
continue
k = len(f)
for i in range(k):
h = (f[i], f[(i + 1) % k])
if signs[owner[(h[1], h[0])]] < 0:
boundary.append(h)
nxt: Dict[HalfEdge, HalfEdge] = {}
for h in boundary:
g = succ[h] # @line L4
while signs[owner[(g[1], g[0])]] > 0: # @line L5
g = succ[(g[1], g[0])]
nxt[h] = g # @line L6
loops: List[List[int]] = []
used: Set[HalfEdge] = set()
for h in boundary: # @line L7
if h in used:
continue
loop = []
g = h
while g not in used:
used.add(g)
loop.append(g[0])
g = nxt[g]
loops.append(loop)
return loops # @line L8
test_parting_line_generation.py 280 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parting-line-generation/. The authors are listed in prov/D4D190.jsonl.
import random
import unittest
from fractions import Fraction
from parting_line_generation import face_signs, newell_normal, parting_loops, silhouette_edges
# The square pyramid of the page: base [-1, 1]^2 at z = 0, apex (0, 0, 2).
PYR_V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 2)]
PYR_F = [[0, 3, 2, 1], [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]]
BOX_V = [(0, 0, 0), (2, 0, 0), (2, 3, 0), (0, 3, 0), (0, 0, 1), (2, 0, 1), (2, 3, 1), (0, 3, 1)]
BOX_F = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
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 sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def hull_2d(points):
"""Andrew's monotone chain, strict corners only, counterclockwise."""
pts = sorted(set(points))
if len(pts) <= 2:
return pts
def turn(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower, upper = [], []
for p in pts:
while len(lower) >= 2 and turn(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
for p in reversed(pts):
while len(upper) >= 2 and turn(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def strict_corners(poly):
"""Drop the points of a closed polygon that are collinear with their neighbours."""
out = list(poly)
changed = True
while changed and len(out) > 2:
changed = False
for i in range(len(out)):
a, b, c = out[i - 1], out[i], out[(i + 1) % len(out)]
if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) == 0:
del out[i]
changed = True
break
return out
def same_cycle(p, q):
if len(p) != len(q):
return False
n = len(p)
for r in (q, q[::-1]):
for s in range(n):
if all(p[i] == r[(i + s) % n] for i in range(n)):
return True
return False
def random_convex_polygon(rng, around_origin):
while True:
pts = [(rng.randint(-20, 20), rng.randint(-20, 20)) for _ in range(rng.randint(3, 14))]
h = hull_2d(pts)
if len(h) < 3:
continue
if around_origin:
k = len(h)
if not all((h[(i + 1) % k][0] - h[i][0]) * (0 - h[i][1]) - (h[(i + 1) % k][1] - h[i][1]) * (0 - h[i][0]) > 0 for i in range(k)):
continue
return h
def prism(poly, h):
k = len(poly)
verts = [(x, y, 0) for x, y in poly] + [(x, y, h) for x, y in poly]
faces = [list(range(k - 1, -1, -1)), list(range(k, 2 * k))]
for i in range(k):
j = (i + 1) % k
faces.append([i, j, k + j, k + i])
return verts, faces
def bipyramid(poly, h):
k = len(poly)
verts = [(x, y, 0) for x, y in poly] + [(0, 0, h), (0, 0, -h)]
faces = []
for i in range(k):
j = (i + 1) % k
faces.append([i, j, k])
faces.append([j, i, k + 1])
return verts, faces
def terrain(rng, nx, ny, hmax):
"""A closed heightfield block: triangulated top, walls and bottom."""
def top(i, j):
return i * (ny + 1) + j
def bot(i, j):
return (nx + 1) * (ny + 1) + top(i, j)
verts = [(i, j, rng.randint(1, hmax)) for i in range(nx + 1) for j in range(ny + 1)]
verts += [(i, j, 0) for i in range(nx + 1) for j in range(ny + 1)]
faces = []
for i in range(nx):
for j in range(ny):
a, b, c, e = top(i, j), top(i + 1, j), top(i + 1, j + 1), top(i, j + 1)
faces += [[a, b, c], [a, c, e]]
a, b, c, e = bot(i, j), bot(i + 1, j), bot(i + 1, j + 1), bot(i, j + 1)
faces += [[a, c, b], [a, e, c]]
quads = []
for i in range(nx):
quads.append((bot(i, 0), bot(i + 1, 0), top(i + 1, 0), top(i, 0)))
quads.append((bot(i + 1, ny), bot(i, ny), top(i, ny), top(i + 1, ny)))
for j in range(ny):
quads.append((bot(0, j + 1), bot(0, j), top(0, j), top(0, j + 1)))
quads.append((bot(nx, j), bot(nx, j + 1), top(nx, j + 1), top(nx, j)))
for a, b, c, e in quads:
faces += [[a, b, c], [a, c, e]]
return verts, faces
def linear_map(rng, verts, faces):
while True:
m = [[rng.randint(-3, 3) for _ in range(3)] for _ in range(3)]
det = dot(m[0], cross(m[1], m[2]))
if det != 0:
break
nv = [tuple(dot(row, v) for row in m) for v in verts]
nf = [list(f) if det > 0 else list(reversed(f)) for f in faces]
return nv, nf
def volume6(verts, faces):
total = 0
for f in faces:
for i in range(1, len(f) - 1):
total += dot(verts[f[0]], cross(verts[f[i]], verts[f[i + 1]]))
return total
def brute_signs(verts, faces, d, zero_side):
"""Face signs from the cross product of the first three vertices, in Fraction."""
out = []
for f in faces:
p0, p1, p2 = ([Fraction(c) for c in verts[i]] for i in f[:3])
n = cross(sub(p1, p0), sub(p2, p0))
s = dot(n, [Fraction(c) for c in d])
out.append(1 if s > 0 else -1 if s < 0 else zero_side)
return out
def brute_silhouette(verts, faces, d, zero_side=-1):
"""Compare every pair of faces: an edge is on the silhouette if its two faces differ in sign."""
signs = brute_signs(verts, faces, d, zero_side)
edges = [set(frozenset((f[i], f[(i + 1) % len(f)])) for i in range(len(f))) for f in faces]
out = set()
for i in range(len(faces)):
for j in range(i + 1, len(faces)):
if signs[i] != signs[j]:
for e in edges[i] & edges[j]:
out.add(tuple(sorted(e)))
return out
def projection_basis(d):
axes = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
e = min(axes, key=lambda a: abs(dot(a, d)))
a = cross(d, e)
b = cross(d, a)
return a, b
class TestPartingLines(unittest.TestCase):
def check_loops(self, verts, faces, d, zero_side=-1):
loops = parting_loops(verts, faces, d, zero_side)
signs = face_signs(verts, faces, d, zero_side)
upper_half_edges = set()
for fi, f in enumerate(faces):
if signs[fi] > 0:
upper_half_edges |= {(f[i], f[(i + 1) % len(f)]) for i in range(len(f))}
seen = []
for loop in loops:
for i in range(len(loop)):
h = (loop[i], loop[(i + 1) % len(loop)])
self.assertIn(h, upper_half_edges)
seen.append(tuple(sorted(h)))
expected = brute_silhouette(verts, faces, d, zero_side)
self.assertEqual(len(seen), len(set(seen)))
self.assertEqual(set(seen), expected)
self.assertEqual(silhouette_edges(verts, faces, d, zero_side), expected)
return loops
def test_pyramid_trace(self):
d = (1, 0, 1)
self.assertEqual([newell_normal(PYR_V, f) for f in PYR_F], [(0, 0, -8), (0, -4, 2), (4, 0, 2), (0, 4, 2), (-4, 0, 2)])
self.assertEqual(face_signs(PYR_V, PYR_F, d), [-1, 1, 1, 1, -1])
self.assertEqual(parting_loops(PYR_V, PYR_F, d), [[0, 1, 2, 3, 4]])
self.check_loops(PYR_V, PYR_F, d)
def test_box_vertical_faces(self):
# d = z: the four walls have n . d = 0, and zero_side decides where they go.
d = (0, 0, 1)
self.assertEqual(parting_loops(BOX_V, BOX_F, d, -1), [[4, 5, 6, 7]])
self.assertEqual(parting_loops(BOX_V, BOX_F, d, 1), [[0, 1, 2, 3]])
self.check_loops(BOX_V, BOX_F, d, -1)
self.check_loops(BOX_V, BOX_F, d, 1)
def test_box_tilted(self):
loops = self.check_loops(BOX_V, BOX_F, (1, 1, 1))
self.assertEqual(len(loops), 1)
self.assertEqual(len(loops[0]), 6)
def test_bad_input(self):
with self.assertRaises(ValueError):
parting_loops(PYR_V, PYR_F[:-1], (0, 0, 1))
with self.assertRaises(ValueError):
face_signs(PYR_V, PYR_F, (0, 0, 1), 0)
def test_random_convex(self):
rng = random.Random(20261115)
done = 0
while done < 150:
poly = random_convex_polygon(rng, around_origin=True)
maker = prism if done % 2 == 0 else bipyramid
verts, faces = maker(poly, rng.randint(1, 15))
verts, faces = linear_map(rng, verts, faces)
self.assertGreater(volume6(verts, faces), 0)
d = (rng.randint(-5, 5), rng.randint(-5, 5), rng.randint(-5, 5))
if d == (0, 0, 0):
continue
if any(dot(newell_normal(verts, f), d) == 0 for f in faces):
continue # not in general position; the theorem needs n . d != 0
loops = self.check_loops(verts, faces, d)
self.assertEqual(len(loops), 1)
loop = loops[0]
self.assertEqual(len(loop), len(set(loop)))
a, b = projection_basis(d)
proj = [(dot(a, verts[v]), dot(b, verts[v])) for v in loop]
hull = hull_2d([(dot(a, v), dot(b, v)) for v in verts])
self.assertTrue(same_cycle(strict_corners(proj), hull))
done += 1
def test_random_terrain(self):
rng = random.Random(7)
for trial in range(40):
verts, faces = terrain(rng, rng.randint(1, 6), rng.randint(1, 6), rng.randint(1, 6))
self.assertGreater(volume6(verts, faces), 0)
d = (rng.randint(-3, 3), rng.randint(-3, 3), rng.randint(1, 4))
for zero_side in (-1, 1):
self.check_loops(verts, faces, d, zero_side)
def test_flat_terrain_is_one_loop(self):
# A terrain with a constant height and d = z: the top face set is the upper region.
rng = random.Random(3)
verts, faces = terrain(rng, 3, 2, 1)
loops = self.check_loops(verts, faces, (0, 0, 1))
self.assertEqual(len(loops), 1)
self.assertEqual(len(loops[0]), 2 * (3 + 2))
if __name__ == "__main__":
unittest.main()
History
The two-piece mold model, with the faces of a part split by their direction relative to the parting direction, is the base of the geometric work on casting by Bose, Bremner and van Kreveld (1997) and by Ahn and coauthors, first at SoCG 1997 and in Computer-Aided Design in 2002. In mold CAD, parting lines were derived from the silhouette in the parting direction. Weinstein and Manoochehri (1997) chose among parting lines by manufacturing criteria. Fu, Nee and Fuh (2002) classified the faces by visibility and moldability and chose the 3D parting line among the edge loops by their projected area.
References
- M. W. Fu, A. Y. C. Nee and J. Y. H. Fuh, The application of surface visibility and moldability to parting line generation, Computer-Aided Design 34(6), 2002, 469 to 480, the classification of the faces by their orientation to the parting direction, the edge loops between the classes, and the choice of a 3D parting line from the projected areas of the loops
- Optimum parting line design of molded and cast parts for manufacturability, Journal of Manufacturing Systems 16(1), 1997, the choice of a parting line among candidates by manufacturing criteria (authors and pages not confirmed here)
- Hee-Kap Ahn, Mark de Berg, Prosenjit Bose, Siu-Wing Cheng, Dan Halperin, Jiri Matousek and Otfried Schwarzkopf, Separating an object from its cast, Computer-Aided Design 34(8), 2002, 547 to 559, the two-piece cast model, in which the parting surface splits the part into the faces seen from +d and from -d, and the test of one direction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D4D190 Edit this page History Report an error Markdown