Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / src / sketch / entities.lucb

## A 2D sketch: entities on its plane held as indices into one array of
## parameters, and the constraints between them, which the solver
## (solver.lucb) satisfies. Lengths are in millimeters, angles in radians.
##
## A point owns two parameters, x and y. A line joins two points. A circle
## is a center point and a radius parameter; an arc is a center point, a
## radius parameter and real start and end points, which two of the
## solver's rows keep on its circle (it sweeps counterclockwise from start
## to end). A spline is drawn on a list of points (`lists`): its control
## points, or the points it passes through (fit points), degree 5 (fewer
## points, lower). An ellipse is a center point, a point at the end of its
## major axis and a minor radius parameter. A conic is a start, an end and
## an apex point (where its end tangents meet) and its rho parameter (0.5 a
## parabola, less an ellipse's arc, more a hyperbola's). Endpoints are
## points of their own, so a coincidence between two curves' ends is
## between two points, and the solver merges their parameters
## (substitution.lucb). Construction entities are solved like any other but
## make no profile curves. shapes.lucb gives the new curves as NURBS. A
## text is an anchor point (where its first line's baseline starts), a
## height parameter (its capitals') and its label: what it says and the
## font file it is set in (lettering.lucb makes its outlines).
## (docs/research/SKETCH-SOLVER-STUDY.md ยง7 has the design.)
import interop
import strings
import c as native_c
import memory
import ownership
from luce_std import math
from luce_geocore.geocore import invalid, Vector3, GeometrySet
from luce_geocore.core.growing import Growing
from luce_geocore.kernel import CurvesBuilder, CurveType, SketchPlane, empty_set, dispose_set, adopt_set, with_curves
from luce_std import files, utf8
from luce_fonts import opentype
from model import CadModel
from modeling import Shape, shape_of, resolve_edges, references_of

pub enum EntityKind as u8:
    point = 0
    line = 1
    circle = 2
    arc = 3
    spline = 4
    ellipse = 5
    conic = 6
    text = 7

## What a constraint holds `first`, `second` and `third` to, and what its
## `value` and `side` mean. The relations of equal or fixed parameters
## (coincident, horizontal, vertical, concentric, equal radii, fix, radius
## and diameter) are substitutions; the rest are the solver's rows.
pub enum ConstraintKind as u8:
    ## Points `first` and `second` at one place.
    coincident = 0
    ## Point `first` on curve `second` (a line, circle or arc's circle).
    on_curve = 1
    ## Line `first` (or points `first` and `second`) level or upright.
    horizontal = 2
    vertical = 3
    parallel = 4
    perpendicular = 5
    ## Line or arc `first` touching circle or arc `second` (or two circles),
    ## on side `side` (+1 or -1: for a line, the side of it the center is
    ## on; for two circles, outside or inside), kept from when it was made.
    ## A control point spline's or a conic's end (`first`; `side` +1 its
    ## start, -1 its end) along line, circle or arc `second`.
    tangent = 6
    ## Lines of equal length, or circles and arcs of equal radius.
    equal = 7
    ## Entity `first` stays where it is.
    fix = 8
    ## Point `first` at the middle of line `second`.
    midpoint = 9
    ## Circles or arcs `first` and `second` about one center.
    concentric = 10
    ## Lines `first` and `second` on one line.
    collinear = 11
    ## Points `first` and `second` mirrored about line `third`.
    symmetric = 12
    ## Dimensions: `value` long between points `first` and `second`; from
    ## point `first` to line `second` on side `side`; across or up
    ## (`side` the sign of second minus first); the angle from line
    ## `first` to line `second` (radians, counterclockwise); a radius or a
    ## diameter of circle or arc `first`.
    distance = 13
    line_distance = 14
    horizontal_distance = 15
    vertical_distance = 16
    angle = 17
    radius = 18
    diameter = 19
    ## Control point spline `first`'s end (`side` +1 its start, -1 its end)
    ## as curved as line, circle or arc `second` where they meet: curvature
    ## continuity (G2), tangent too. `value` is the sign the curvature
    ## turns with, kept from when it was made.
    curvature = 20
    ## Curvature and its rate of change continuous too (G3): as `curvature`,
    ## and the end's curvature changing as the other's does (not at all on
    ## a line, circle or arc).
    smooth = 21

## How many kinds of constraint there are.
pub let constraint_kind_count: usize = 22

## Whether constraint kind `kind` is a length (a distance, a radius, a
## diameter): what scaling the sketch scales.
pub func is_length_dimension(kind: ConstraintKind) -> bool:
    return kind == ConstraintKind.distance or kind == ConstraintKind.line_distance or kind == ConstraintKind.horizontal_distance or kind == ConstraintKind.vertical_distance or kind == ConstraintKind.radius or kind == ConstraintKind.diameter

pub struct SketchEntity:
    pub var kind: EntityKind
    ## A point: its x parameter (y is the next). A line: its start point.
    ## A circle, arc or ellipse: its center point. A spline: where its
    ## points start in `lists`. A conic: its start point.
    pub var first: i64
    ## A line: its end point. A circle or an arc: its radius parameter; an
    ## ellipse its minor radius, a conic its rho, a text its height. A
    ## spline: how many points it has.
    pub var second: i64
    ## An arc: its start and end points. An ellipse: its major axis point.
    ## A conic: its end and apex points. A spline: its degree (most), and 1
    ## when it passes through its points, 0 when they are its control net.
    ## A text: its label (in `labels`).
    pub var third: i64
    pub var fourth: i64
    pub var construction: bool

## A text's label: what it says and its font file (empty: the system's
## sans), as runs of a sketch's `chars`.
pub struct Label:
    pub var content: usize
    pub var content_length: usize
    pub var font: usize
    pub var font_length: usize

## A projected curve (`entity`, fixed) and the reference of the body edge
## it is the shadow of, a run of a sketch's `chars`.
pub struct Link:
    pub var entity: i64
    pub var reference: usize
    pub var reference_length: usize

pub struct SketchConstraint:
    pub var kind: ConstraintKind
    ## The entities it holds (-1: none).
    pub var first: i64
    pub var second: i64
    pub var third: i64
    ## A dimension's length (mm) or angle (radians).
    pub var value: f64
    ## The side kept from when it was made (+1 or -1).
    pub var side: f64
    ## A reference (driven) dimension: measured, never solved for.
    pub var driven: bool

pub struct Sketch:
    pub var params: Growing[f64]
    pub var entities: Growing[SketchEntity]
    pub var constraints: Growing[SketchConstraint]
    ## The splines' points, each spline's a run of point entities.
    pub var lists: Growing[i64]
    ## The texts' labels, their bytes in `chars`.
    pub var labels: Growing[Label]
    pub var chars: Growing[u8]
    ## Projected curves and the body edges they follow (projection.lucb).
    pub var links: Growing[Link]

    pub func close():
        self.params.close()
        self.entities.close()
        self.constraints.close()
        self.lists.close()
        self.labels.close()
        self.chars.close()
        self.links.close()

    ## A new point at (`x`, `y`).
    pub func add_point(x: f64, y: f64, construction: bool = false) -> i64!:
        let at = (i64)self.params.count
        try self.params.push(x)
        try self.params.push(y)
        return try self.add(SketchEntity(EntityKind.point, at, -1, -1, -1, construction))

    ## A line from point `start` to point `end`.
    pub func add_line(start: i64, end: i64, construction: bool = false) -> i64!:
        try self.require(start, EntityKind.point)
        try self.require(end, EntityKind.point)
        if start == end: error(invalid, "a line needs two different points")
        return try self.add(SketchEntity(EntityKind.line, start, end, -1, -1, construction))

    ## A circle about point `center` of `radius`.
    pub func add_circle(center: i64, radius: f64, construction: bool = false) -> i64!:
        try self.require(center, EntityKind.point)
        if not (radius > 0.0): error(invalid, "a circle needs a positive radius")
        let r = (i64)self.params.count
        try self.params.push(radius)
        return try self.add(SketchEntity(EntityKind.circle, center, r, -1, -1, construction))

    ## An arc about point `center` from point `start` counterclockwise to
    ## point `end`; its radius starts as the center's distance to `start`.
    pub func add_arc(center: i64, start: i64, end: i64, construction: bool = false) -> i64!:
        try self.require(center, EntityKind.point)
        try self.require(start, EntityKind.point)
        try self.require(end, EntityKind.point)
        if center == start or center == end or start == end: error(invalid, "an arc needs a center and two different ends")
        let radius = self.distance(center, start)
        if not (radius > 0.0): error(invalid, "an arc needs a positive radius")
        let r = (i64)self.params.count
        try self.params.push(radius)
        return try self.add(SketchEntity(EntityKind.arc, center, r, start, end, construction))

    ## A spline drawn on `points` (2 to 256 point entities): through them
    ## (`fit`), or on them as its control net; of degree `degree` (1..5),
    ## less when there are fewer points.
    pub func add_spline(points: const i64[], fit: bool, degree: i64 = 5, construction: bool = false) -> i64!:
        if points.length < 2 or points.length > 256: error(invalid, "a spline needs 2 to 256 points")
        if degree < 1 or degree > 5: error(invalid, "a spline's degree is 1 to 5")
        for p in points: try self.require(p, EntityKind.point)
        let start = (i64)self.lists.count
        for p in points: try self.lists.push(p)
        return try self.add(SketchEntity(EntityKind.spline, start, (i64)points.length, degree, 1 if fit else 0, construction))

    ## An ellipse about point `center`, its major axis out to point `major`,
    ## its minor radius `minor` (at most the major's).
    pub func add_ellipse(center: i64, major: i64, minor: f64, construction: bool = false) -> i64!:
        try self.require(center, EntityKind.point)
        try self.require(major, EntityKind.point)
        if center == major or not (minor > 0.0): error(invalid, "an ellipse needs a major axis and a positive minor radius")
        let r = (i64)self.params.count
        try self.params.push(minor)
        return try self.add(SketchEntity(EntityKind.ellipse, center, r, major, -1, construction))

    ## A conic from point `start` to point `end`, its end tangents meeting
    ## at point `apex`, of `rho` (between 0 and 1).
    pub func add_conic(start: i64, end: i64, apex: i64, rho: f64, construction: bool = false) -> i64!:
        for p in [start, end, apex]: try self.require(p, EntityKind.point)
        if start == end or start == apex or end == apex: error(invalid, "a conic needs three different points")
        if not (rho > 0.0 and rho < 1.0): error(invalid, "a conic's rho is between 0 and 1")
        let r = (i64)self.params.count
        try self.params.push(rho)
        return try self.add(SketchEntity(EntityKind.conic, start, r, end, apex, construction))

    ## A text at point `anchor` saying `content` (lines apart by newlines)
    ## in font file `font` (empty: the system's sans), its capitals
    ## `height` tall.
    pub func add_text(anchor: i64, height: f64, content: str, font: str, construction: bool = false) -> i64!:
        try self.require(anchor, EntityKind.point)
        if not (height > 0.0): error(invalid, "a text needs a positive height")
        if content.length == 0: error(invalid, "a text needs something to say")
        let label = Label(self.chars.count, content.length, self.chars.count + content.length, font.length)
        for byte in content.bytes: try self.chars.push(byte)
        for byte in font.bytes: try self.chars.push(byte)
        try self.labels.push(label)
        let r = (i64)self.params.count
        try self.params.push(height)
        return try self.add(SketchEntity(EntityKind.text, anchor, r, (i64)self.labels.count - 1, -1, construction))

    ## What text `e` says, and its font file.
    pub func text_content(e: SketchEntity) -> str:
        let label = self.labels.items[(usize)e.third]
        return (str)self.chars.view()[label.content..<label.content + label.content_length]

    pub func text_font(e: SketchEntity) -> str:
        let label = self.labels.items[(usize)e.third]
        return (str)self.chars.view()[label.font..<label.font + label.font_length]

    ## Link `link`'s edge reference.
    pub func link_reference(link: Link) -> str:
        return (str)self.chars.view()[link.reference..<link.reference + link.reference_length]

    ## Link curve `entity` to the edge `reference` names.
    pub func link(entity: i64, reference: str) -> !:
        let at = self.chars.count
        for byte in reference.bytes: try self.chars.push(byte)
        try self.links.push(Link(entity, at, reference.length))

    ## A sketch of its own with everything this one has.
    pub func copy() -> Sketch!:
        var s = new_sketch()
        errdefer s.close()
        try s.params.assign(self.params.view())
        try s.entities.assign(self.entities.view())
        try s.constraints.assign(self.constraints.view())
        try s.lists.assign(self.lists.view())
        try s.labels.assign(self.labels.view())
        try s.chars.assign(self.chars.view())
        try s.links.assign(self.links.view())
        return s

    ## Curve `entity` no longer follows the edge it was projected from
    ## (it was cut, extended or rounded: its own shape now).
    pub func unlink(entity: i64):
        var kept: usize = 0
        for at in 0..<self.links.count:
            if self.links.items[at].entity == entity: continue
            self.links.items[kept] = self.links.items[at]
            kept += 1
        self.links.count = kept

    ## The point entities curve `e` is drawn on, in order (a spline's
    ## list; an arc's center, start and end; a conic's start, end, apex).
    pub func points_of(e: SketchEntity, out: Growing[i64]*) -> !:
        out.clear()
        for at in 0..<self.point_count(e): try out.push(self.point_of(e, at))

    ## How many point entities curve `e` is drawn on (none for a point).
    pub func point_count(e: SketchEntity) -> i64:
        if e.kind == EntityKind.spline: return e.second
        if e.kind == EntityKind.point: return 0
        if e.kind == EntityKind.circle or e.kind == EntityKind.text: return 1
        return 3 if e.kind == EntityKind.arc or e.kind == EntityKind.conic else 2

    ## Point `at` of those curve `e` is drawn on (points_of's order).
    pub func point_of(e: SketchEntity, at: i64) -> i64:
        if e.kind == EntityKind.spline: return self.spline_point(e, at)
        if at == 0: return e.first
        if e.kind == EntityKind.line: return e.second
        return e.third if at == 1 else e.fourth

    ## Whether `value` can be curve `e`'s own parameter: a rho between 0
    ## and 1, any other positive.
    pub func scalar_fits(e: SketchEntity, value: f64) -> bool:
        if e.kind == EntityKind.conic: return value > 0.0 and value < 1.0
        return value > 0.0

    ## Curve `e`'s own parameter (a radius, a minor radius, a rho), or -1.
    pub func scalar_of(e: SketchEntity) -> i64:
        if e.kind == EntityKind.circle or e.kind == EntityKind.arc or e.kind == EntityKind.ellipse or e.kind == EntityKind.conic or e.kind == EntityKind.text: return e.second
        return -1

    ## Point `at` of spline `spline` (its list's).
    pub func spline_point(spline: SketchEntity, at: i64) -> i64:
        return self.lists.items[(usize)(spline.first + at)]

    ## A constraint; its index.
    pub func constrain(kind: ConstraintKind, first: i64, second: i64 = -1, third: i64 = -1, value: f64 = 0.0, side: f64 = 1.0, driven: bool = false) -> i64!:
        for named in [first, second, third]:
            if named >= (i64)self.entities.count or named < -1: error(invalid, "a constraint names an entity the sketch does not have")
        if not self.fits(kind, first, second, third): error(invalid, "a constraint is between entities of kinds it does not join")
        try self.constraints.push(SketchConstraint(kind, first, second, third, value, side, driven))
        return (i64)self.constraints.count - 1

    pub func entity(at: i64) -> SketchEntity:
        return self.entities.items[(usize)at]

    ## Point `point`'s coordinates.
    pub func x(point: i64) -> f64:
        return self.params.items[(usize)self.entities.items[(usize)point].first]

    pub func y(point: i64) -> f64:
        return self.params.items[(usize)self.entities.items[(usize)point].first + 1]

    ## Circle or arc `curve`'s radius.
    pub func radius_of(curve: i64) -> f64:
        return self.params.items[(usize)self.entities.items[(usize)curve].second]

    ## Move point `point` to (`x`, `y`) (before a solve, as a drag does).
    pub func place(point: i64, x: f64, y: f64):
        let at = (usize)self.entities.items[(usize)point].first
        self.params.items[at] = x
        self.params.items[at + 1] = y

    ## Whether constraint `kind` joins entities `first`, `second` and
    ## `third` of their kinds.
    func fits(kind: ConstraintKind, first: i64, second: i64, third: i64) -> bool:
        let a = self.kind_at(first)
        let b = self.kind_at(second)
        let c = self.kind_at(third)
        let point = (i64)(u8)EntityKind.point
        let line = (i64)(u8)EntityKind.line
        let spline = (i64)(u8)EntityKind.spline
        let ra = a == (i64)(u8)EntityKind.circle or a == (i64)(u8)EntityKind.arc
        let rb = b == (i64)(u8)EntityKind.circle or b == (i64)(u8)EntityKind.arc
        if kind == ConstraintKind.coincident or kind == ConstraintKind.distance or kind == ConstraintKind.horizontal_distance or kind == ConstraintKind.vertical_distance:
            return a == point and b == point and third < 0
        # A point on a line, circle, arc or ellipse.
        if kind == ConstraintKind.on_curve: return a == point and (b == line or rb or b == (i64)(u8)EntityKind.ellipse) and third < 0
        if kind == ConstraintKind.horizontal or kind == ConstraintKind.vertical:
            return (a == line and second < 0) or (a == point and b == point and third < 0)
        if kind == ConstraintKind.parallel or kind == ConstraintKind.perpendicular or kind == ConstraintKind.angle or kind == ConstraintKind.collinear:
            return a == line and b == line and third < 0
        # A control point spline or a conic touching (a spline: curving
        # like) another curve at its end.
        let net = a == spline and self.entities.items[(usize)first].fourth == 0
        let ended = net or a == (i64)(u8)EntityKind.conic
        if kind == ConstraintKind.tangent:
            if ended: return (b == line or (rb and a == spline)) and third < 0
            return ((a == line and rb) or (ra and (b == line or rb))) and third < 0
        if kind == ConstraintKind.curvature or kind == ConstraintKind.smooth:
            if not net or not (b == line or rb) or third >= 0: return false
            # Curving needs a degree 2 net of 3 points; its change, degree
            # 3 and 4.
            let e = self.entities.items[(usize)first]
            let least: i64 = 2 if kind == ConstraintKind.curvature else 3
            return e.third >= least and e.second >= least + 1
        if kind == ConstraintKind.equal: return ((a == line and b == line) or (ra and rb)) and third < 0
        if kind == ConstraintKind.fix: return first >= 0 and second < 0
        if kind == ConstraintKind.midpoint or kind == ConstraintKind.line_distance: return a == point and b == line and third < 0
        if kind == ConstraintKind.concentric: return ra and rb and third < 0
        if kind == ConstraintKind.symmetric: return a == point and b == point and c == line
        # Radius and diameter, the last kinds.
        return ra and second < 0

    ## Entity `at`'s kind as a number (EntityKind's), -1 for none.
    func kind_at(at: i64) -> i64:
        if at < 0: return -1
        return (i64)(u8)self.entities.items[(usize)at].kind

    func distance(a: i64, b: i64) -> f64:
        return math.hypot(self.x(b) - self.x(a), self.y(b) - self.y(a))

    func add(entity: SketchEntity) -> i64!:
        try self.entities.push(entity)
        return (i64)self.entities.count - 1

    func require(at: i64, kind: EntityKind) -> !:
        if at < 0 or at >= (i64)self.entities.count or self.entities.items[(usize)at].kind != kind:
            error(invalid, "a sketch entity is not of the kind it needs to be")

## An empty sketch.
pub func new_sketch() -> Sketch:
    return Sketch(Growing[f64](), Growing[SketchEntity](), Growing[SketchConstraint](), Growing[i64](), Growing[Label](), Growing[u8](), Growing[Link]())