Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.1

0.9.1 / src / brep / exact.lucb

## Read-only exact data for exporters (luce-usd writes CAD faces as USD
## NurbsPatch prims): a face's support surface as its record holds it, and
## the face's trim loops in the support's UV chart. The loops are sampled
## at the stations the display tessellation starts from (each edge's
## baseline intervals for the same divisions and the model's tolerance) and
## chained across coedges as the tessellator chains them (trim_chains), so
## a periodic support keeps each loop in one chart.
##
## Charts (mapped_patch.parameter): a plane's (x, y) in its frame; a
## cylinder's or cone's (angle, height); a sphere's (angle, latitude); a
## torus's (angle, minor angle); a B-spline's normalized knot domain
## [0, 1] x [0, 1].

import curve_spacing as spacing
from edge_sampling import compact_seams, curve_intervals
from layout_types import Stations, UVChain
from trim_chains import refreshed
from patch_sides import edge_index

## A face's support, copied out of the model.
pub struct FaceSupport:
    ## plane 0, cylinder 1, cone 2, rational B-spline 3, sphere 4, torus 5.
    pub var kind: i64
    pub var origin: Vector3
    pub var x: Vector3
    pub var y: Vector3
    pub var z: Vector3
    ## The radius (a torus's major one).
    pub var radius: f64
    ## A cone's semi-angle, or a torus's minor radius.
    pub var angle: f64
    ## A B-spline's net: nu x nv control points u-major (index u * nv + v),
    ## weights alike, expanded knot vectors, degrees.
    pub var points: Growing[Vector3]
    pub var weights: Growing[f64]
    pub var knots_u: Growing[f64]
    pub var knots_v: Growing[f64]
    pub var nu: i64
    pub var nv: i64
    pub var du: i64
    pub var dv: i64
    ## Whether the face's normal follows the support's (du x dv).
    pub var sense: bool
    ## The face's placement (applied after the support).
    pub var placement: Matrix4

    pub static func empty() -> FaceSupport:
        return FaceSupport(kind = 0, origin = Vector3(), x = Vector3(1.0, 0.0, 0.0), y = Vector3(0.0, 1.0, 0.0), z = Vector3(0.0, 0.0, 1.0), radius = 0.0, angle = 0.0,
                           points = Growing[Vector3](), weights = Growing[f64](), knots_u = Growing[f64](), knots_v = Growing[f64](),
                           nu = 0, nv = 0, du = 0, dv = 0, sense = true, placement = Matrix4())

    pub func close():
        self.points.close()
        self.weights.close()
        self.knots_u.close()
        self.knots_v.close()

## Chain every loop of `face` from `initial`; false when a loop does not
## close in one chart (another seed may). On periodic supports a seam's
## second use takes the chart's other side, a coedge leaving a singular
## point (a cone's apex, a sphere's pole) takes the side that closes the
## loop, and a loop wrapping once around the period (a sphere's
## hemisphere, bounded by its equator alone) closes along the singular
## line on the face's side.
func chain_loops(face: BrepFace, surface: Surface, vertices: const Vector3[], edges: const Curve[], stations: const Stations[], tolerance: f64, initial: Vector3, uv: Growing[Vector3]*, sizes: Growing[i64]*) -> bool!:
    let period = 2.0 * math.pi if surface.kind == 1 or surface.kind == 2 or surface.kind == 4 or surface.kind == 5 else 0.0
    var offset: usize = 0
    var loop_seed = initial
    var junctions = Growing[usize]()
    defer junctions.close()
    for size in face.sizes:
        var seed = loop_seed
        let start = uv.count
        junctions.clear()
        for entry in 0..<(usize)size:
            let use = face.uses[offset + entry]
            let forward = use > 0
            let chain = try refreshed(UVChain(), surface, vertices, edges[edge_index(use)], stations[offset + entry], tolerance, seed, forward)
            defer:
                free(chain.points) in memory.heap
                free(chain.times) in memory.heap
            let points = chain.points
            let begin = points[0 if forward else points.length - 1]
            var shift = 0.0
            let at_singular = entry > 0 and singular(surface, seed, tolerance)
            if at_singular: try junctions.push(uv.count)
            if entry > 0 and not at_singular and begin.subtract(seed).length() > 1e-4:
                if period > 0.0 and begin.add(Vector3(period, 0.0, 0.0)).subtract(seed).length() <= 1e-4:
                    shift = period
                elif period > 0.0 and begin.subtract(Vector3(period, 0.0, 0.0)).subtract(seed).length() <= 1e-4:
                    shift = -period
                else:
                    return false
            # Every point but the coedge's last, which the next one starts at.
            for step in 0..<points.length - 1:
                try uv.push(points[step if forward else points.length - 1 - step].add(Vector3(shift, 0.0, 0.0)))
            seed = points[points.length - 1 if forward else 0].add(Vector3(shift, 0.0, 0.0))
        let first = uv.items[start]
        if seed.subtract(first).length() > 1e-4 and not (try close_loop(face, surface, tolerance, period, uv, start, seed, junctions.view())):
            return false
        try sizes.push((i64)(uv.count - start))
        # A hole on a periodic support is seeded inside the outer loop's chart.
        if offset == 0 and (surface.kind == 1 or surface.kind == 2):
            var low: f64 = 1e100
            var high: f64 = -1e100
            for point in uv.view()[start..]:
                low = math.min(low, point.x)
                high = math.max(high, point.x)
            loop_seed = Vector3((low + high) * 0.5, 0.0, 0.0)
        offset += (usize)size
    return true

## Close the loop from `start` whose last coedge ended at `end`: by moving
## the coedges after a singular junction to the chart's other side, or,
## for a loop wrapping once around the period, along the singular line on
## the face's side. False when neither closes it.
func close_loop(face: BrepFace, surface: Surface, tolerance: f64, period: f64, uv: Growing[Vector3]*, start: usize, end: Vector3, junctions: const usize[]) -> bool!:
    if period <= 0.0: return false
    let first = uv.items[start]
    for junction in junctions:
        for side in [-period, period]:
            if end.add(Vector3(side, 0.0, 0.0)).subtract(first).length() <= 1e-4:
                for at in junction..<uv.count: uv.items[at] = uv.items[at].add(Vector3(side, 0.0, 0.0))
                return true
    let wrap = end.x - first.x
    if math.abs(math.abs(wrap) - period) > 1e-4 or math.abs(end.y - first.y) > 1e-4: return false
    # Left of the loop's direction in (u, v) is the face when it follows
    # the support's normal.
    let upward = (wrap > 0.0) == face.sense
    let edge = singular_height(surface, upward, end.y) else return false
    try uv.push(end)
    try uv.push(Vector3(end.x, edge, 0.0))
    try uv.push(Vector3(first.x, edge, 0.0))
    return true

## Whether chart point `p` is singular: a cone's apex or a sphere's pole.
func singular(surface: Surface, p: Vector3, tolerance: f64) -> bool:
    if surface.kind == 4: return math.abs(math.abs(p.y) - math.pi * 0.5) < 1e-6
    if surface.kind == 2: return math.abs(surface.radius + p.y * math.tan(surface.angle)) <= tolerance
    return false

## The singular line's v above `level` (`upward`) or below it: a sphere's
## pole, a cone's apex on that side; none elsewhere.
func singular_height(surface: Surface, upward: bool, level: f64) -> f64?:
    if surface.kind == 4: return math.pi * 0.5 if upward else -math.pi * 0.5
    if surface.kind == 2:
        let slope = math.tan(surface.angle)
        if slope == 0.0: return none
        let apex = -surface.radius / slope
        if (apex > level) == upward: return apex
    return none

extend BrepModel:
    ## Face `face`'s support surface, copied out of the model.
    pub func face_support(face: i64) -> FaceSupport!:
        try self.check_face(face)
        let records = try self.tessellation_records()
        let entry = records.faces[(usize)face]
        let surface = records.surfaces[(usize)entry.surface]
        var made = FaceSupport.empty()
        errdefer made.close()
        made.kind = surface.kind
        made.origin = surface.origin
        made.x = surface.x
        made.y = surface.y
        made.z = surface.z
        made.radius = surface.radius
        made.angle = surface.angle
        try made.points.assign(surface.points)
        try made.weights.assign(surface.weights)
        try made.knots_u.assign(surface.ku)
        try made.knots_v.assign(surface.kv)
        made.nu = surface.nu
        made.nv = surface.nv
        made.du = surface.du
        made.dv = surface.dv
        made.sense = entry.sense
        made.placement = entry.placement
        return made

    ## Face `face`'s trim loops in its support's chart, outer loop first:
    ## `uv` takes each loop's points in coedge order (the joint between two
    ## coedges once, the loop closing back to its first point) and `sizes`
    ## each loop's point count.
    pub func face_trim_uv(face: i64, divisions: i64, uv: Growing[Vector3]*, sizes: Growing[i64]*) -> !:
        try self.check_face(face)
        if divisions < 1 or divisions > 64: error(invalid, "CAD trim sampling requires 1..64 divisions")
        uv.clear()
        sizes.clear()
        let records = try self.tessellation_records()
        let entry = records.faces[(usize)face]
        let surface = records.surfaces[(usize)entry.surface]
        let edges = records.edges
        let metrics = try spacing.measure(edges)
        defer spacing.close(metrics)
        let compact = try compact_seams(records.faces, edges.length)
        defer free(compact) in memory.heap
        # Each coedge's stations, as the display tessellation's baseline has them.
        let stations = try new Stations[entry.uses.length] --- in memory.heap
        defer free(stations) in memory.heap
        for at in 0..<stations.length: stations[at] = Stations()
        defer:
            for station in stations: station.close()
        for at in 0..<entry.uses.length:
            let index = edge_index(entry.uses[at])
            let count = try curve_intervals(edges[index], divisions, self.tolerance, &metrics[index], compact[index])
            try stations[at].open(count + 1)
            for step in 0..<count + 1: _ = try stations[at].insert(metrics[index].station((f64)step / (f64)count), 1e-12)
        let vertices = self.vertices.view()
        # Seeds as trim_chains.initialize tries them: one chart for every loop.
        for initial in [Vector3(0.5, 0.5, 0.0), Vector3(0.0, 0.0, 0.0), Vector3(1.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0), Vector3(1.0, 1.0, 0.0)]:
            uv.clear()
            sizes.clear()
            if try chain_loops(entry, surface, vertices, edges, stations, self.tolerance, initial, uv, sizes): return
        error(invalid, "trim loops do not close in one support chart")