Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.6

0.11.6 / src / cad_blends.luc

## Fillet and Chamfer as Fusion 360's dialogs have them, on luce-cad's
## blends (CadModeling.filleted, chamfered, fillet_plan, rule_edges), and
## where a blend's radius arrow stands (handle_lines).
##   Fillet: Type Fillet (the edges picked, kept by reference), Rule
##     fillet (All edges, or the edges Between faces of two picked sets;
##     Rounds, Fillets or both) or Full round (a picked center face rounded
##     away whole between its sides); Radius Type Constant (Radius), Chord
##     length (the contacts' distance) or Variable (Radius at the start of
##     the edge or its tangent chain, End radius at its end, points between
##     as fractions of its length, smooth or straight; G1, G2 or G3);
##     Corner type Rolling ball or Setback (G1;
##     G2 and G3 corners are setbacks); Continuity G1 (Fusion's Tangent),
##     G2 (Curvature) or G3; Tangency weight (Fusion's, 0.1 to 2, constant
##     or variable radius: how far the continuity reaches into the blend; a
##     G1 fillet then a conic); Parasolid's sections: G1 Conic by rho (its
##     own, relative to the circle's, or its middle's radius), G2 by Depth
##     and Skew or by Softness; Limits (the fillet from and to fractions
##     of one straight edge, capped by planes square to it); Setback (radii
##     a corner's fillets stop at least from it); Overflow (off: a fillet
##     must fit its faces) and the behaviours it may take, Smooth (rolling
##     on over a line splitting its face, or onto a round beyond it), Cliff
##     (a cliff-edge blend: tangent to one face, through the edge where the
##     other ends) and Notch (the next face trims it); Tangent chain;
##     Selection sets (Fusion's: the edges picked are set 1 at Radius, sets
##     2 to 9 each its own edges and radius, meeting at setback corners;
##     with Variable radius a second set is the constant edges the law runs
##     into at corners).
##   Chamfer: Type Equal distance, Two distances (Distance along the first
##     face, the one more of the picked edges lie on, Distance 2 along the
##     other; Flip swaps them) or Distance and angle (the chamfer leaving
##     the first face at Angle); Corner Type Chamfer, Miter or Blend where
##     three meet; Tangent chain.
from luce_cad.cad_geometry import CadGeometry
from luce_cad.modeling import CadModeling, FilletPlan
from luce_cad.model import CadModel
from luce_3d.graphics import Vector3
from angles import radians
from geometry_data import GeometryData
from handle_lines import HandleLine
import handle_lines
from luce_ui import ui
from luce_std import math

# -- Fillet's and Chamfer's value slots (node_catalog.cad_fields).
pub let size_slot = 0
pub let continuity_slot = 1
pub let chain_slot = 2
pub let type_slot = 3
pub let rule_slot = 4
pub let rounds_slot = 5
pub let fillets_slot = 6
pub let radius_type_slot = 7
pub let chord_slot = 8
pub let end_radius_slot = 9
pub let smooth_slot = 10
## Fillet's Corner type: Rolling ball (0) or Setback (1), for G1; G2 and
## G3 corners are always setbacks.
pub let fillet_corner_slot = 11
## Fillet's Tangency weight (0.1 to 2, 1 the plain fillet).
pub let tangency_slot = 12
## Parasolid's sections (luce-cad blend_shape.lucb): G1's conic (Off, Rho,
## Rho relative, Middle radius) and its value; G2's shape (Fusion's, Depth
## and skew, Softness) and its values. (Slot 15 is a node's Group Type.)
pub let conic_slot = 13
pub let rho_slot = 14
pub let g2_shape_slot = 16
pub let depth_slot = 17
pub let skew_slot = 18
pub let softness_slot = 19
## Limits: the fillet from and to fractions of its edge, capped there.
pub let limits_slot = 20
pub let limit_from_slot = 21
pub let limit_to_slot = 22
## Setbacks: where fillets meet at a corner, each stops at least this many
## radii from it (0: as far as the corner needs).
pub let setback_ratio_slot = 23
## Overflow (Parasolid's): on, a fillet runs off its face by the behaviours
## its Smooth, Cliff and Notch rows allow (tried in that order); off, it
## must fit its faces.
pub let overflow_slot = 24
pub let smooth_overflow_slot = 26
pub let cliff_overflow_slot = 27
pub let notch_overflow_slot = 28
## Whether the rows past the section show (Limits, Setback, Overflow): the
## pane's and the step's tool bar's "More options".
pub let more_slot = 25
## Variable radius's points between its ends: "position radius" pairs
## apart by `;` (positions 0 to 1 along the edge), text 3.
pub let points_text = 3
## Selection sets (Fusion's: one Fillet's edge sets, each its own radius,
## luce-cad's filleted_sets): how many (1, the picked edges alone), the
## radii of sets 2 to 9 in slots 30 to 37, and their edges in text 4
## (references apart by `;`, set from set by `|`). Variable radius with a
## second set: its picked edges each follow the law, the second set's
## edges constant at Set 2 radius, meeting at corners (luce-cad's
## variable_filleted_edges).
pub let sets_slot = 29
pub let set_radius_slot = 30
pub let most_sets = 9
pub let sets_text = 4
## Setback corners' shape (Alias's corner controls, luce-cad's
## corner_shape and corner_fullness): the G1 face curves' rho relative to
## the circle's (Corner Blend's Edge Shape; 0.5 the circle, Fusion's) and
## the patch's bulge scale (Ball Corner's Pivot Curve Length Ratio; 0
## Fusion's, the default; 1 the fair fill's). After the sets' radii.
pub let corner_shape_slot = 38
pub let corner_fullness_slot = 39
## Parasolid's overlap limit (with Limits): the fillet only where it fits
## its faces, capped square there (luce-cad's limit_overlap).
pub let limit_overlap_slot = 40
## Fillet's Type entries: Fillet, Rule fillet, Full round.
pub let full_round_type = 2
## Chamfer's: its type, second distance, angle and flip.
pub let chamfer_type_slot = 3
pub let second_slot = 4
pub let angle_slot = 5
pub let flip_slot = 6
pub let corner_slot = 7
## Rule fillet's face sets (Between faces): texts 1 and 2.
pub let faces_text = 1
pub let others_text = 2

## What a blend's Edges text (edge references apart by `;`) shows.
pub func edges_summary(text: str) -> str:
    if text.trim() == "":
        return "All straight edges"
    let count = text.split(";").length
    return "1 edge" if count == 1 else f"{count} edges"

## What a feature node keeps between its evaluations on the compute
## worker: a Fillet's plan (luce-cad's FilletPlan: the body's edges
## resolved and its corners fitted once), so dragging its radius rebuilds
## only. Made again when the body, edges, continuity or chaining change.
pub class BlendMemo:
    pub var plan: FilletPlan? = none
    ## Plans made so far (one per change of body, edges or continuity).
    pub var made: int = 0

## The edges a Fillet with values `v` and texts `texts` blends on `body`:
## its picked references, or its rule's (made again on every cook, so
## they follow the body).
pub func edges_of(v: list[float], texts: list[str], body: CadModel) -> str!:
    if int(v[type_slot]) != 1:
        return texts[0]
    let between = int(v[rule_slot]) == 1
    return CadModeling.rule_edges(body, v[rounds_slot] != 0.0, v[fillets_slot] != 0.0, texts[faces_text] if between else "", texts[others_text] if between else "")

## Fillet or Chamfer (`kind`) of `body` with values `v` and texts `texts`,
## its faces named for `tag`; `memo` keeps a Fillet's plan when given.
pub func blended(kind: str, v: list[float], texts: list[str], body: CadModel, tag: str, memo: BlendMemo?) -> GeometryData!:
    let chain = v[chain_slot] != 0.0
    if kind == "Chamfer":
        let edges = texts[0]
        let shape = int(v[chamfer_type_slot])
        let corner = int(v[corner_slot])
        if shape == 0:
            return with_arrow(CadModeling.chamfered(body, edges, v[size_slot], tag, chain, corner), body, edges)
        let second = v[second_slot] if shape == 1 else 0.0
        return with_arrow(CadModeling.chamfered_sides(body, edges, v[size_slot], second, radians(v[angle_slot]), tag, chain, v[flip_slot] != 0.0, corner), body, edges)
    let continuity = int(v[continuity_slot]) + 1
    let shape = section_shape(v, continuity)
    let (conic, rho, depth, skew, softness) = shape
    if int(v[type_slot]) == full_round_type:
        # Full round: the center face picked, its sides found.
        let center = texts[faces_text].split(";")[0].trim()
        if center == "":
            error(ui.invalid, "Full round: pick the center face (Pick center face)")
        return GeometryData(geometry = CadGeometry.of_model(CadModeling.full_round(body, center, tag, continuity)))
    let edges = edges_of(v, texts, body)
    if int(v[type_slot]) == 0 and set_count(v) > 1:
        return sets_filleted(v, texts, body, tag, continuity, chain, edges)
    if int(v[radius_type_slot]) == 2:
        let (positions, radii) = variable_points(v, texts)
        if edges.split(";")[0].trim() == "":
            error(ui.invalid, "Variable radius: pick the edge (Pick edges)")
        # One tangent chain: the edges picked (and, with Tangent chain, the
        # edges going on from them), the radii along it from its start.
        return with_arrow(CadModeling.variable_filleted(body, edges, positions, radii, tag, v[smooth_slot] != 0.0, continuity, chain, v[tangency_slot], conic, rho, depth, skew, softness), body, edges)
    # Chord length: the radius that leaves the faces that far apart.
    let radius = CadModeling.chord_radius(body, edges, v[chord_slot], chain) if int(v[radius_type_slot]) == 1 else v[size_slot]
    let tangency = v[tangency_slot]
    # Setback corners (vertex blends where both kinds meet): no plan kept.
    let setback = int(v[fillet_corner_slot]) == 1
    # Limits: the fillet between them on its one edge, capped (no plan);
    # At overlap, only where it fits its faces.
    let limited = limits_slot < v.length and v[limits_slot] != 0.0
    let at_overlap = limited and limit_overlap_slot < v.length and v[limit_overlap_slot] != 0.0
    let ratio = v[setback_ratio_slot] if setback_ratio_slot < v.length and setback else 0.0
    let overflow = overflow_behaviours(v)
    # The corner's shape (setback corners only; unset values are the
    # defaults).
    let corners = setback or continuity > 1
    let edge_shape = v[corner_shape_slot] if corners and corner_shape_slot < v.length and v[corner_shape_slot] > 0.0 else 0.5
    let fullness = v[corner_fullness_slot] if corners and corner_fullness_slot < v.length else 0.0
    if setback or limited or ratio > 0.0 or overflow != 7 or edge_shape != 0.5 or fullness != 0.0:
        let from_at = v[limit_from_slot] if limited else 0.0
        let to_at = v[limit_to_slot] if limited else 1.0
        return with_arrow(CadModeling.filleted(body, edges, radius, tag, continuity, chain, setback, tangency, conic, rho, depth, skew, softness, from_at, to_at, ratio, overflow, edge_shape, fullness, at_overlap), body, edges, int(v[radius_type_slot]) == 0)
    let kept = memo else return with_arrow(CadModeling.filleted(body, edges, radius, tag, continuity, chain, false, tangency, conic, rho, depth, skew, softness), body, edges, int(v[radius_type_slot]) == 0)
    var plan = kept.plan
    if let held = plan:
        if not held.made_for(body, edges, continuity, tag, chain, tangency, conic, rho, depth, skew, softness):
            plan = none
    if plan == none:
        kept.made += 1
    let current = plan else CadModeling.fillet_plan(body, edges, continuity, tag, chain, tangency, conic, rho, depth, skew, softness)
    kept.plan = current
    return with_arrow(current.filleted(radius), body, edges, int(v[radius_type_slot]) == 0)

## The overflow behaviours values `v` allow, as luce-cad's filleted takes
## them: Smooth 1, Cliff 2, Notch 4 added up (7, all three, by default,
## Fusion's cliff included); 0 with Overflow off.
func overflow_behaviours(v: list[float]) -> int:
    if overflow_slot >= v.length:
        return 7
    if v[overflow_slot] == 0.0:
        return 0
    if notch_overflow_slot >= v.length:
        return 7
    return (1 if v[smooth_overflow_slot] != 0.0 else 0) + (2 if v[cliff_overflow_slot] != 0.0 else 0) + (4 if v[notch_overflow_slot] != 0.0 else 0)

## How many selection sets values `v` hold (1: the picked edges alone).
pub func set_count(v: list[float]) -> int:
    if sets_slot >= v.length:
        return 1
    return int(math.max(1.0, math.min(float(most_sets), v[sets_slot])))

## Set `k`'s edge references (k from 2) in texts `texts` ("" when none
## picked yet).
pub func set_edges(texts: list[str], k: int) -> str:
    if sets_text >= texts.length:
        return ""
    let parts = texts[sets_text].split("|")
    return parts[k - 2].trim() if k - 2 < parts.length else ""

## Set `k`'s references in text 4 `text` ("" when none picked yet).
pub func set_part(text: str, k: int) -> str:
    let parts = text.split("|")
    return parts[k - 2].trim() if k - 2 < parts.length else ""

## Texts `text` (text 4) with set `k`'s references `references`.
pub func with_set_edges(text: str, k: int, references: str) -> str:
    let parts = text.split("|") if text != "" else []
    while parts.length < k - 1:
        parts.append("")
    parts[k - 2] = references
    return parts.join("|")

## A Fillet of selection sets: Constant, each set at its radius
## (filleted_sets); Variable, the picked edges along the law into the
## second set's edges at its radius (variable_filleted_edges). Each set's
## radius arrow on its first edge.
func sets_filleted(v: list[float], texts: list[str], body: CadModel, tag: str, continuity: int, chain: bool, edges: str) -> GeometryData!:
    let count = set_count(v)
    let arrows: list[(str, int)] = [(edges, size_slot)]
    for k in 2..<count + 1:
        if set_edges(texts, k) == "":
            error(ui.invalid, f"Selection sets: pick set {k}'s edges (Pick set {k} edges)")
        arrows.append((set_edges(texts, k), set_radius_slot + k - 2))
    if edges.split(";")[0].trim() == "":
        error(ui.invalid, "Selection sets: pick the first set's edges (Pick edges)")
    if int(v[radius_type_slot]) == 2:
        if count != 2:
            error(ui.invalid, "Variable radius into corners takes one more set: its constant edges (Selection sets 2)")
        let (positions, radii) = variable_points(v, texts)
        let picked: list[str] = []
        for part in edges.split(";"):
            if part.trim() != "":
                picked.append(part.trim())
        let all_positions: list[float] = []
        let all_radii: list[float] = []
        let counts: list[int] = []
        for _ in picked:
            all_positions.extend(positions)
            all_radii.extend(radii)
            counts.append(positions.length)
        let made = CadModeling.variable_filleted_edges(body, set_edges(texts, 2), v[set_radius_slot], picked.join(";"), all_positions, all_radii, counts, tag, continuity, v[smooth_slot] != 0.0, v[tangency_slot])
        return with_arrows(made, body, arrows[1..])
    if int(v[radius_type_slot]) != 0:
        error(ui.invalid, "Selection sets take a Constant radius each, or Variable into one set of corners")
    var sets = edges
    let radii = [v[size_slot]]
    for k in 2..<count + 1:
        sets = sets + "|" + set_edges(texts, k)
        radii.append(v[set_radius_slot + k - 2])
    return with_arrows(CadModeling.filleted_sets(body, sets, radii, tag, continuity, chain), body, arrows)

## `made` as a result with a radius arrow for each of `arrows` (edges and
## the slot their arrow drags), on the first of the edges.
func with_arrows(made: CadModel, body: CadModel, arrows: list[(str, int)]) -> GeometryData!:
    let result = GeometryData(geometry = CadGeometry.of_model(made))
    let lines: list[HandleLine] = []
    for (edges, slot) in arrows:
        let first = edges.split(";")[0].trim()
        if first == "":
            continue
        let frame = CadModeling.edge_frame(body, first) catch failure:
            continue
        if frame.found:
            lines.append(HandleLine("arrow", slot, 1.0, frame.point, frame.outward, -1, Vector3()))
    if lines.length > 0:
        result.handles = handle_lines.encode(lines)
    return result

## The section's shape by values `v` at `continuity` (luce-cad's
## filleted): the conic's kind and rho (G1), the G2 depth, skew and
## softness (-1 unused).
func section_shape(v: list[float], continuity: int) -> (int, float, float, float, float):
    if softness_slot >= v.length:
        return (0, 0.5, -1.0, 0.5, -1.0)
    let conic = int(v[conic_slot]) if continuity == 1 else 0
    let g2 = int(v[g2_shape_slot]) if continuity == 2 else 0
    return (conic, v[rho_slot], v[depth_slot] if g2 == 1 else -1.0, v[skew_slot] if g2 == 1 else 0.5, v[softness_slot] if g2 == 2 else -1.0)

## A Variable radius's positions and radii: Radius at 0, the points
## between (sorted), End radius at 1.
func variable_points(v: list[float], texts: list[str]) -> (list[float], list[float])!:
    let between: list[(float, float)] = []
    for pair in (texts[points_text] if points_text < texts.length else "").split(";"):
        let t = pair.trim()
        if t == "":
            continue
        let parts: list[str] = []
        for part in t.split(" "):
            if part.trim() != "":
                parts.append(part.trim())
        if parts.length != 2:
            error(ui.invalid, "Variable radius points are \"position radius\" pairs apart by ;, positions between 0 and 1")
        let position = float(parts[0])
        if not (position > 0.0 and position < 1.0):
            error(ui.invalid, "A variable radius point's position is between 0 and 1 along the edge")
        between.append((position, float(parts[1])))
    between.sort()
    let positions = [0.0]
    let radii = [v[size_slot]]
    for (position, radius) in between:
        positions.append(position)
        radii.append(radius)
    positions.append(1.0)
    radii.append(v[end_radius_slot])
    return (positions, radii)

## `made` as a result, with the radius arrow on the first of `edges` of
## `body` (none for every edge, or without `arrow`: a chord length's is no
## radius), out of the edge's corner.
func with_arrow(made: CadModel, body: CadModel, edges: str, arrow: bool = true) -> GeometryData!:
    let result = GeometryData(geometry = CadGeometry.of_model(made))
    let first = edges.split(";")[0].trim()
    if first == "" or not arrow:
        return result
    let frame = CadModeling.edge_frame(body, first) catch failure:
        return result
    if frame.found:
        result.handles = handle_lines.encode([HandleLine("arrow", size_slot, 1.0, frame.point, frame.outward, -1, Vector3())])
    return result