Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.5

0.9.5 / src / meshing / bands.lucb

## Faces meshed as bands of quads (patch_dispatch.lucb): a B-spline face
## ruled in one direction (linear in v, proved from its control net and
## checked at every boundary sample), and a cylinder's or cone's closed
## band between two circles with its seam used twice.

## Whether `a` and `b` are within `tolerance`.
func near_points(a: Vector3, b: Vector3, tolerance: f64) -> bool:
    return a.subtract(b).length() <= tolerance

## Prove linearity in V from the control net, then verify all boundary samples.
## Unsupported nonrectangular/general trimmed patches fail rather than leak.
func ruled(mesh: MeshBuilder*, face: BrepFace, surface: Surface, edges: const Curve[], samples: const Samples[], tolerance: f64, transposed: bool = false) -> !:
    if face.sizes.length != 1 or face.uses.length != 4:
        error(invalid, "NURBS face needs a four-edge ruled boundary in this tessellator")
    let u0 = surface.ku[(usize)surface.du]
    let u1 = surface.ku[(usize)surface.nu]
    var v0 = surface.kv[(usize)surface.dv]
    var v1 = surface.kv[(usize)surface.nv]
    var linear = true
    for u in 0..<(usize)surface.nu:
        let first = u * (usize)surface.nv
        let a = surface.points[first]
        let b = surface.points[first + (usize)surface.nv - 1]
        for v in 0..<(usize)surface.nv:
            var greville: f64 = 0.0
            for index in 1..<(usize)surface.dv + 1:
                greville += surface.kv[v + index] / (f64)surface.dv
            let expected = a.add(b.subtract(a).multiply_scalar((greville - v0) / (v1 - v0)))
            if not near_points(expected, surface.points[first + v], tolerance) or math.abs(surface.weights[first + v] - surface.weights[first]) > 0.000000000001:
                linear = false
    if not linear:
        if transposed:
            error(invalid, "general trimmed non-ruled NURBS tessellation is not supported yet")
        let points = try new Vector3[surface.points.length] --- in memory.heap
        defer free(points) in memory.heap
        let weights = try new f64[surface.weights.length] --- in memory.heap
        defer free(weights) in memory.heap
        for u in 0..<(usize)surface.nu:
            for v in 0..<(usize)surface.nv:
                points[v * (usize)surface.nu + u] = surface.points[u * (usize)surface.nv + v]
                weights[v * (usize)surface.nu + u] = surface.weights[u * (usize)surface.nv + v]
        var swapped = try Surface(3, surface.origin, surface.x, surface.z, 0.0, 0.0, points, weights, surface.kv, surface.ku, surface.nv, surface.nu, surface.dv, surface.du)
        swapped.edited = surface.edited
        swapped.trim_tolerance = surface.trim_tolerance
        defer swapped.close()
        let reversed = try BrepFace(face.surface, face.uses, face.sizes, not face.sense)
        defer reversed.close()
        try ruled(mesh, reversed, swapped, edges, samples, tolerance, true)
        return
    let original_low = v0
    let original_high = v1
    let base = try surface.at(u0, v0)
    let span = (try surface.at(u0, v1)).subtract(base)
    var minimum: f64 = 1e100
    var maximum: f64 = -1e100
    for use in face.uses:
        let edge = edges[edge_index(use)]
        for id in [edge.start, edge.end]:
            let p = mesh.points[(usize)id]
            let t = p.subtract(base).dot(span) / span.dot(span)
            if near_points(p, base.add(span.multiply_scalar(t)), tolerance):
                minimum = math.min(minimum, t)
                maximum = math.max(maximum, t)
    if minimum < maximum and minimum >= -0.000001 and maximum <= 1.000001:
        v0 = original_low + (original_high - original_low) * math.clamp(minimum, 0.0, 1.0)
        v1 = original_low + (original_high - original_low) * math.clamp(maximum, 0.0, 1.0)
    let a = try surface.at(u0, v0)
    let b = try surface.at(u1, v0)
    let c = try surface.at(u0, v1)
    let d = try surface.at(u1, v1)
    var lower: i64 = -1
    var upper: i64 = -1
    var low_forward = true
    var high_forward = true
    var sides: usize = 0
    for use in face.uses:
        let index = edge_index(use)
        let edge = edges[index]
        let start = mesh.points[(usize)edge.start]
        let end = mesh.points[(usize)edge.end]
        if (near_points(start, a, tolerance) and near_points(end, b, tolerance)) or (near_points(start, b, tolerance) and near_points(end, a, tolerance)):
            lower = (i64)index
            low_forward = near_points(start, a, tolerance)
        elif (near_points(start, c, tolerance) and near_points(end, d, tolerance)) or (near_points(start, d, tolerance) and near_points(end, c, tolerance)):
            upper = (i64)index
            high_forward = near_points(start, c, tolerance)
        elif edge.kind == curve_line and ((near_points(start, a, tolerance) and near_points(end, c, tolerance)) or (near_points(start, c, tolerance) and near_points(end, a, tolerance)) or (near_points(start, b, tolerance) and near_points(end, d, tolerance)) or (near_points(start, d, tolerance) and near_points(end, b, tolerance))):
            sides += 1
        else:
            error(invalid, "NURBS face boundary is not the complete ruled parameter rectangle")
    if lower < 0 or upper < 0 or sides != 2:
        error(invalid, "NURBS ruled face is missing its boundary edges")
    let low = samples[(usize)lower].ids
    let high = samples[(usize)upper].ids
    if low.length != high.length:
        error(invalid, "opposing NURBS edges have incompatible discretizations")
    for at in 0..<low.length:
        let u = u0 + (u1 - u0) * (f64)at / (f64)(low.length - 1)
        let li = low[at if low_forward else low.length - 1 - at]
        let hi = high[at if high_forward else high.length - 1 - at]
        if not near_points(mesh.points[(usize)li], try surface.at(u, v0), tolerance) or not near_points(mesh.points[(usize)hi], try surface.at(u, v1), tolerance):
            error(invalid, "B-rep spline edge and surface parameterizations disagree")
    let lower_ids = try new i64[low.length] --- in memory.heap
    defer free(lower_ids) in memory.heap
    let upper_ids = try new i64[high.length] --- in memory.heap
    defer free(upper_ids) in memory.heap
    for at in 0..<low.length:
        lower_ids[at] = low[at if low_forward else low.length - 1 - at]
        upper_ids[at] = high[at if high_forward else high.length - 1 - at]
    try stitch_strip(mesh, face, edges, samples, lower_ids, upper_ids, not face.sense)

func quad(mesh: MeshBuilder*, a: i64, b: i64, c: i64, d: i64, reversed: bool) -> !:
    try mesh.face(4)
    for index in [a, d if reversed else b, c, b if reversed else d]:
        try mesh.corner(index)

func stitch_strip(mesh: MeshBuilder*, face: BrepFace, edges: const Curve[], samples: const Samples[], low: const i64[], high: const i64[], reversed: bool) -> !:
    var left: i64 = -1
    var right: i64 = -1
    for use in face.uses:
        let index = edge_index(use)
        let edge = edges[index]
        if (edge.start == low[0] and edge.end == high[0]) or (edge.end == low[0] and edge.start == high[0]):
            left = (i64)index
        if (edge.start == low[low.length - 1] and edge.end == high[high.length - 1]) or (edge.end == low[low.length - 1] and edge.start == high[high.length - 1]):
            right = (i64)index
    if left < 0 or right < 0:
        error(invalid, "structured patch has no matching side edges")
    let l = samples[(usize)left].ids
    let r = samples[(usize)right].ids
    if l.length != r.length or low.length != high.length or l.length * low.length > 16384:
        error(invalid, "structured patch grid is incompatible or exceeds point budget")
    let grid = try new i64[l.length * low.length] --- in memory.heap
    defer free(grid) in memory.heap
    let closed = low[0] == low[low.length - 1]
    for row in 0..<l.length:
        let fraction = (f64)row / (f64)(l.length - 1)
        for column in 0..<low.length:
            var id: i64 = -1
            if row == 0:
                id = low[column]
            elif row + 1 == l.length:
                id = high[column]
            elif column == 0:
                id = l[row if l[0] == low[0] else l.length - 1 - row]
            elif column + 1 == low.length:
                id = grid[row * low.length] if closed else r[row if r[0] == low[column] else r.length - 1 - row]
            else:
                let a = mesh.points[(usize)low[column]]
                let b = mesh.points[(usize)high[column]]
                id = try mesh.point(a.add(b.subtract(a).multiply_scalar(fraction)))
            grid[row * low.length + column] = id
    for row in 0..<l.length - 1:
        for column in 0..<low.length - 1:
            let at = row * low.length + column
            try quad(mesh, grid[at], grid[at + 1], grid[at + low.length + 1], grid[at + low.length], reversed)

## Circular closed bands, including a topological seam used twice by the face.
func periodic_band(mesh: MeshBuilder*, face: BrepFace, surface: Surface, edges: const Curve[], samples: const Samples[], tolerance: f64) -> !:
    if face.sizes.length != 1 or face.uses.length != 4:
        error(invalid, "cylinder/cone requires a closed circular band with a seam")
    var rings: i64[2]
    var count: usize = 0
    var seam: i64 = -1
    var seam_count: usize = 0
    for use in face.uses:
        let index = edge_index(use)
        let edge = edges[index]
        if edge.kind == curve_circle and count < 2:
            rings[count] = (i64)index
            count += 1
        elif edge.kind == curve_line:
            seam = (i64)index
            seam_count += 1
        else:
            error(invalid, "unsupported periodic surface trim")
    if count != 2 or seam < 0 or seam_count != 2:
        error(invalid, "periodic face is missing rings or seam")
    let first = samples[(usize)rings[0]].ids
    let second = samples[(usize)rings[1]].ids
    if first.length != second.length or first.length < 4:
        error(invalid, "periodic rings have incompatible discretization")
    let tangent = math.sin(surface.angle) / math.cos(surface.angle) if surface.kind == surface_cone else 0.0
    for ring in rings:
        for id in samples[(usize)ring].ids:
            let relative = mesh.points[(usize)id].subtract(surface.origin)
            let axial = relative.dot(surface.z)
            let radius = relative.subtract(surface.z.multiply_scalar(axial)).length()
            if math.abs(radius - surface.radius - axial * tangent) > surface.trims_within(tolerance):
                error(invalid, "circular boundary is not on its analytic support surface")
    let a0 = mesh.points[(usize)first[0]]
    let b0 = mesh.points[(usize)second[0]]
    let radial_a = try radial_offset(a0, surface).normalized()
    let closed = first[0] == first[first.length - 1]
    let forward = near_points(try radial_offset(mesh.points[(usize)first[1]], surface).normalized(), try radial_offset(mesh.points[(usize)second[1]], surface).normalized(), tolerance) if closed else near_points(radial_a, try radial_offset(b0, surface).normalized(), tolerance)
    if not near_points(radial_a, try radial_offset(mesh.points[(usize)second[0 if forward else second.length - 1]], surface).normalized(), tolerance):
        error(invalid, "circular band endpoints have different angles")
    let steps = first.length - 1
    let paired = try new i64[second.length] --- in memory.heap
    defer free(paired) in memory.heap
    for at in 0..<paired.length:
        paired[at] = second[at if forward else steps - at]
    var reversed = false
    for at in 0..<steps:
        let a = first[at]
        let b = first[at + 1]
        let c = second[at + 1 if forward else steps - at - 1]
        let d = second[at if forward else steps - at]
        if not near_points(try radial_offset(mesh.points[(usize)a], surface).normalized(), try radial_offset(mesh.points[(usize)d], surface).normalized(), tolerance):
            error(invalid, "periodic ring samples cannot be paired")
        let pa = mesh.points[(usize)a]
        let pb = mesh.points[(usize)b]
        let pd = mesh.points[(usize)d]
        let outward = (try radial_offset(pa.add(pb).multiply_scalar(0.5), surface).normalized()).subtract(surface.z.multiply_scalar(tangent))
        let normal = pb.subtract(pa).cross(pd.subtract(pa))
        reversed = (normal.dot(outward) < 0.0) == face.sense
    try stitch_strip(mesh, face, edges, samples, first, paired, reversed)

func radial_offset(point: Vector3, surface: Surface) -> Vector3:
    let relative = point.subtract(surface.origin)
    return relative.subtract(surface.z.multiply_scalar(relative.dot(surface.z)))