Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / src / layout / trim_chains.lucb

## Topological trim chains in one support chart. A periodic seam has two UV
## uses even though both uses reference exactly the same canonical CAD edge.

pub func chain_face(chains: UVChain[], face: BrepFace, s: Surface, vertices: const Vector3[], edges: const Curve[], cuts: const Stations[], tolerance: f64) -> !:
    # Nonperiodic patches retain their original inverse-projection seeds. On
    # analytic periodic supports and repeated NURBS seams the seed must arrive
    # from the preceding coedge. Independent seeds turn ordinary cylinder joins
    # into 0/2pi jumps, even when no authored edge is used twice by the face.
    var seam = false
    for use in 0..<face.uses.length:
        for before in 0..<use:
            seam = seam or edge_index(face.uses[use]) == edge_index(face.uses[before])
    if not seam and s.kind != surface_cylinder and s.kind != surface_cone: return
    let gap = chart_gap(s, tolerance)
    let closed_u = try closed_axis(s, 0, tolerance)
    let closed_v = try closed_axis(s, 1, tolerance)
    var complete = false
    for initial in chart_seeds():
        var valid = true
        var offset: usize = 0
        var loop_seed = initial
        for size in face.sizes:
            var seed = loop_seed
            var first = Vector3()
            for entry in 0..<(usize)size:
                let at = offset + entry
                let use = face.uses[at]
                let index = edge_index(use)
                if chains[at].points.length > 0: free(chains[at].points) in memory.heap
                if chains[at].times.length > 0: free(chains[at].times) in memory.heap
                chains[at] = UVChain()
                let uv = try cached(&chains[at], s, vertices, edges[index], cuts[index], tolerance, seed, use > 0)
                let start = uv[0 if use > 0 else uv.length - 1]
                if entry == 0: first = start
                elif not chart_near(start, seed, gap): valid = false
                seed = uv[uv.length - 1 if use > 0 else 0]
                # A jump across a closed support inside one sampled coedge is
                # not an edge across the surface. Reject that chart branch.
                if s.kind == surface_spline:
                    for i in 1..<uv.length:
                        if (closed_u and math.abs(uv[i].x - uv[i - 1].x) > 0.5) or (closed_v and math.abs(uv[i].y - uv[i - 1].y) > 0.5): valid = false
            if not chart_near(seed, first, gap): valid = false
            # A hole may begin on the other side of atan2's branch. Seed it
            # inside the outer chart, not independently around zero. This is
            # an integer-period chart choice; canonical geometry is unchanged.
            if offset == 0 and (s.kind == surface_cylinder or s.kind == surface_cone):
                var span = Vector3(1e100, -1e100, 0.0)
                for at in 0..<(usize)size: span = angle_span(span, chains[at].points)
                loop_seed = hole_seed(span)
            offset += (usize)size
        if valid:
            complete = true
            break
    if not complete: error(invalid, "trim loops do not close in one support chart")

## The chart seeds a face's loops are chained from, in the order tried
## (the tessellator's and the exporter's alike): the chart's middle, then
## its corners.
pub func chart_seeds() -> Vector3[5]:
    return [Vector3(0.5, 0.5, 0.0), Vector3(0.0, 0.0, 0.0), Vector3(1.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector3(1.0, 1.0, 0.0)]

## `span` (lowest and highest angle, in x and y) widened by `points`.
pub func angle_span(span: Vector3, points: const Vector3[]) -> Vector3:
    var widened = span
    for p in points: widened = Vector3(math.min(widened.x, p.x), math.max(widened.y, p.x), 0.0)
    return widened

## Where a hole of a face on a cylinder or cone starts chaining: inside the
## outer loop's angles (`span`, angle_span), not around zero, since a hole
## may begin on the other side of atan2's branch.
pub func hole_seed(span: Vector3) -> Vector3:
    return Vector3((span.x + span.y) * 0.5, 0.0, 0.0)

func closed_axis(s: Surface, axis: usize, tolerance: f64) -> bool!:
    if s.kind != surface_spline: return false
    for at in 0..<5:
        let t = (f64)at / 4.0
        let a = try surface_point(s, Vector3(0.0 if axis == 0 else t, t if axis == 0 else 0.0, 0.0))
        let b = try surface_point(s, Vector3(1.0 if axis == 0 else t, t if axis == 0 else 1.0, 0.0))
        if a.subtract(b).length() > math.max(1e-9, tolerance * 0.1): return false
    return true

## Cached points remain in canonical edge order even when initialized backwards.
## New stations inherit the chart branch from the immutable old endpoints.
pub func cached(chain: UVChain*, s: Surface, vertices: const Vector3[], edge: Curve, stations: Stations, tolerance: f64, initial: Vector3 = Vector3(0.5, 0.5, 0.0), forward: bool = true, memo: TrimMemo*? = none) -> const Vector3[]!:
    if chain.points.length != stations.count:
        let fresh = try refreshed(*chain, s, vertices, edge, stations, tolerance, initial, forward, memo)
        if chain.points.length > 0: free(chain.points) in memory.heap
        if chain.times.length > 0: free(chain.times) in memory.heap
        chain.points = fresh.points
        chain.times = fresh.times
    return chain.points

## The chain `cached` would store for `stations`, as new arrays; `chain` is
## only read, so speculative passes can preview a refresh.
pub func refreshed(chain: UVChain, s: Surface, vertices: const Vector3[], edge: Curve, stations: Stations, tolerance: f64, initial: Vector3 = Vector3(0.5, 0.5, 0.0), forward: bool = true, memo: TrimMemo*? = none) -> UVChain!:
    let points = try new Vector3[stations.count] --- in memory.heap
    errdefer free(points) in memory.heap
    let times = try new f64[stations.count] --- in memory.heap
    errdefer free(times) in memory.heap
    var previous: usize = 0
    var seed = initial
    for step in 0..<points.length:
        let at = step if forward else points.length - 1 - step
        let t = stations.values[at]
        times[at] = t
        # Refreshes use canonical order; reverse traversal is only needed
        # for the very first topological chart construction.
        while previous < chain.times.length and chain.times[previous] < t - 1e-12: previous += 1
        if previous < chain.times.length and math.abs(chain.times[previous] - t) < 1e-12:
            seed = chain.points[previous]
        else:
            let p = vertices[(usize)edge.start] if at == 0 else (vertices[(usize)edge.end] if at + 1 == points.length else (try edge.at(t)))
            seed = try memo_parameter(memo, s, p, seed, tolerance)
        points[at] = seed
    var result = UVChain()
    result.points = points
    result.times = times
    return result

## A chart seam is cut in UV and stitched only after lifting. Preserve pinched
## vertices in the same chart, but never identify opposite periodic rails in 2D.
pub func chart_identities(s: Surface, uv: const Vector3[], ids: const i64[], tolerance: f64) -> i64[]!:
    let result = try new i64[ids.length] --- in memory.heap
    errdefer free(result) in memory.heap
    let table = try new i64[ids.length * 2 + 1] --- in memory.heap
    defer free(table) in memory.heap
    for at in 0..<table.length: table[at] = -1
    var checked = false
    var closed_u = false
    var closed_v = false
    for at in 0..<ids.length:
        var slot = (usize)ids[at] % table.length
        result[at] = (i64)at
        while table[slot] >= 0:
            let before = (usize)table[slot]
            if ids[before] == ids[at]:
                let d = uv[at].subtract(uv[before])
                if d.length() <= 1e-12:
                    result[at] = (i64)before
                    break
                if not checked:
                    closed_u = (try closed_axis(s, 0, tolerance)) if s.kind == surface_spline else s.kind != surface_plane
                    closed_v = (try closed_axis(s, 1, tolerance)) if s.kind == surface_spline else s.kind == surface_torus
                    checked = true
                let period_u = 1.0 if s.kind == surface_spline else 2.0 * math.pi
                let period_v = 1.0 if s.kind == surface_spline else (2.0 * math.pi if s.kind == surface_torus else 0.0)
                let du = math.abs(d.x)
                let dv = math.abs(d.y)
                let periodic_u = closed_u and math.abs(du - period_u) < 1e-8
                let periodic_v = closed_v and math.abs(dv - period_v) < 1e-8
                if not ((periodic_u and (dv < 1e-8 or periodic_v)) or (periodic_v and du < 1e-8)):
                    error(invalid, "one CAD vertex has inconsistent nonperiodic trim projections")
            slot = (slot + 1) % table.length
        if table[slot] < 0: table[slot] = (i64)at
    return result