Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / src / modeling / blend.lucb

## Chamfers and fillets made with booleans (the first rows of OpenCASCADE's
## ChFiKPart table): for each chosen edge a tool solid (blend_tools.lucb),
## the corner the blend takes away (a convex edge) or adds (a concave one),
## swept along the edge or turned about a rim's axis. Edges blended: lines
## between two planes, lines between a plane and a cylinder along them (a
## D-shaft's flat), and rims (a circle or arc between a flat face and a
## cylinder or cone about it). A chamfer's tool is the triangle between the
## edge and the points `distance` along each face; a fillet's the region
## between the edge and its section (a circle of `radius` touching both
## faces, or a G2/G3 B-spline). Where fillets meet at corners: corners.lucb
## (balls), setback.lucb (G2/G3); every edge of a convex polyhedron rounded
## whole: rounded.lucb. Straight edges between planes are first tried
## directly (local_blend.lucb). Whether a blend fits: blend_fits.lucb.

## The unit direction across face `f` from the middle of edge `e`, into the
## face, perpendicular to the edge.
func into_face(w: const Shape*, f: usize, e: usize, along: Vector3) -> Vector3!:
    let middle = try w.edge_at(e, 0.5)
    let n = try w.face_normal(f, middle)
    let side = try n.cross(along).normalized()
    let reach = math.max((try w.edge_at(e, 0.0)).subtract(try w.edge_at(e, 1.0)).length(), (try w.edge_at(e, 0.0)).subtract(middle).length()) * 0.01
    if try face_contains(w, f, middle.add(side.multiply_scalar(reach)), w.tolerance) == inside_face: return side
    return side.multiply_scalar(-1.0)

## The unit direction along edge `e` at its middle.
func along_edge(w: const Shape*, e: usize) -> Vector3!:
    let edge = w.edges.items[e]
    let t = (edge.t0 + edge.t1) * 0.5
    return try (try w.tangent(edge.carrier, t)).multiply_scalar(1.0 if edge.t1 > edge.t0 else -1.0).normalized()

## A circle, or an arc of one, between a flat face across its axis and a
## cylinder or cone about it (a hole's rim, a boss's edge, the edge around
## an earlier fillet, a countersink's rim).
func is_rim(w: const Shape*, e: usize, fa: usize, fb: usize) -> bool:
    let edge = w.edges.items[e]
    let c = w.carriers.items[(usize)edge.carrier]
    if c.kind != curve_circle: return false
    let axis = c.x.cross(c.y)
    let sa = w.surfaces.items[(usize)w.faces.items[fa].surface]
    let sb = w.surfaces.items[(usize)w.faces.items[fb].surface]
    let plane = sa if sa.kind == surface_plane else sb
    let round = sb if sa.kind == surface_plane else sa
    if plane.kind != surface_plane or (round.kind != surface_cylinder and round.kind != surface_cone): return false
    if math.abs(math.abs(plane.z.dot(axis)) - 1.0) > 1e-9 or math.abs(math.abs(round.z.dot(axis)) - 1.0) > 1e-9: return false
    # On the cylinder or cone, about its axis: its radius there is the
    # circle's (a cone's along its height).
    let offset = c.origin.subtract(round.origin)
    let height = offset.dot(round.z)
    let radius = round.radius + (height * math.tan(round.angle) if round.kind == surface_cone else 0.0)
    return offset.subtract(round.z.multiply_scalar(height)).length() < c.a * 1e-6 and math.abs(radius - c.a) < c.a * 1e-6

## Whether edge `e` can be blended: a line between two planar faces, or a
## rim (is_rim), convex or concave but not flat.
func blendable(w: const Shape*, e: usize) -> bool!:
    let edge = w.edges.items[e]
    let kind = w.carriers.items[(usize)edge.carrier].kind
    if kind != curve_line and kind != curve_circle: return false
    # A seam (one face's both ways) is no edge between two faces.
    let (fa, fb) = edge_faces(w, e) catch failure:
        _ = failure
        return false
    if kind == curve_circle:
        if not is_rim(w, e, fa, fb): return false
    elif not flat_pair(w, fa, fb) and ruled_pair(w, e, fa, fb) < 0: return false
    let along = try along_edge(w, e)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    return ua.cross(ub).length() > 1e-9

func flat_pair(w: const Shape*, fa: usize, fb: usize) -> bool:
    return w.surfaces.items[(usize)w.faces.items[fa].surface].kind == surface_plane and w.surfaces.items[(usize)w.faces.items[fb].surface].kind == surface_plane

## Of a straight edge `e` between a plane and a cylinder along it (a
## D-shaft's flat, a slot's side meeting its round end), the cylinder's
## face (fa or fb); -1 when it is not one.
func ruled_pair(w: const Shape*, e: usize, fa: usize, fb: usize) -> i64:
    let sa = w.surfaces.items[(usize)w.faces.items[fa].surface]
    let sb = w.surfaces.items[(usize)w.faces.items[fb].surface]
    var cylinder: i64 = -1
    if sa.kind == surface_plane and sb.kind == surface_cylinder: cylinder = (i64)fb
    elif sa.kind == surface_cylinder and sb.kind == surface_plane: cylinder = (i64)fa
    else: return -1
    let c = w.surfaces.items[(usize)w.faces.items[(usize)cylinder].surface]
    let edge = w.edges.items[e]
    let direction = w.carriers.items[(usize)edge.carrier].x
    if c.z.cross(direction).length() > 1e-9: return -1
    return cylinder

## Whether edge `e`'s faces turn away from each other (the other face runs
## below this one's outward normal): a blend takes material away there.
## Concave edges (an inside corner) are blended by adding it.
func convex(w: const Shape*, e: usize) -> bool!:
    let (fa, fb) = try edge_faces(w, e)
    let ub = try into_face(w, fb, e, try along_edge(w, e))
    return ub.dot(try w.face_normal(fa, try w.edge_at(e, 0.5))) < 0.0

## `model` with the edges `references` refers to (references.lucb; empty:
## every straight convex edge between two planes) blended: filleted to
## `size` when `round`, else chamfered `size` along each face. The blend
## faces are named for feature `tag`. A fillet's `continuity` is 1 (G1,
## circular), 2 (G2) or 3 (G3): see corner_profile.
## With `chain`, each referenced edge brings the edges that continue it
## tangentially (Fusion's Tangent Chain): a slot's rim, the edges around an
## earlier fillet.
## `direct` false skips the direct build (local_blend.lucb), for tests
## that compare it with the booleans.
pub func blended(model: const CadModel*, references: str, size: f64, round: bool, tag: str, continuity: i64 = 1, chain: bool = true, direct: bool = true) -> interop.Reference[CadModel]!:
    var w = try shape_of(model)
    defer w.close()
    var chosen = Growing[usize]()
    defer chosen.close()
    try choose_edges(&w, references, chain, &chosen)
    return try blend_chosen(model, &w, chosen.view(), trimmed(references) == "", size, round, tag, continuity, direct, none)

## The edges of `w` that `references` names onto `chosen` (empty: every
## straight convex edge between flat faces; rims and inside corners only
## when named), with the edges continuing them tangentially when `chain`.
func choose_edges(w: Shape*, references: str, chain: bool, chosen: Growing[usize]*) -> !:
    if trimmed(references) == "":
        for e in 0..<w.edges.count:
            if w.carriers.items[(usize)w.edges.items[e].carrier].kind == curve_line and try blendable(w, e) and try convex(w, e): try chosen.push(e)
    else:
        try resolve_edges(w, references, chosen)
        for e in chosen.view():
            if not try blendable(w, e): error(invalid, "only straight edges between flat faces, and rims (a circle or arc between a flat face and a cylinder about it), can be blended yet")
        if chain: try tangent_chains(w, chosen)
    if chosen.count == 0: error(invalid, "the body has no edges to blend")

## `model` (its shape `w`) with edges `chosen` blended to `size` (`every`:
## they are every edge, as blended's empty references). `patches` keeps
## setback corners' patches between sizes (FilletPlan), when given.
func blend_chosen(model: const CadModel*, w: Shape*, chosen: const usize[], every: bool, size: f64, round: bool, tag: str, continuity: i64, direct: bool, patches: PatchCache*?) -> interop.Reference[CadModel]!:
    if not math.is_finite(size) or size <= 0.0: error(invalid, "a blend needs a positive size")
    if continuity < 1 or continuity > 3: error(invalid, "a fillet's continuity is G1, G2 or G3")
    # Each edge's blend must fit its faces: said precisely, before any tool.
    for e in chosen: try check_fits(w, e, size, round)
    # Straight edges between flat faces are built directly; what that
    # declines (curved faces at a corner, mixed corners, chamfers...) the
    # booleans below make.
    if round and direct:
        if let made = try local_blend(w, chosen, size, continuity, tag, patches): return made
    # Inside and outside fillets meeting at a corner: one side first, the
    # other then runs around it (a torus), by name on the result.
    if round and not every:
        var later = Growing[usize]()
        defer later.close()
        try mixed_order(w, chosen, &later)
        if later.count > 0:
            var first = Growing[i64]()
            defer first.close()
            var second = Growing[i64]()
            defer second.close()
            for e in chosen:
                if edge_in(later.view(), e): try second.push((i64)e)
                else: try first.push((i64)e)
            var text = Growing[u8]()
            defer text.close()
            try references_of(w, first.view(), &text)
            let earlier = try blended(model, (str)text.view(), size, round, tag, continuity, false, direct)
            defer earlier.release()
            try references_of(w, second.view(), &text)
            return try blended(earlier.value(), (str)text.view(), size, round, tag, continuity, true, direct)
    # Every edge of a convex polyhedron rounded: built whole.
    if round and every and continuity == 1:
        if let whole = try rounded_polyhedron(w, size, tag): return whole
    # Where three fillets meet, a ball rounds the corner.
    var balls = Growing[Ball]()
    defer balls.close()
    # Where three G2 or G3 fillets meet, a setback corner.
    var setbacks = Growing[Setback]()
    defer setbacks.close()
    # Where chained edges meet tangentially, their tools end square.
    var joints = Growing[i64]()
    defer joints.close()
    try fillet_corners(w, chosen, size, continuity, round, &balls, &setbacks, &joints)
    var body = try shape_rays(w)
    defer body.close()
    var tools = Growing[interop.Reference[CadModel]]()
    defer:
        for tool in tools.view(): tool.release()
        tools.close()
    # Whether each tool is added (a concave edge's) rather than taken away.
    var adds = Growing[bool]()
    defer adds.close()
    # Collinear chosen edges between the same two faces (one edge cut into
    # pieces by earlier operations) are one chain: one tool spans them.
    var done = Growing[bool]()
    defer done.close()
    for _ in chosen: try done.push(false)
    var name = Growing[u8]()
    defer name.close()
    for i in 0..<chosen.length:
        if done.items[i]: continue
        done.items[i] = true
        let e = chosen[i]
        var low = try w.edge_at(e, 0.0)
        var high = try w.edge_at(e, 1.0)
        try blend_name(w, e, tag, &name)
        let adding = not try convex(w, e)
        # A rim is its own tool.
        if w.carriers.items[(usize)w.edges.items[e].carrier].kind != curve_line:
            let edge = w.edges.items[e]
            let at_start = vertex_in(joints.view(), edge.start)
            let at_end = vertex_in(joints.view(), edge.end)
            try tools.push(try edge_tool(w, e, size, round, continuity, low, high, at_start, at_end, &body, (str)name.view()))
            try adds.push(adding)
            continue
        let (fa, fb) = try edge_faces(w, e)
        let along = try high.subtract(low).normalized()
        for j in i + 1..<chosen.length:
            if done.items[j]: continue
            let other = chosen[j]
            if not try same_curve(w, w.edges.items[e].carrier, other, w.tolerance): continue
            let (ga, gb) = try edge_faces(w, other)
            if not ((ga == fa and gb == fb) or (ga == fb and gb == fa)): continue
            done.items[j] = true
            for k in 0..<2:
                let p = try w.edge_at(other, (f64)k)
                if p.subtract(low).dot(along) < 0.0: low = p
                if p.subtract(high).dot(along) > 0.0: high = p
        # An end at a ball's corner stops where the ball's center is along it.
        var exact_low = false
        var exact_high = false
        for ball in balls.view():
            let corner = w.points.items[(usize)ball.vertex]
            let foot = low.add(along.multiply_scalar(ball.center.subtract(low).dot(along)))
            if corner.subtract(low).length() <= w.tolerance * 10.0:
                low = foot
                exact_low = true
            elif corner.subtract(high).length() <= w.tolerance * 10.0:
                high = foot
                exact_high = true
        # An end at a setback corner stops at its setback.
        for corner in setbacks.view():
            let apex = w.points.items[(usize)corner.vertex]
            for k in 0..<(usize)3:
                if math.abs(corner.ways[k].dot(along)) < 1.0 - 1e-9: continue
                let foot = apex.add(corner.ways[k].multiply_scalar(corner.distances[k]))
                if apex.subtract(low).length() <= w.tolerance * 10.0:
                    low = foot
                    exact_low = true
                elif apex.subtract(high).length() <= w.tolerance * 10.0:
                    high = foot
                    exact_high = true
        # The corners at both ends must leave the edge some length.
        if exact_low or exact_high:
            let original = try w.edge_at(e, 1.0).subtract(try w.edge_at(e, 0.0)).length()
            let left = high.subtract(low).dot(along)
            if left <= w.tolerance * 10.0:
                let most = size * original / (original - left)
                var buffer: u8[256]
                let owned = try interop.copy_text(try strings.format(buffer, f"a fillet radius of {rounded_text(size)} is too large for this edge between its rounded corners: it must be less than {rounded_text(most)}"))
                if let owner = owned.owner: _ = ownership.pool_object(owner)
                error(invalid, owned.value)
        for v in joints.view():
            let corner = w.points.items[(usize)v]
            if corner.subtract(low).length() <= w.tolerance * 10.0: exact_low = true
            elif corner.subtract(high).length() <= w.tolerance * 10.0: exact_high = true
        if adding: try tools.push(try concave_tool(w, e, size, round, continuity, low, high, exact_low, exact_high, (str)name.view()))
        else: try tools.push(try edge_tool(w, e, size, round, continuity, low, high, exact_low, exact_high, &body, (str)name.view()))
        try adds.push(adding)
    for ball in balls.view():
        try corner_name(w, (usize)ball.vertex, tag, &name)
        try tools.push(try corner_tool(w, &ball, size, (str)name.view()))
        try adds.push(ball.inside)
    for corner in setbacks.view():
        try corner_name(w, (usize)corner.vertex, tag, &name)
        try tools.push(try setback_tool(w, &corner, size, continuity, (str)name.view()))
        try adds.push(corner.inside)
    # Material taken away first, then added.
    var result = try copy_model(model)
    for pass in 0..<2:
        for at in 0..<tools.count:
            if adds.items[at] != (pass == 1): continue
            let next = combine(result.value(), tools.items[at].value(), op_union if pass == 1 else op_subtract) catch failure:
                result.release()
                error(failure.code, failure.message)
            result.release()
            result = next
    return result

func edge_in(edges: const usize[], e: usize) -> bool:
    for known in edges:
        if known == e: return true
    return false

## The edges of `chosen` to fillet after the rest, where inside and
## outside fillets meet at a corner: the lone outside edge first where it
## meets two inside ones (a boss's upright on a plate: the base then runs
## around its fillet), the lone inside edge first where two outside ones
## meet it (an L's inside upright under its top edges). Others: refused.
func mixed_order(w: const Shape*, chosen: const usize[], later: Growing[usize]*) -> !:
    var seen = Growing[i64]()
    defer seen.close()
    var here = Growing[usize]()
    defer here.close()
    for e in chosen:
        let ends: i64[2] = [w.edges.items[e].start, w.edges.items[e].end]
        for v in ends:
            if vertex_in(seen.view(), v): continue
            try seen.push(v)
            here.clear()
            var concaves = 0
            for other in chosen:
                let o = w.edges.items[other]
                if o.start != v and o.end != v: continue
                try here.push(other)
                if not try convex(w, other): concaves += 1
            if concaves == 0 or concaves == (i64)here.count: continue
            if here.count != 3:
                error(invalid, "an inside-corner fillet meeting an outside one at a corner is supported where three edges meet: fillet them one at a time")
            # The lone kind goes first; the pair after.
            let lone_inside = concaves == 1
            for other in here.view():
                let goes_later = (not try convex(w, other)) != lone_inside
                if goes_later and not edge_in(later.view(), other): try later.push(other)
                if not goes_later and edge_in(later.view(), other): error(invalid, "these fillets meet at corners in orders that conflict: fillet them in two features")
    # An edge sent later at one corner but first at another conflicts.
    seen.clear()
    for e in later.view():
        let ends: i64[2] = [w.edges.items[e].start, w.edges.items[e].end]
        for v in ends:
            var concaves = 0
            var count = 0
            for other in chosen:
                let o = w.edges.items[other]
                if o.start != v and o.end != v: continue
                count += 1
                if not try convex(w, other): concaves += 1
            if concaves == 0 or concaves == count: continue
            if (not try convex(w, e)) == (concaves == 1): error(invalid, "these fillets meet at corners in orders that conflict: fillet them in two features")

func vertex_in(vertices: const i64[], v: i64) -> bool:
    for known in vertices:
        if known == v: return true
    return false

## `chosen` with the edges that continue its edges tangentially, of the
## same convexity, through vertices where nothing else could be blended
## (a slot's rim around its ends, the edges around an earlier fillet).
func tangent_chains(w: const Shape*, chosen: Growing[usize]*) -> !:
    var at: usize = 0
    while at < chosen.count:
        let e = chosen.items[at]
        at += 1
        let outward = try convex(w, e)
        for end in 0..<2:
            let v = w.edges.items[e].start if end == 0 else w.edges.items[e].end
            # Arriving at v along e.
            let arriving = (try w.leaving(e, (i64)end)).multiply_scalar(-1.0)
            for f in 0..<w.edges.count:
                if f == e: continue
                let other = w.edges.items[f]
                if other.start != v and other.end != v: continue
                var known = false
                for c in chosen.view():
                    if c == f: known = true
                if known: continue
                let leaving = try w.leaving(f, 0 if other.start == v else 1)
                if leaving.dot(arriving) < 1.0 - 1e-6: continue
                if not try blendable(w, f) or try convex(w, f) != outward: continue
                try chosen.push(f)

## The name of edge `e`'s blend, `tag/blend[A&B]`, into `out` (empty
## when its faces have no names).
func blend_name(w: const Shape*, e: usize, tag: str, out: Growing[u8]*) -> !:
    out.clear()
    let (fa, fb) = try edge_faces(w, e)
    if w.face_name(fa) == "" or w.face_name(fb) == "": return
    try role_name(out, tag, "blend[")
    try edge_name(w, e, out)
    try out.push(93)

## A new reference to `model`'s B-rep, placed as it is.
func copy_model(model: const CadModel*) -> interop.Reference[CadModel]!:
    var w = try shape_of(model)
    defer w.close()
    let b = try brep_of(&w)
    defer b.release()
    return try CadModel.of_brep(b)