Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.3

0.9.3 / src / modeling / setback.lucb

## Three or more fillets meeting at a corner of flat faces: G2 or G3 ones,
## G1 ones when Fusion's Setback corner type is asked for, and four or more
## G1 ones where no one ball touches every face (a rectangular pyramid's
## apex). No ball is tangent to G2 and G3 fillets: their sections are not
## circles. So, as Fusion and SolidWorks do, each fillet stops short of the
## corner, at its setback: a plane square to its edge. A G1 corner's A
## curves are the circles' arcs raised to degree 5, rational: the patch is
## fitted in homogeneous space (patch_fit.lucb). The hole between the N
## fillets' end sections and the N faces (2N sides) is filled by a patch
## with the fillets' continuity (patch_fit.lucb). The corner tool is the
## region between the sharp corner and the patch, cut off by the setback
## planes. It is taken away after the edges' tools (added, at an inside
## corner), and it leaves the patch. Its sides meet the body's faces only
## along curves both carry, which the booleans take as touching
## (splines.lucb).

## The most edges a setback corner takes.
let most_setback_edges: usize = 8

## A setback corner: its vertex; its `count` edges, ordered so that face i
## holds edges i and i + 1 (round the corner); each edge's unit way from
## the corner; how far along it the fillets stop. `inside` marks an inside
## corner, whose tool is added. Each edge's fillet radius, when they differ
## (`radii`, 0: the corner's one radius).
struct Setback:
    var vertex: i64
    var count: usize
    var edges: usize[8]
    var ways: Vector3[8]
    var distances: f64[8]
    var inside: bool
    var radii: f64[8]
    ## Fillets of both kinds (a vertex blend): its patch meets faces from
    ## either side, so no one cone holds it.
    var mixed: bool
    ## The curves on the faces' rho relative to the circle's, and the
    ## patch's bulge scale (BlendLimits.corner_shape, corner_fullness; 0
    ## Fusion's, fusion_fullness).
    var edge_shape: f64
    var fullness: f64
    ## Fusion's Rolling ball corner of three G2 or G3 fillets
    ## (three_sided.lucb): each stops through the ball's center, a
    ## three-sided patch between their end sections, no curves on the faces.
    var three_sided: bool
    ## Variable fillets on straight radius laws (variable_corners.lucb's
    ## law_setback): edge i's strip a cone (`coned[i]`) whose rulings meet
    ## at `apexes[i]` (where its radius would be 0), its radius growing by
    ## `growth[i]` per length away from the corner, its G1 section's middle
    ## weight `cone_weights[i]` (the ball's rolling: rolling_weight).
    var coned: bool[8]
    var apexes: Vector3[8]
    var growth: f64[8]
    var cone_weights: f64[8]

## A fillet's own end section at a setback corner (a G1 variable edge's
## rolled envelope, straight_law_tool): the six control points of edge
## `edge`'s section where it reaches corner `vertex`, from one face's
## contact to the other's. The corner's patch takes it as that side.
struct GivenSection:
    var vertex: i64
    var edge: usize
    var points: Vector3[6]

## An empty setback corner at vertex `v`.
func empty_setback(v: i64) -> Setback:
    return Setback(v, 0, [0, 0, 0, 0, 0, 0, 0, 0], [Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3()], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], false, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], false, 0.5, 0.0, false,
                   [false, false, false, false, false, false, false, false], [Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3()],
                   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])

## A setback corner of fillets of `radius` at vertex `v`, where `edges`
## (three or more, one per line through it) meet. Each fillet stops past
## where its neighbors' contacts cross its own on the faces (the farther
## crossing), by Fusion 2705's reach (probes 14 and 17 of 2026-10-13, a 20
## cube's corner with every mix of radii 1 to 6, G1 and G2, Setback and
## Rolling ball alike): the mean of the corner's contact distances, and
## for the one smallest fillet half the gap to the next smallest more. At a
## square corner of one radius that is 2 r; radii 2, 3 and 4 stop 7.5, 7
## and 6 from it; 1, 4 and 4 stop 8.5, 7 and 7. `hollow` marks an inside
## corner. With `radii` (one per edge of `edges`), each fillet has its own
## radius.
func setback_at(w: const Shape*, v: i64, edges: const usize[], radius: f64, hollow: bool, radii: (const f64[])? = none) -> Setback!:
    let n = edges.length
    if n < 3 or n > most_setback_edges: error(invalid, "a setback corner needs three to eight edges")
    var corner = empty_setback(v)
    corner.count = n
    corner.inside = hollow
    # Ordered round the corner: each next one shares a face with the last.
    var taken: bool[8] = [false, false, false, false, false, false, false, false]
    corner.edges[0] = edges[0]
    if let given = radii: corner.radii[0] = given[0]
    taken[0] = true
    for i in 1..<n:
        var found = false
        for j in 0..<n:
            if taken[j] or found: continue
            if try shared_face(w, corner.edges[i - 1], edges[j]) >= 0:
                corner.edges[i] = edges[j]
                if let given = radii: corner.radii[i] = given[j]
                taken[j] = true
                found = true
        if not found: error(invalid, "fillets meeting at a corner must go round it face by face")
    if try shared_face(w, corner.edges[n - 1], corner.edges[0]) < 0: error(invalid, "fillets meeting at a corner must go round it face by face")
    for i in 0..<n:
        let edge = w.edges.items[corner.edges[i]]
        corner.ways[i] = try w.leaving(corner.edges[i], 0 if edge.start == v else 1)
    let frame = try setback_frame(w, &corner, radius)
    let p = w.points.items[(usize)v]
    # The mean reach, and the smallest and next smallest (the smallest
    # alone when its next is larger).
    var mean = 0.0
    var least = 1e300
    for i in 0..<n:
        mean += frame.reaches[i] / (f64)n
        least = math.min(least, frame.reaches[i])
    var next_least = 1e300
    var lowest: usize = 0
    var ties: usize = 0
    for i in 0..<n:
        if frame.reaches[i] <= least * (1.0 + 1e-12):
            lowest = i
            ties += 1
        else: next_least = math.min(next_least, frame.reaches[i])
    for i in 0..<n:
        let beyond = mean + ((next_least - least) * 0.5 if ties == 1 and i == lowest and next_least < 1e299 else 0.0)
        let before = (i + n - 1) % n
        let next = (i + 1) % n
        let after = try contacts_cross(p, corner.ways[i], frame.intos[i * 2 + 1], frame.reaches[i], corner.ways[next], frame.intos[next * 2], frame.reaches[next])
        let behind = try contacts_cross(p, corner.ways[before], frame.intos[before * 2 + 1], frame.reaches[before], corner.ways[i], frame.intos[i * 2], frame.reaches[i])
        corner.distances[i] = math.max(after.subtract(p).dot(corner.ways[i]), behind.subtract(p).dot(corner.ways[i])) + beyond
    return corner

## Setback corner `corner` (of four or more edges) set back further, by a
## quarter of its distances at a time, up to three times, until its patch
## for `continuity` stays within its corner (a G1 corner's rational patch
## can bulge out of a face of an irregular apex when set back the least).
func roomy_setback(w: const Shape*, corner: Setback*, radius: f64, continuity: i64) -> !:
    var quads = Growing[Vector3]()
    defer quads.close()
    var weights = Growing[f64]()
    defer weights.close()
    var knots = Growing[f64]()
    defer knots.close()
    for attempt in 0..<4:
        quads.clear()
        weights.clear()
        knots.clear()
        var fits = true
        setback_patch(w, corner, radius, continuity, &quads, &weights, &knots) catch failure:
            if failure.code != invalid or attempt == 3: error(failure.code, failure.message)
            fits = false
            recover ()
        if fits: return
        for i in 0..<corner.count: corner.distances[i] *= 1.25

## Of a setback corner: each edge's contact distance (reaches[i]); its
## ways into its faces, perpendicular to it (into face i - 1 at
## intos[2 i], into face i at intos[2 i + 1]); and the faces (face i holds
## edges i and i + 1).
struct Frame:
    var reaches: f64[8]
    var intos: Vector3[16]
    var faces: usize[8]

func setback_frame(w: const Shape*, corner: const Setback*, radius: f64) -> Frame!:
    let n = corner.count
    var frame = Frame([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3()], [0, 0, 0, 0, 0, 0, 0, 0])
    for i in 0..<n:
        let f = try shared_face(w, corner.edges[i], corner.edges[(i + 1) % n])
        if f < 0 or w.surfaces.items[(usize)w.faces.items[(usize)f].surface].kind != surface_plane: error(invalid, "fillets meeting at a corner need flat faces there")
        frame.faces[i] = (usize)f
    for i in 0..<n:
        let along = corner.ways[i]
        frame.intos[i * 2] = try into_face(w, frame.faces[(i + n - 1) % n], corner.edges[i], along)
        frame.intos[i * 2 + 1] = try into_face(w, frame.faces[i], corner.edges[i], along)
        let angle = math.acos(math.clamp(frame.intos[i * 2].dot(frame.intos[i * 2 + 1]), -1.0, 1.0))
        frame.reaches[i] = (corner.radii[i] if corner.radii[i] > 0.0 else radius) / math.tan(angle * 0.5)
    return frame

## The face edges `a` and `b` share, or -1.
func shared_face(w: const Shape*, a: usize, b: usize) -> i64!:
    let (fa, fb) = try edge_faces(w, a)
    let (ga, gb) = try edge_faces(w, b)
    if fa == ga or fa == gb: return (i64)fa
    if fb == ga or fb == gb: return (i64)fb
    return -1

## Where fillet `i`'s contact line on face i crosses fillet `next`'s on it
## (`frame`'s reaches at the corner's setbacks): a cone's contact line runs
## to its apex (its radius changing along it), a plain one along its edge.
func contact_lines_cross(p: Vector3, corner: const Setback*, frame: const Frame*, i: usize, next: usize) -> Vector3!:
    let ta = p.add(corner.ways[i].multiply_scalar(corner.distances[i])).add(frame.intos[i * 2 + 1].multiply_scalar(frame.reaches[i]))
    let tb = p.add(corner.ways[next].multiply_scalar(corner.distances[next])).add(frame.intos[next * 2].multiply_scalar(frame.reaches[next]))
    var da = corner.ways[i]
    if corner.coned[i]: da = try ta.subtract(corner.apexes[i]).normalized()
    var db = corner.ways[next]
    if corner.coned[next]: db = try tb.subtract(corner.apexes[next]).normalized()
    let k = da.dot(db)
    let det = 1.0 - k * k
    if det < 1e-12: error(invalid, "fillets meeting at a corner run along one line")
    let r = ta.subtract(tb)
    let s = (k * r.dot(db) - r.dot(da)) / det
    return ta.add(da.multiply_scalar(s))

## Where two fillets' contact lines cross on the face they share: fillet
## `a` runs along `way_a` from corner `p`, its contact `reach_a` into the
## face along `into_a`; likewise `b`.
func contacts_cross(p: Vector3, way_a: Vector3, into_a: Vector3, reach_a: f64, way_b: Vector3, into_b: Vector3, reach_b: f64) -> Vector3!:
    let pa = p.add(into_a.multiply_scalar(reach_a))
    let pb = p.add(into_b.multiply_scalar(reach_b))
    let k = way_a.dot(way_b)
    let det = 1.0 - k * k
    if det < 1e-12: error(invalid, "fillets meeting at a corner run along one line")
    let r = pa.subtract(pb)
    let s = (k * r.dot(way_b) - r.dot(way_a)) / det
    return pa.add(way_a.multiply_scalar(s))

## A setback corner's tool for fillets of `radius` and `continuity`: the
## region between the sharp corner and the patch, within the setback
## planes. The patch's quads are named `name`.
func setback_tool(w: const Shape*, corner: const Setback*, radius: f64, continuity: i64, name: str, blend_shape: BlendShape = plain_blend, given: (const GivenSection[])? = none) -> interop.Reference[CadModel]!:
    if corner.three_sided: return try three_sided_tool(w, corner, radius, continuity, name, blend_shape)
    var quads = Growing[Vector3]()
    defer quads.close()
    var quad_weights = Growing[f64]()
    defer quad_weights.close()
    var quad_knots = Growing[f64]()
    defer quad_knots.close()
    try setback_patch(w, corner, radius, continuity, &quads, &quad_weights, &quad_knots, blend_shape, given)
    let p = w.points.items[(usize)corner.vertex]
    let cone = try corner_cone(w, corner, radius)
    return try corner_solid(p, corner, quads.view(), quad_weights.view(), cone[..<corner.count], quad_knots.view(), quad_knots.count - 6, name)

## Each face's outward normal at a setback corner, turned to face away
## from the corner's inside (along the edge before it, not on the face).
func corner_cone(w: const Shape*, corner: const Setback*, radius: f64) -> Vector3[8]!:
    let n = corner.count
    let frame = try setback_frame(w, corner, radius)
    var cone: Vector3[8] = [Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3()]
    for i in 0..<n:
        let normal = face_outward(w, frame.faces[i])
        # Any edge at the corner not on face i lies inside, against its
        # outward normal: the next but one (or, of three, the one left).
        let other = corner.ways[(i + 2) % n]
        cone[i] = normal if normal.dot(other) > 0.0 else normal.multiply_scalar(-1.0)
    return cone

## A setback corner's patch for fillets of `radius` and `continuity`: 2N
## quads onto `quads` (patch_fit.lucb's order), their weights onto
## `quad_weights` (1 but at a G1 corner), their knots onto `quad_knots`.
## Its control points must stay between the faces and the setback planes
## (so it meets the body only along curves both carry).
## A fillet whose own end section is `given` takes it as its side.
func setback_patch(w: const Shape*, corner: const Setback*, radius: f64, continuity: i64, quads: Growing[Vector3]*, quad_weights: Growing[f64]*, quad_knots: Growing[f64]*, blend_shape: BlendShape = plain_blend, given: (const GivenSection[])? = none) -> !:
    let n = corner.count
    let frame = try setback_frame(w, corner, radius)
    let p = w.points.items[(usize)corner.vertex]
    # The hole's 2N curves: each fillet's end section (as its tool's
    # profile makes it) from face i - 1 to face i, then the curve on face i
    # to the next fillet's contact, legs along the contact lines. All are
    # the fillet's section (fillet_section), so they share knots.
    var curves = Growing[Vector3]()
    defer curves.close()
    var weights = Growing[f64]()
    defer weights.close()
    var knots = Growing[f64]()
    defer knots.close()
    var sides = Growing[HoleSide]()
    defer sides.close()
    # The A curves the fillets' sections (G1: the circles' arcs); the B
    # curves on the faces, G1, Fusion's circles tangent to both contact
    # lines (Edge shape makes them conics); G2 and G3, the fillet's own
    # section, flat at its ends: three points along each contact line, as
    # the strip's rows run beside it, so the patch keeps G2 there (Fusion's
    # circles would break it).
    for i in 0..<n:
        let next = (i + 1) % n
        let foot = p.add(corner.ways[i].multiply_scalar(corner.distances[i]))
        let ta = foot.add(frame.intos[i * 2].multiply_scalar(frame.reaches[i]))
        let tb = foot.add(frame.intos[i * 2 + 1].multiply_scalar(frame.reaches[i]))
        knots.clear()
        let own = given_section(given, corner.vertex, corner.edges[i])
        if own >= 0 and continuity == 1:
            # Its own section, run from face i - 1's contact to face i's.
            let first = curves.count
            let section = given_points(given, own)
            let forward = section[0].subtract(ta).length() <= section[5].subtract(ta).length()
            for k in 0..<(usize)6:
                try curves.push(section[k if forward else 5 - k])
                try weights.push(1.0)
            for _ in 0..<(usize)6: try knots.push(0.0)
            for _ in 0..<(usize)6: try knots.push(1.0)
            try middle_knot_twice(&curves, &weights, first, &knots)
        elif continuity == 1:
            # A cone's section: its rolling ball's middle weight.
            var shape = blend_shape
            if corner.coned[i]: shape = weighted_shape(corner.cone_weights[i] / math.sin(math.acos(math.clamp(frame.intos[i * 2].dot(frame.intos[i * 2 + 1]), -1.0, 1.0)) * 0.5))
            let first = curves.count
            try arc_section(ta, tb, foot, &curves, &weights, &knots, shape)
            try middle_knot_twice(&curves, &weights, first, &knots)
        else:
            try fillet_section(ta, tb, foot, continuity, &curves, &knots, blend_shape)
            while weights.count < curves.count: try weights.push(1.0)
        try sides.push(HoleSide(true, corner.ways[i], corner.apexes[i], corner.coned[i]))
        let cross = try contact_lines_cross(p, corner, &frame, i, next)
        let foot_next = p.add(corner.ways[next].multiply_scalar(corner.distances[next]))
        let tc = foot_next.add(frame.intos[next * 2].multiply_scalar(frame.reaches[next]))
        knots.clear()
        if continuity == 1:
            # Fusion's: the circle tangent to both contact lines (a conic
            # where they reach the crossing unequally), as a polynomial
            # quintic within 2e-5 of it, so the quads' rows stay exact.
            let first = curves.count
            try round_quintic(tb, tc, cross, &curves, &knots, corner.edge_shape)
            while weights.count < curves.count: try weights.push(1.0)
            try middle_knot_twice(&curves, &weights, first, &knots)
        else:
            try fillet_section(tb, tc, cross, continuity, &curves, &knots)
            while weights.count < curves.count: try weights.push(1.0)
        try sides.push(HoleSide(false, face_outward(w, frame.faces[i])))
    let fullness = corner.fullness if corner.fullness > 0.0 else fusion_fullness(continuity)
    let first_quad = quads.count
    let first_weight = quad_weights.count
    try corner_patch(curves.view(), weights.view(), knots.view(), sides.view(), continuity, quads, quad_weights, quad_knots, fullness)
    if corner.mixed: return
    # A full patch of three fillets of unequal radii can bulge through a
    # face beside its curve there: fitted again with two rows in each face's
    # plane, flat across it to second order.
    if n == 3 and not try patch_inside(w, corner, radius, quads.view()[first_quad..]):
        quads.count = first_quad
        quad_weights.count = first_weight
        try corner_patch(curves.view(), weights.view(), knots.view(), sides.view(), continuity, quads, quad_weights, quad_knots, fullness, 0, true)
    if not try patch_inside(w, corner, radius, quads.view()[first_quad..]): error(invalid, "the corner patch would leave its corner: use a rolling ball (G1) there")

## Whether setback corner `corner`'s patch control points `quads` stay
## between its faces and its setback planes.
func patch_inside(w: const Shape*, corner: const Setback*, radius: f64, quads: const Vector3[]) -> bool!:
    let p = w.points.items[(usize)corner.vertex]
    let slack = radius * 1e-9
    let cone = try corner_cone(w, corner, radius)
    for q in quads:
        for i in 0..<corner.count:
            if q.subtract(p).dot(cone[i]) < -slack or q.subtract(p).dot(corner.ways[i]) > corner.distances[i] + slack: return false
    return true

## A polynomial quintic Bezier from `ta` to `tb` near the conic tangent to
## the lines from each to `p` of rho `rho` relative to the circle's (0.5 the
## circle when they are as long; more nearer `p`), onto `points` and
## `knots` (one span): its second and fifth points along those lines, the
## inner two free, fitted by least squares to the conic sampled evenly by
## length, each sample at its share of the length.
func round_quintic(ta: Vector3, tb: Vector3, p: Vector3, points: Growing[Vector3]*, knots: Growing[f64]*, rho: f64 = 0.5) -> !:
    if not (rho > 0.0 and rho < 1.0): error(invalid, "a corner's edge shape is a rho from 0 to 1 (0.5 the circle)")
    let la = try ta.subtract(p).normalized()
    let lb = try tb.subtract(p).normalized()
    let middle = math.sin(math.acos(math.clamp(la.dot(lb), -1.0, 1.0)) * 0.5) * rho / (1.0 - rho)
    # The conic densely, and its length so far at each sample.
    let dense: usize = 400
    var conic = Growing[Vector3]()
    defer conic.close()
    var lengths = Growing[f64]()
    defer lengths.close()
    for k in 0..<dense + 1:
        let s = (f64)k / (f64)dense
        let a = (1.0 - s) * (1.0 - s)
        let c = 2.0 * s * (1.0 - s) * middle
        let d = s * s
        try conic.push(ta.multiply_scalar(a).add(p.multiply_scalar(c)).add(tb.multiply_scalar(d)).multiply_scalar(1.0 / (a + c + d)))
        try lengths.push(0.0 if k == 0 else lengths.items[k - 1] + conic.items[k].subtract(conic.items[k - 1]).length())
    let total = lengths.items[dense]
    if not (total > 0.0): error(invalid, "a corner's face curve has no length")
    # Unknowns: the second point's and fifth's steps along their lines,
    # then the third's and fourth's coordinates (8).
    let ea = p.subtract(ta)
    let eb = p.subtract(tb)
    var matrix: f64[64]
    var rhs: f64[8]
    for i in 0..<(usize)64: matrix[i] = 0.0
    for i in 0..<(usize)8: rhs[i] = 0.0
    let samples: usize = 60
    var at: usize = 0
    for k in 1..<samples:
        let s = (f64)k / (f64)samples
        let want = s * total
        while at + 1 < dense and lengths.items[at + 1] < want: at += 1
        let span = lengths.items[at + 1] - lengths.items[at]
        let f = (want - lengths.items[at]) / span if span > 0.0 else 0.0
        let target = conic.items[at].add(conic.items[at + 1].subtract(conic.items[at]).multiply_scalar(f))
        let u = 1.0 - s
        let bases: f64[6] = [u * u * u * u * u, 5.0 * s * u * u * u * u, 10.0 * s * s * u * u * u, 10.0 * s * s * s * u * u, 5.0 * s * s * s * s * u, s * s * s * s * s]
        let rest = target.subtract(ta.multiply_scalar(bases[0] + bases[1])).subtract(tb.multiply_scalar(bases[4] + bases[5]))
        for axis in 0..<(usize)3:
            let ra = ea.x if axis == 0 else (ea.y if axis == 1 else ea.z)
            let rb = eb.x if axis == 0 else (eb.y if axis == 1 else eb.z)
            var row: f64[8] = [bases[1] * ra, bases[4] * rb, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
            row[2 + axis] = bases[2]
            row[5 + axis] = bases[3]
            let goal = rest.x if axis == 0 else (rest.y if axis == 1 else rest.z)
            for i in 0..<(usize)8:
                rhs[i] += row[i] * goal
                for j in 0..<(usize)8: matrix[i * 8 + j] += row[i] * row[j]
    try cholesky_solve(matrix[..<64], rhs[..<8], 8)
    try points.push(ta)
    try points.push(ta.add(ea.multiply_scalar(rhs[0])))
    try points.push(Vector3(rhs[2], rhs[3], rhs[4]))
    try points.push(Vector3(rhs[5], rhs[6], rhs[7]))
    try points.push(tb.add(eb.multiply_scalar(rhs[1])))
    try points.push(tb)
    for _ in 0..<(usize)6: try knots.push(0.0)
    for _ in 0..<(usize)6: try knots.push(1.0)

## Fusion's setback corners are fuller than the fair fill (a hexagon's
## transfinite patch, probe 14): the patch's bulge scaled by this (asked by
## a fullness of 0) takes its volumes to Fusion's within 0.4 (a 20 cube's
## corner rounded 4, a boss's and an L's mixed corners at G1; the cube's at
## G2). Not the default: a fuller patch's offsets (a G2-rounded box's shell)
## no longer meet within the tolerance at its center.
func fusion_fullness(continuity: i64) -> f64:
    return 1.27 if continuity == 1 else 1.1

## Of `given`, the place of edge `e`'s section at corner `v`, or -1.
func given_section(given: (const GivenSection[])?, v: i64, e: usize) -> i64:
    if let all = given:
        for k in 0..<all.length:
            if all[k].vertex == v and all[k].edge == e: return (i64)k
    return -1

## Of `given`, section `k`'s points.
func given_points(given: (const GivenSection[])?, k: i64) -> Vector3[6]:
    if let all = given: return all[(usize)k].points
    return [Vector3(), Vector3(), Vector3(), Vector3(), Vector3(), Vector3()]

## A one-span degree 5 curve (the points from `first` on `points`, their
## weights alike on `weights`, its knots `knots`) given the knot 1/2 twice:
## the same curve, as G2's sections (fillet_section) are knotted, so a G1
## corner's arcs and the G2 curves on its faces share knots.
func middle_knot_twice(points: Growing[Vector3]*, weights: Growing[f64]*, first: usize, knots: Growing[f64]*) -> !:
    var rows = Growing[f64]()
    defer rows.close()
    for at in first..<points.count:
        let weight = weights.items[at]
        let q = points.items[at].multiply_scalar(weight)
        try rows.push(q.x)
        try rows.push(q.y)
        try rows.push(q.z)
        try rows.push(weight)
    var scratch = Growing[f64]()
    defer scratch.close()
    try insert_knot(&rows, knots, &scratch, 5, 4, 0.5)
    try insert_knot(&rows, knots, &scratch, 5, 4, 0.5)
    points.count = first
    weights.count = first
    for at in 0..<rows.count // 4:
        let weight = rows.items[at * 4 + 3]
        try points.push(Vector3(rows.items[at * 4], rows.items[at * 4 + 1], rows.items[at * 4 + 2]).multiply_scalar(1.0 / weight))
        try weights.push(weight)

## The corner tool's B-rep: the 2N quads, a cap on each setback plane and
## a piece of each face, between corner `p` and the patch.
func corner_solid(p: Vector3, corner: const Setback*, quads: const Vector3[], quad_weights: const f64[], cone: const Vector3[], knots: const f64[], m: usize, name: str) -> interop.Reference[CadModel]!:
    let n = corner.count
    let sides = n * 2
    let size = (quads[0].subtract(p)).length() * 4.0
    let solid = try BrepModel.sized(size)
    defer solid.release()
    let b = solid.value()
    let mm = m * m
    let apex = try b.add_vertex(p)
    var feet: i64[8] = [0, 0, 0, 0, 0, 0, 0, 0]
    for i in 0..<n: feet[i] = try b.add_vertex(p.add(corner.ways[i].multiply_scalar(corner.distances[i])))
    # The hole's corners (quad k's corner (0, 0)), its curves' middles
    # (quad k's (1, 0)) and the center.
    var corners: i64[16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    var middles: i64[16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for k in 0..<sides:
        corners[k] = try b.add_vertex(quads[k * mm])
        middles[k] = try b.add_vertex(quads[k * mm + (m - 1) * m])
    let center = try b.add_vertex(quads[mm - 1])
    var lines: i64[8] = [0, 0, 0, 0, 0, 0, 0, 0]
    var toward_before: i64[8] = [0, 0, 0, 0, 0, 0, 0, 0]
    var toward_after: i64[8] = [0, 0, 0, 0, 0, 0, 0, 0]
    for i in 0..<n:
        lines[i] = try b.add_line(apex, feet[i])
        toward_before[i] = try b.add_line(feet[i], corners[i * 2])
        toward_after[i] = try b.add_line(feet[i], corners[i * 2 + 1])
    # Each curve's halves and each seam, from the quads' own rows (a half
    # run from the middle back takes the knots reversed).
    var reversed = Growing[f64]()
    defer reversed.close()
    var k_ = knots.length
    while k_ > 0:
        k_ -= 1
        try reversed.push(1.0 - knots[k_])
    var net = Growing[Vector3]()
    defer net.close()
    var net_weights = Growing[f64]()
    defer net_weights.close()
    var firsts: i64[16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    var seconds: i64[16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    var seams: i64[16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    for k in 0..<sides:
        let next = (k + 1) % sides
        net.clear()
        net_weights.clear()
        for a in 0..<m:
            try net.push(quads[k * mm + a * m])
            try net_weights.push(quad_weights[k * mm + a * m])
        firsts[k] = try b.add_spline_edge(corners[k], middles[k], net.view(), net_weights.view(), 5, knots, true)
        net.clear()
        net_weights.clear()
        for b_ in 0..<m:
            try net.push(quads[next * mm + m - 1 - b_])
            try net_weights.push(quad_weights[next * mm + m - 1 - b_])
        seconds[k] = try b.add_spline_edge(middles[k], corners[next], net.view(), net_weights.view(), 5, reversed.view(), true)
        net.clear()
        net_weights.clear()
        for b_ in 0..<m:
            try net.push(quads[k * mm + (m - 1) * m + b_])
            try net_weights.push(quad_weights[k * mm + (m - 1) * m + b_])
        seams[k] = try b.add_spline_edge(middles[k], center, net.view(), net_weights.view(), 5, knots, true)
    # The quads: outward (away from the corner) is du x dv or against it.
    var bu: f64[36]
    var bv: f64[36]
    spline_basis(knots, 0.75, bu[..<36])
    spline_basis(knots, 0.75, bv[..<36])
    let four: i64[1] = [4]
    for k in 0..<sides:
        let before = (k + sides - 1) % sides
        var du = Vector3()
        var dv = Vector3()
        var at = Vector3()
        for a in 0..<m:
            for b_ in 0..<m:
                let q = quads[k * mm + a * m + b_]
                du = du.add(q.multiply_scalar(bu[9 + a] * bv[b_]))
                dv = dv.add(q.multiply_scalar(bu[a] * bv[9 + b_]))
                at = at.add(q.multiply_scalar(bu[a] * bv[b_]))
        let surface = try b.add_spline_surface(quads[k * mm..<(k + 1) * mm], quad_weights[k * mm..<(k + 1) * mm], (i64)m, (i64)m, 5, 5, knots, knots)
        let outward = du.cross(dv).dot(at.subtract(p)) > 0.0
        let forward: i64[4] = [firsts[k] + 1, seams[k] + 1, -(seams[before] + 1), seconds[before] + 1]
        let backward: i64[4] = [-(seconds[before] + 1), seams[before] + 1, -(seams[k] + 1), -(firsts[k] + 1)]
        var face: i64 = 0
        if outward: face = try b.add_face(surface, forward[..<4], four[..<1], true)
        else: face = try b.add_face(surface, backward[..<4], four[..<1], false)
        try b.set_face_name(face, name)
    # The caps, outward along each edge, and the faces' pieces, outward
    # away from the corner's inside.
    for i in 0..<n:
        let foot = p.add(corner.ways[i].multiply_scalar(corner.distances[i]))
        let uses: i64[4] = [toward_before[i] + 1, firsts[i * 2] + 1, seconds[i * 2] + 1, -(toward_after[i] + 1)]
        let around: Vector3[4] = [foot, quads[i * 2 * mm], quads[i * 2 * mm + (m - 1) * m], quads[(i * 2 + 1) * mm]]
        try flat_face(b, foot, corner.ways[i], uses[..<4], around[..<4])
    for i in 0..<n:
        let next = (i + 1) % n
        let uses: i64[6] = [lines[i] + 1, toward_after[i] + 1, firsts[i * 2 + 1] + 1, seconds[i * 2 + 1] + 1, -(toward_before[next] + 1), -(lines[next] + 1)]
        let around: Vector3[6] = [p, p.add(corner.ways[i].multiply_scalar(corner.distances[i])), quads[(i * 2 + 1) * mm], quads[(i * 2 + 1) * mm + (m - 1) * m],
                                  quads[(i * 2 + 2) % sides * mm], p.add(corner.ways[next].multiply_scalar(corner.distances[next]))]
        try flat_face(b, p, cone[i].multiply_scalar(-1.0), uses[..<6], around[..<6])
    return try CadModel.of_brep(solid)

## A flat face of `b` through `origin`, outward `normal`, bounded by
## `uses`: their order reversed when the points `around` them (their
## starts) turn the other way about the normal.
func flat_face(b: BrepModel*, origin: Vector3, normal: Vector3, uses: const i64[], around: const Vector3[]) -> !:
    # Newell's normal of the loop.
    var turn = Vector3()
    for k in 0..<around.length:
        let a = around[k]
        let c = around[(k + 1) % around.length]
        turn = turn.add(Vector3((a.y - c.y) * (a.z + c.z), (a.z - c.z) * (a.x + c.x), (a.x - c.x) * (a.y + c.y)))
    var loop = Growing[i64]()
    defer loop.close()
    if turn.dot(normal) > 0.0:
        try loop.assign(uses)
    else:
        var k = uses.length
        while k > 0:
            k -= 1
            try loop.push(-uses[k])
    let plane = try b.add_surface(0, origin, normal, try across(normal))
    let sizes: i64[1] = [(i64)uses.length]
    _ = try b.add_face(plane, loop.view(), sizes[..<1])

## The circle's arc from `ta` to `tb` whose tangents meet at `p` (a G1
## fillet's section), raised from a rational quadratic (middle weight
## sin(θ/2) for legs θ apart) to degree 5, one span: its points onto
## `points`, their weights onto `weights`, its knots onto `knots`. Fusion's
## Tangency weight `blend_shape` scales the middle weight: a conic, drawn
## toward the corner above 1 (a hyperbola), toward the chord below (an
## ellipse), still tangent to both faces at the same contacts.
func arc_section(ta: Vector3, tb: Vector3, p: Vector3, points: Growing[Vector3]*, weights: Growing[f64]*, knots: Growing[f64]*, blend_shape: BlendShape = plain_blend) -> !:
    let la = try ta.subtract(p).normalized()
    let lb = try tb.subtract(p).normalized()
    let middle = blend_shape.middle(math.sin(math.acos(math.clamp(la.dot(lb), -1.0, 1.0)) * 0.5))
    let arc_points: Vector3[3] = [ta, p.multiply_scalar(middle), tb]
    let arc_weights: f64[3] = [1.0, middle, 1.0]
    # Degree elevation by three in homogeneous space:
    # H5_j = sum C(2, i) C(3, j - i) / C(5, j) H2_i.
    let c2: f64[3] = [1.0, 2.0, 1.0]
    let c3: f64[4] = [1.0, 3.0, 3.0, 1.0]
    let c5: f64[6] = [1.0, 5.0, 10.0, 10.0, 5.0, 1.0]
    for j in 0..<(usize)6:
        var h = Vector3()
        var weight = 0.0
        for i in 0..<(usize)3:
            if j < i or j - i > 3: continue
            let f = c2[i] * c3[j - i] / c5[j]
            h = h.add(arc_points[i].multiply_scalar(f))
            weight += arc_weights[i] * f
        try points.push(h.multiply_scalar(1.0 / weight))
        try weights.push(weight)
    for _ in 0..<(usize)6: try knots.push(0.0)
    for _ in 0..<(usize)6: try knots.push(1.0)