Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-geocore

Source of release 0.7.2

0.7.2 / src / geometries / builder.lucb

## Bounded temporary topology with explicit output-to-input provenance.
import interop
import memory
from luce_std import math
import errors
from math.vector import Vector3
from geometries.polygon import Mesh, mesh_type
from geometries.triangulation.polygon_triangulation import triangulate, unit_or_zero
import geometries.triangulation.face_scratch
from core.limits import max_points, max_faces, max_corners, check_mesh_size
from core.growing import grown

## A mesh built point by point and face by face, each element recording
## its parent. Its arrays grow by doubling up to core.limits, so callers must
## not keep spans across appends.
pub struct MeshBuilder:
    pub var points: Vector3[]
    pub var sizes: i64[]
    pub var corners: i64[]
    pub var point_parents: i64[]
    pub var face_parents: i64[]
    pub var corner_parents: i64[]
    # Lazy per-face display indices; -1 requests ordinary triangulation. The
    # used length is always 3*(nc-2*nf), so transactional nf/nc rewinds also
    # rewind display data. face() clears reused slots before another attempt.
    pub var display: i64[]
    pub var np: usize
    pub var nf: usize
    pub var nc: usize
    ## Build a precise mesh (f64 points kept; see Mesh). Copying a
    ## precise mesh's points turns it on.
    pub var precise: bool

    pub func init(precise: bool = false) -> !:
        let p = try new Vector3[256] --- in memory.heap
        errdefer free(p) in memory.heap
        let s = try new i64[256] --- in memory.heap
        errdefer free(s) in memory.heap
        let c = try new i64[1024] --- in memory.heap
        errdefer free(c) in memory.heap
        let pp = try new i64[256] --- in memory.heap
        errdefer free(pp) in memory.heap
        let fp = try new i64[256] --- in memory.heap
        errdefer free(fp) in memory.heap
        let cp = try new i64[1024] --- in memory.heap
        self.points = p
        self.sizes = s
        self.corners = c
        self.point_parents = pp
        self.face_parents = fp
        self.corner_parents = cp
        var empty: i64[]
        self.display = empty
        self.np = 0
        self.nf = 0
        self.nc = 0
        self.precise = precise

    pub func point(position: Vector3, parent: i64 = -1) -> i64!:
        if self.np == max_points: try check_mesh_size(self.np + 1, 0, 0)
        self.points = try grown[Vector3](self.points, self.np, self.np + 1)
        self.point_parents = try grown[i64](self.point_parents, self.np, self.np + 1)
        let id = self.np
        self.points[id] = position
        self.point_parents[id] = parent
        self.np += 1
        return (i64)id

    ## Begin a face of `count` corners (at least 3, any number more within
    ## the corner budget); its corners follow.
    pub func face(count: i64, parent: i64 = -1) -> !:
        if count < 3: error(errors.invalid, "a polygon needs at least 3 corners")
        try check_mesh_size(0, 0, (usize)count)
        if self.display.length > 0:
            let start = (self.nc - self.nf * 2) * 3
            let end = start + ((usize)count - 2) * 3
            try self.reserve_display(end)
            for at in start..<end: self.display[at] = -1
        if self.nf == max_faces: try check_mesh_size(0, self.nf + 1, 0)
        self.sizes = try grown[i64](self.sizes, self.nf, self.nf + 1)
        self.face_parents = try grown[i64](self.face_parents, self.nf, self.nf + 1)
        self.sizes[self.nf] = count
        self.face_parents[self.nf] = parent
        self.nf += 1

    pub func corner(point: i64, parent: i64 = -1) -> !:
        if self.nc == max_corners: try check_mesh_size(0, 0, self.nc + 1)
        self.corners = try grown[i64](self.corners, self.nc, self.nc + 1)
        self.corner_parents = try grown[i64](self.corner_parents, self.nc, self.nc + 1)
        self.corners[self.nc] = point
        self.corner_parents[self.nc] = parent
        self.nc += 1

    pub func copy_points(mesh: const Mesh*) -> !:
        if mesh.is_precise(): self.precise = true
        for id in 0..<mesh.point_count():
            _ = try self.point(try mesh.point(id), id)

    pub func copy_face(mesh: const Mesh*, id: i64) -> !:
        let count = try mesh.face_size(id)
        let offset = try mesh.face_offset(id)
        try self.face(count, id)
        var unchanged = true
        for at in 0..<count:
            let point = try mesh.face_point(id, at)
            try self.corner(point, offset + at)
            if point < 0 or (usize)point >= self.np: unchanged = false
            else:
                let a = self.points[(usize)point]
                let b = try mesh.point(point)
                unchanged = unchanged and a.x == b.x and a.y == b.y and a.z == b.z
        # Subsets retain the surface tessellation; arbitrary point edits must
        # rebuild it. Affine transforms preserve it explicitly in Mesh.
        if unchanged: try self.copy_last_display(mesh, id)

    ## Supply local corner indices for the most recently completed polygon.
    ## Full topology and geometric validation occurs in finish().
    pub func set_last_display(indices: const i64[]) -> !:
        if self.nf == 0: error(errors.invalid, "display triangulation requires a polygon")
        let count = (usize)self.sizes[self.nf - 1]
        if self.nc < count or indices.length != (count - 2) * 3: error(errors.invalid, "last polygon display size mismatch")
        for index in indices:
            if index < 0 or (usize)index >= count: error(errors.invalid, "display index leaves the last polygon")
        let start = self.nc - count
        let offset = (start - (self.nf - 1) * 2) * 3
        try self.reserve_display(offset + indices.length)
        for at in 0..<indices.length: self.display[offset + at] = (i64)start + indices[at]

    ## Compute the ordinary projected triangulation of the last completed face,
    ## without installing it or allocating a mesh/BVH. Returned indices are local
    ## corners, so geometry producers can compare it with a support-chart result.
    pub func triangulate_last(indices: i64[]) -> !:
        if self.nf == 0: error(errors.invalid, "triangulation requires a polygon")
        let count = (usize)self.sizes[self.nf - 1]
        if self.nc < count or indices.length != (count - 2) * 3: error(errors.invalid, "last polygon display size mismatch")
        let corners = self.corners[self.nc - count..<self.nc]
        for corner in corners:
            if corner < 0 or (usize)corner >= self.np: error(errors.invalid, "polygon point is out of range")
        let origin = self.points[(usize)corners[0]]
        var normal = Vector3()
        var extent2: f64 = 0.0
        for at in 0..<count:
            let a = self.points[(usize)corners[at]].subtract(origin)
            let b = self.points[(usize)corners[(at + 1) % count]].subtract(origin)
            normal = normal.add(a.cross(b))
            extent2 = math.max(extent2, a.dot(a))
        try triangulate(self.points[..<self.np], corners, 0, count, unit_or_zero(normal, extent2), indices)

    ## Copy triangles when polygon corner order is unchanged but point IDs may
    ## have been remapped (worker assembly, subsets and CAD boundary stitching).
    pub func copy_last_display(mesh: const Mesh*, face: i64, reversed: bool = false) -> !:
        let count = try mesh.face_size(face)
        if self.nf == 0 or self.sizes[self.nf - 1] != count: error(errors.invalid, "display copy requires matching polygon sizes")
        let offset = try mesh.face_offset(face)
        let first = (offset - face * 2) * 3
        let size = (usize)(count - 2) * 3
        # Small faces work on the stack, larger ones in heap scratch.
        var stack: i64[762] = ---
        let indices = try face_scratch.take[i64](stack, (usize)count, size)
        defer face_scratch.release[i64](stack, indices)
        for at in 0..<(count - 2) * 3:
            let input = at // 3 * 3 + (2 - at % 3 if reversed else at % 3)
            let index = mesh.index(first + input)
            defer index.release()
            let corner = (try index.get()) - offset
            indices[(usize)at] = count - 1 - corner if reversed else corner
        try self.set_last_display(indices)

    func reserve_display(required: usize) -> !:
        if required <= self.display.length: return
        if required > 100663296: error(errors.limit, "display triangulation exceeds geometry limits")
        var capacity: usize = 1024 if self.display.length == 0 else self.display.length
        while capacity < required: capacity *= 2
        if capacity > 100663296: capacity = 100663296
        let values = try new i64[capacity] --- in memory.heap
        memory.copy(values, self.display, self.display.length)
        for at in self.display.length..<capacity: values[at] = -1
        if self.display.length > 0: free(self.display) in memory.heap
        self.display = values

    ## Preserve authored normals only when the caller keeps their geometry valid.
    ## Ordinary modeling edits retain the default invalidation behavior.
    pub func finish(source: const Mesh*? = none, preserve_normals: bool = false) -> interop.Reference[Mesh]!:
        var triangles: const i64[]? = none
        if self.display.length > 0: triangles = self.display[..<(self.nc - self.nf * 2) * 3]
        if let original = source:
            return try original.remapped(self.points[..<self.np], self.sizes[..<self.nf], self.corners[..<self.nc], self.point_parents[..<self.np], self.face_parents[..<self.nf], self.corner_parents[..<self.nc], preserve_normals, triangles, self.precise)
        return try interop.Reference[Mesh].adopt(new Mesh(self.points[..<self.np], self.sizes[..<self.nf], self.corners[..<self.nc], triangles, self.precise) in memory.heap, mesh_type, memory.heap)

    pub func close():
        free(self.points) in memory.heap
        free(self.sizes) in memory.heap
        free(self.corners) in memory.heap
        free(self.point_parents) in memory.heap
        free(self.face_parents) in memory.heap
        free(self.corner_parents) in memory.heap
        if self.display.length > 0: free(self.display) in memory.heap