Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.4

0.9.4 / src / brep / cvs.lucb

## The cv domain: the control vertices of every B-spline surface, in surface
## order (surface s owns cvs surface_cv_offsets[s]..<[s + 1]). Moving some
## makes a copy of the model that shares every other column; its per-face
## tessellation cache starts from this model's, so only faces whose inputs
## changed (the moved surfaces' faces, and neighbors whose layout follows
## them) are meshed again. The edges stay where they are, so moving a
## trimmed net's boundary rows takes its trims off the surface: the moved
## surfaces are marked edited, and their trims are re-projected (nearest
## parameters; surface_trim.project) so the face follows its cvs and stays
## joined to its neighbors along the unmoved edges. A face whose trims no
## longer mesh (folded) is left out and counted (face_jobs.mesh_faces).
## Placed, a surface's cvs take its first face's placement (the hull draws
## a net once per placement; assemblies give each part's faces one).

extend BrepModel:
    pub func cv_count() -> i64:
        return (i64)self.cv_positions.count

    ## Where cv `index` is, in B-rep space (before face placements).
    pub func cv_position(index: i64) -> Vector3!:
        if index < 0 or index >= self.cv_count(): error(invalid, "CAD control vertex out of range")
        return self.cv_positions.get((usize)index)

    ## The surface whose control net holds cv `index`.
    pub func cv_surface(index: i64) -> i64!:
        if index < 0 or index >= self.cv_count(): error(invalid, "CAD control vertex out of range")
        var low: usize = 0
        var high = self.surface_kind.count
        while low + 1 < high:
            let middle = (low + high) // 2
            if (i64)self.surface_cv_offsets.get(middle) <= index: low = middle
            else: high = middle
        return (i64)low

    ## Faces whose tessellation came from the per-face cache since the last
    ## call (diagnostics and tests).
    pub func reused_faces() -> i64:
        let derived = self.derived
        derived.lock.lock()
        defer derived.lock.unlock()
        if let cache = derived.faces: return (i64)cache.take_hits()
        return 0

    ## A copy with cvs `ids` moved by `delta` (B-rep space).
    pub func with_cvs_moved(ids: const i64[], delta: Vector3) -> interop.Reference[BrepModel]!:
        if not delta.is_finite(): error(invalid, "a control vertex move must be finite")
        for id in ids:
            if id < 0 or id >= self.cv_count(): error(invalid, "CAD control vertex out of range")
        let copy = try self.shared_copy()
        errdefer copy.release()
        let positions = try copy.value().cv_positions.writable()
        for id in ids: positions[(usize)id] = positions[(usize)id].add(delta)
        try copy.value().mark_edited(ids)
        try self.pass_quick(copy.value(), ids)
        return copy

    ## A copy with cvs `ids` at `positions` (B-rep space, one per id).
    pub func with_cvs_at(ids: const i64[], positions: const Vector3[]) -> interop.Reference[BrepModel]!:
        if ids.length != positions.length: error(invalid, "every moved control vertex needs a position")
        for at in 0..<ids.length:
            if ids[at] < 0 or ids[at] >= self.cv_count(): error(invalid, "CAD control vertex out of range")
            if not positions[at].is_finite(): error(invalid, "a control vertex position must be finite")
        let copy = try self.shared_copy()
        errdefer copy.release()
        let written = try copy.value().cv_positions.writable()
        for at in 0..<ids.length: written[(usize)ids[at]] = positions[at]
        try copy.value().mark_edited(ids)
        try self.pass_quick(copy.value(), ids)
        return copy

    ## Mark the surfaces owning cvs `ids` as edited.
    ## Mark surface `index` edited: its faces' boundaries take their nearest
    ## parameters on it (a surface rebuilt or converted under its trims).
    pub func mark_surface_edited(index: i64) -> !:
        if index < 0 or index >= self.surface_count(): error(invalid, "CAD surface out of range")
        let edited = try self.surface_edited.writable()
        edited[(usize)index] = 1

    func mark_edited(ids: const i64[]) -> !:
        let edited = try self.surface_edited.writable()
        for id in ids: edited[(usize)(try self.cv_surface(id))] = 1

    ## Each surface's placement (its first face's; the identity when no face
    ## uses it), into `out`.
    pub func surface_placements(out: Growing[Matrix4]*) -> !:
        let surfaces = (usize)self.surface_count()
        out.clear()
        try out.fill(surfaces, Matrix4())
        var seen = try BitsBuilder.zeros(surfaces)
        defer seen.close()
        for face in 0..<(usize)self.face_count():
            let surface = (usize)self.face_surface.get(face)
            if seen.view().get(surface): continue
            seen.set(surface)
            out.items[surface] = self.face_placement.get(face)

    ## The placement of cv `index` (its surface's).
    pub func cv_placement(index: i64) -> Matrix4!:
        let surface = try self.cv_surface(index)
        for face in 0..<(usize)self.face_count():
            if (i64)self.face_surface.get(face) == surface: return self.face_placement.get(face)
        return Matrix4()

    ## Every cv placed by `matrix` after its surface's placement, appended
    ## to `out`.
    pub func placed_cvs(matrix: Matrix4, out: Growing[Vector3]*) -> !:
        var placements = Growing[Matrix4]()
        defer placements.close()
        try self.surface_placements(&placements)
        try out.reserve(out.count + (usize)self.cv_count())
        for surface in 0..<(usize)self.surface_count():
            let place = matrix.multiply(placements.items[surface])
            for point in self.cvs_of(surface):
                out.items[out.count] = place.transform_point(point)
                out.count += 1

    ## Each cv's surface frame, placed as placed_cvs places it: at the cv's
    ## Greville point its surface's unit normal, u and v tangents (three
    ## vectors a cv, appended to `out`): the frame Alias's NUV moves along.
    ## A degenerate point (a pole) takes the hull's directions there.
    pub func placed_cv_frames(matrix: Matrix4, out: Growing[Vector3]*) -> !:
        var placements = Growing[Matrix4]()
        defer placements.close()
        try self.surface_placements(&placements)
        for surface in 0..<(usize)self.surface_count():
            if self.cvs_of(surface).length == 0: continue
            let place = matrix.multiply(placements.items[surface])
            var record = try self.surface((usize)surface)
            defer record.close()
            let low_u = record.ku[(usize)record.du]
            let high_u = record.ku[(usize)record.nu]
            let low_v = record.kv[(usize)record.dv]
            let high_v = record.kv[(usize)record.nv]
            for iu in 0..<(usize)record.nu:
                for iv in 0..<(usize)record.nv:
                    let u = (greville_of(record.ku, iu, record.du) - low_u) / (high_u - low_u)
                    let v = (greville_of(record.kv, iv, record.dv) - low_v) / (high_v - low_v)
                    let jet = try surface_jet(&record, Vector3(u, v, 0.0), u >= 1.0, v >= 1.0)
                    var du = place.transform_direction(jet.su)
                    var dv = place.transform_direction(jet.sv)
                    # At a pole one tangent vanishes: the net's own row.
                    let at = iu * (usize)record.nv + iv
                    if not (du.length() > 1e-12):
                        let ahead = record.points[fewer_index(at + (usize)record.nv, at, (usize)(record.nu * record.nv))]
                        let behind = record.points[at - (usize)record.nv if iu > 0 else at]
                        du = place.transform_direction(ahead.subtract(behind))
                    if not (dv.length() > 1e-12):
                        let ahead = record.points[at + 1 if iv + 1 < (usize)record.nv else at]
                        let behind = record.points[at - 1 if iv > 0 else at]
                        dv = place.transform_direction(ahead.subtract(behind))
                    let su = du.normalized() catch failure: recover Vector3(1.0, 0.0, 0.0)
                    let sv = dv.normalized() catch failure: recover Vector3(0.0, 1.0, 0.0)
                    let normal = su.cross(sv).normalized() catch failure: recover Vector3(0.0, 0.0, 1.0)
                    try out.push(normal)
                    try out.push(su)
                    try out.push(sv)

    ## Another model over the same columns (O(1) each), with copies of the
    ## face paths and a face cache inherited from this one.
    func shared_copy() -> interop.Reference[BrepModel]!:
        let output = try BrepModel.held(self.tolerances, self.tolerance)
        errdefer output.release()
        let target = output.value()
        target.vertices.close()
        target.vertices = self.vertices.share()
        target.curve_kind = self.curve_kind.share()
        target.curve_ends = self.curve_ends.share()
        target.curve_frame = self.curve_frame.share()
        target.curve_degree = self.curve_degree.share()
        target.curve_sense = self.curve_sense.share()
        target.curve_point_offsets.close()
        target.curve_point_offsets = self.curve_point_offsets.share()
        target.curve_points = self.curve_points.share()
        target.curve_weight_offsets.close()
        target.curve_weight_offsets = self.curve_weight_offsets.share()
        target.curve_weights = self.curve_weights.share()
        target.curve_knot_offsets.close()
        target.curve_knot_offsets = self.curve_knot_offsets.share()
        target.curve_knots = self.curve_knots.share()
        target.edge_precision = self.edge_precision.share()
        target.vertex_precision = self.vertex_precision.share()
        target.surface_kind = self.surface_kind.share()
        target.surface_edited = self.surface_edited.share()
        target.surface_frame = self.surface_frame.share()
        target.surface_dims = self.surface_dims.share()
        target.surface_cv_offsets.close()
        target.surface_cv_offsets = self.surface_cv_offsets.share()
        target.cv_positions = self.cv_positions.share()
        target.surface_weight_offsets.close()
        target.surface_weight_offsets = self.surface_weight_offsets.share()
        target.cv_weights = self.cv_weights.share()
        target.surface_knot_offsets.close()
        target.surface_knot_offsets = self.surface_knot_offsets.share()
        target.surface_knots = self.surface_knots.share()
        target.face_surface = self.face_surface.share()
        target.face_sense = self.face_sense.share()
        target.face_use_offsets.close()
        target.face_use_offsets = self.face_use_offsets.share()
        target.face_uses = self.face_uses.share()
        target.face_loop_offsets.close()
        target.face_loop_offsets = self.face_loop_offsets.share()
        target.loop_sizes = self.loop_sizes.share()
        target.face_placement = self.face_placement.share()
        target.face_color = self.face_color.share()
        target.face_colored = self.face_colored.share()
        for face in 0..<self.face_paths.count():
            try target.face_paths.push(self.face_paths.get(face))
            try target.face_names.push(self.face_names.get(face))
        let derived = self.derived
        derived.lock.lock()
        defer derived.lock.unlock()
        if let cache = derived.faces: target.derived.faces = try inherited(cache)
        try target.derived.boundaries.assign(derived.boundaries.view())
        return output

## The Greville abscissa of control point `i`: its knots' average.
func greville_of(knots: const f64[], i: usize, degree: i64) -> f64:
    var sum = 0.0
    for k in 1..<(usize)degree + 1: sum += knots[i + k]
    return sum / (f64)degree

## `ahead` when it is inside `count`, else `here`.
func fewer_index(ahead: usize, here: usize, count: usize) -> usize:
    return ahead if ahead < count else here

extend BrepModel:
    ## Another model over the same columns (O(1) each), built under
    ## `tolerances` instead: a held body rechecked against a changed
    ## project setting, or an import taken under the project's.
    pub func under(tolerances: CadTolerances) -> interop.Reference[BrepModel]!:
        try tolerances.checked()
        let output = try self.shared_copy()
        output.value().tolerances = tolerances
        return output