Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-geocore

Source of release 0.7.8

0.7.8 / src / geometries / query_cache.lucb

## One lazy spatial index per mesh geometry, shared by snapshots on any
## thread. Concurrent borrowed queries may initialize it; the owner count is
## atomic. A mesh made by moving points keeps the previous geometry's cache
## as its source and refits that tree instead of building one: its faces and
## triangle slots are the same, even where a folded face was re-triangulated,
## so the old leaves still partition its triangles.
import sync
import memory
from core.float3 import Float3
from core.shared import Column
from geometries.triangle_index import TriangleIndex

pub struct QueryCache:
    pub var owners: @usize = 1
    var lock: sync.Mutex
    var ready: @u32
    var index: TriangleIndex*? = none
    ## The cache of the same faces before the positions moved, held until
    ## this one is built.
    var source: QueryCache*? = none
    ## Mirror maps of this geometry (selecting/mirror.lucb), by domain and
    ## axis: built on first use, kept with the geometry, so a symmetric drag
    ## pairs its input's elements once, not on every frame. Never carried
    ## to moved positions (`after` starts empty).
    var mirror_lock: sync.Mutex
    var mirrors: Column[i32][15]
    ## The last soft selection weighed on this geometry (Transform
    ## Components' soft radius): its group's words, radius and falloff, and
    ## the points it reaches with their weights. One, replaced when another
    ## is asked for: a drag changes only the transform, so it weighs once.
    var soft_group: Column[u64]
    var soft_radius: f64
    var soft_falloff: i64
    var soft_points: Column[u32]
    var soft_weights: Column[f32]

    ## A cache for a mesh whose positions moved over the faces and triangle
    ## slots of `previous`'s mesh; it holds `previous` until it is built.
    ## An unbuilt `previous` passes on its own source, so a run of moves with
    ## no query keeps one tree alive, not a chain.
    pub static func after(previous: QueryCache*) -> QueryCache*!:
        let cache = try new QueryCache() in memory.heap
        previous.lock.lock()
        var base = previous
        if previous.ready.load(.acquire) == 0:
            if let older = previous.source: base = older
        _ = base.owners.add(1, .relaxed)
        previous.lock.unlock()
        cache.source = base
        return cache

    ## Publish only a fully built index. Allocation failure unlocks without
    ## poisoning the cache, so a later query can retry. Published data is immutable.
    pub func get(positions: const Float3[], corners: const i32[], triangles: const i32[], faces: const i32[]) -> const TriangleIndex*!:
        if self.ready.load(.acquire) == 0:
            self.lock.lock()
            defer self.lock.unlock()
            if self.ready.load(.acquire) == 0:
                var refitted = false
                if let source = self.source:
                    if source.ready.load(.acquire) != 0:
                        let previous = source.index else trap("unpublished polygon query index")
                        var fitted = try previous.refit(positions, triangles)
                        let storage = new TriangleIndex[1] --- in memory.heap catch failure:
                            fitted.close()
                            error(failure.code, failure.message)
                        storage[0] = fitted
                        self.index = storage.data
                        refitted = true
                if not refitted:
                    self.index = try new TriangleIndex(positions, corners, triangles, faces) in memory.heap
                self.ready.store(1, .release)
                if let source = self.source:
                    self.source = none
                    release_query(source)
        return self.index else trap("unpublished polygon query index")

    ## Mirror map `slot` (see `mirrors`), shared, or none before it is kept.
    pub func mirror(slot: usize) -> Column[i32]?:
        self.mirror_lock.lock()
        defer self.mirror_lock.unlock()
        if self.mirrors[slot].is_empty(): return none
        return self.mirrors[slot].share()

    ## Keep `map` (shared) as mirror map `slot`, unless one is kept already.
    pub func keep_mirror(slot: usize, map: const Column[i32]*):
        self.mirror_lock.lock()
        defer self.mirror_lock.unlock()
        if self.mirrors[slot].is_empty(): self.mirrors[slot] = map.share()

    ## The points and weights kept for soft selection of `group` (its words)
    ## at `radius` with `falloff`, shared, or none.
    pub func soft(group: const u64[], radius: f64, falloff: i64) -> (Column[u32], Column[f32])?:
        self.mirror_lock.lock()
        defer self.mirror_lock.unlock()
        if self.soft_group.is_empty() or self.soft_radius != radius or self.soft_falloff != falloff: return none
        let kept = self.soft_group.view()
        if kept.length != group.length: return none
        for at in 0..<kept.length:
            if kept[at] != group[at]: return none
        return (self.soft_points.share(), self.soft_weights.share())

    ## Keep the soft selection weighed for `group` (copied), replacing any.
    pub func keep_soft(group: const u64[], radius: f64, falloff: i64, points: const Column[u32]*, weights: const Column[f32]*) -> !:
        var words = try Column[u64].copy_of(group)
        self.mirror_lock.lock()
        defer self.mirror_lock.unlock()
        self.soft_group.release()
        self.soft_points.release()
        self.soft_weights.release()
        self.soft_group = words
        self.soft_radius = radius
        self.soft_falloff = falloff
        self.soft_points = points.share()
        self.soft_weights = weights.share()

    pub func is_ready() -> bool:
        return self.ready.load(.acquire) != 0

    ## Called by the last owner, after every reader.
    func close():
        for at in 0..<(usize)15: self.mirrors[at].release()
        self.soft_group.release()
        self.soft_points.release()
        self.soft_weights.release()
        if let index = self.index:
            index.close()
            free(index) in memory.heap
        if let source = self.source:
            self.source = none
            release_query(source)

## Give up one owner of `cache`; the last frees it.
pub func release_query(cache: QueryCache*):
    if cache.owners.sub(1, .acq_rel) > 1: return
    cache.close()
    free(cache) in memory.heap