Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.7

0.11.7 / src / compute_bridge.lucb

## App-owned worker boundary. Luce graphs and ARC owners never cross threads.
## Requests are copied text, applied in order: each is a delta against the one
## before, so none is dropped, but only the newest is cooked and published. A
## cook whose stamp the newest request still wants runs to completion into the
## worker's result store; stale publishing stops at the next check.
## Published products are keyed by content: the UI keeps the meshes it adopted,
## and the worker re-publishes a held key without copying, indexing or
## re-extracting overlays.
import interop
import memory
import thread
import sync
import c
from luce_geocore import geocore
from luce_geocore.geocore import detached_mesh, mesh_overlay_points
from luce_3d.graphics import Vector3, Matrix4, invalid, WireBatch, wire_batch_type, append_curve_segments, FogVolume, fog_volume_type, fog_volume_of, fog_look, restyle_fog
from luce_3d.graphics import GaussianSplats, gaussian_splats_type, gaussian_splats_of
from luce_geocore.geocore import GeometrySet
from luce_geocore.kernel import VolumeLook
from luce_geocore.core.growing import Growing
from overlay_lines import OverlayLines, line_points, check_label_pairs
from luce_cad.measure import CadCheck, check_lines
from luce_cad.cad_curves import curve_lines
from luce_cad.cad_geometry import set_models
from luce_ui import ui
from signal import Signal, SignalCore, release_core

pub type ComputeHandler = interop.Callback[str, unit]

struct Request:
    let message: interop.Packet[str]
    let generation: i64
    let wanted: i64[]

## A product of the current result. Fresh products own a deep mesh copy for
## the UI and freshly extracted overlays; others name a key the UI holds.
struct Product:
    let key: i64
    var mesh: geocore.Mesh*?
    let node: i64
    let display: bool
    var inspect: bool
    let fresh: bool
    var wires: Vector3[]
    var normals: Vector3[]
    var patches: Vector3[]
    ## Evaluated curves and their control hulls.
    var curves: Vector3[]
    var hulls: Vector3[]
    ## A Check node's lines (luce-cad's check groups) one group after the
    ## other, then its labels' pairs (check_label_pairs): group g ends at
    ## check_ends[g], the labels at check_ends[5].
    var checks: Vector3[]
    var check_ends: usize[6]
    ## A fog volume made here for the UI to adopt (its texels; the UI
    ## uploads them on its first draw), and the look a fog product draws
    ## with, on the heap (none for other products).
    var volume: FogVolume*?
    var look: VolumeLook*?
    ## A point cloud packed here for the UI to adopt (the UI uploads it on
    ## its first draw), and whether the product is a cloud's (new or held).
    var splats: GaussianSplats*?
    var cloud: bool
    ## A displayed output's whole set, for the viewport's render mode: a new
    ## owner of the worker's immutable storage for the UI to adopt, and
    ## whether the product is a set's (new or held).
    var set: GeometrySet*?
    var scene: bool

## Overlays of a key the UI holds, kept so unchanged keys need no extraction.
struct Held:
    let key: i64
    var wires: Vector3[]
    var normals: Vector3[]
    var patches: Vector3[]
    var curves: Vector3[]
    var hulls: Vector3[]
    var checks: Vector3[]
    var check_ends: usize[6]

struct State:
    var lock: sync.Mutex
    var changed: sync.Condition
    var stopping: bool = false
    var queue: Request[]
    var queued: usize = 0
    var wanted: i64[]
    var cooking: i64[64]
    var depth: usize = 0
    var requested: i64 = 0
    var active: i64 = 0
    var completed: i64 = 0
    var sequence: i64 = 0
    var node: i64 = -1
    var fraction: f64 = 0.0
    var phase: interop.Packet[str]? = none
    var report: interop.Packet[str]? = none
    var failed: bool = false
    var products: Product[1024]
    var count: usize = 0
    var held: Held[1024]
    var held_count: usize = 0
    var handle: thread.Handle
    let entry: interop.WorkerEntry[i64, str, unit]
    ## Wakes the UI loop when there is something for it (a result, progress,
    ## a request taken): the UI never polls the worker on a timer.
    var waker: ui.NotifyHandle? = none
    ## The worker's wait for news (signal.lucb): notified when a request
    ## arrives or the service stops, so a cook waiting on a build hears it.
    var news: SignalCore*? = none

    ## Wake the UI loop (its notifier's callback polls the service once).
    func wake():
        if let handle = self.waker: handle.notify()

    ## Drop the current result; untaken fresh copies are freed.
    func clear():
        for product in self.products[..<self.count]:
            if let mesh = product.mesh:
                mesh.close()
                free(mesh) in memory.heap
            release_points(product.wires)
            release_points(product.normals)
            release_points(product.patches)
            release_points(product.curves)
            release_points(product.hulls)
            release_points(product.checks)
            if let volume = product.volume:
                volume.close()
                free(volume) in memory.heap
            if let look = product.look:
                free(VolumeLook[](look, 1)) in memory.heap
            if let splats = product.splats:
                splats.close()
                free(splats) in memory.heap
            if let set = product.set:
                set.close()
                free(set) in memory.heap
        self.count = 0
        if let report = self.report:
            report.release()
        self.report = none
        self.failed = false

    func holds(key: i64) -> bool:
        for held in self.held[..<self.held_count]:
            if held.key == key:
                return true
        return false

    func wants(stamp: i64) -> bool:
        for wanted in self.wanted:
            if wanted == stamp:
                return true
        return false

func release_points(points: Vector3[]):
    if points.length > 0:
        free(points) in memory.heap

func copy_points(points: const Vector3[]) -> Vector3[]!:
    var empty: Vector3[]
    if points.length == 0:
        return empty
    let output = try new Vector3[points.length] --- in memory.heap
    memory.copy(output, points, points.length)
    return output

## Borrowed synchronized channel valid only while the service's worker lives.
pub struct ComputeChannel:
    let state: State*

    pub func close():
        _ = self.state

    ## Cancellation point. A newer request cancels publishing, and a cook only
    ## when that request no longer wants the stamp being cooked.
    pub func check() -> !:
        self.state.lock.lock()
        defer self.state.lock.unlock()
        if self.state.stopping:
            error(invalid, "Computation superseded")
        if self.state.queued == 0:
            return
        if self.state.depth == 0 or not self.state.wants(self.state.cooking[self.state.depth - 1]):
            error(invalid, "Computation superseded")

    ## Notify `signal` when a request arrives or the service stops (the worker
    ## waits on it for builds and children, which wake it too).
    pub func wake_on_requests(signal: interop.Reference[Signal]) -> !:
        let core = (try signal.get()).held_core()
        self.state.lock.lock()
        defer self.state.lock.unlock()
        if let old = self.state.news: release_core(old)
        self.state.news = core

    ## Whether a newer request waits; its delta must be applied before cooking.
    pub func superseded() -> bool:
        self.state.lock.lock()
        defer self.state.lock.unlock()
        return self.state.queued > 0 or self.state.stopping

    pub func begin(stamp: i64) -> !:
        self.state.lock.lock()
        defer self.state.lock.unlock()
        if self.state.depth == self.state.cooking.length:
            error(invalid, "Node cooks nest too deeply")
        self.state.cooking[self.state.depth] = stamp
        self.state.depth += 1

    pub func end():
        self.state.lock.lock()
        defer self.state.lock.unlock()
        if self.state.depth > 0:
            self.state.depth -= 1

    pub func progress(node: i64, fraction: f64, phase: str) -> !:
        try self.check()
        let copied = try interop.text_transfer.copy(phase)
        self.state.lock.lock()
        defer self.state.lock.unlock()
        if let previous = self.state.phase:
            previous.release()
        self.state.phase = copied
        self.state.node = node
        self.state.fraction = fraction
        self.state.sequence += 1
        self.state.wake()

    ## True when the UI already holds this product key from the last result.
    pub func holds(key: i64) -> bool:
        self.state.lock.lock()
        defer self.state.lock.unlock()
        return self.state.holds(key)

    ## Publish a key the UI holds: no copy, index or overlay work.
    pub func reuse(key: i64, node: i64, display: bool, inspect: bool) -> !:
        try self.check()
        if self.merge(key, inspect):
            return
        try self.add(Product(key, none, node, display, inspect, false))

    ## Publish a new mesh product: a new owner of the worker's immutable storage
    ## (its caches included; the UI picks on the GPU, so only what drawing
    ## needs is warmed).
    pub func mesh(source: interop.Reference[geocore.Mesh], key: i64, node: i64, display: bool, inspect: bool) -> !:
        try self.check()
        if self.merge(key, inspect):
            return
        # What the viewport's first draw of a new mesh needs, its edges and
        # smooth shading normals, is made here, off the UI thread: the copy
        # shares those caches (a 2M-face Boolean's result took the UI
        # ~60 ms to draw first otherwise).
        if display:
            _ = try source.value().edge_count()
            _ = try source.value().smooth_ids()
            try self.check()
        let copy = try detached_mesh(source)
        var product = Product(key, copy, node, display, inspect, true)
        errdefer:
            copy.close()
            free(copy) in memory.heap
            release_points(product.wires)
            release_points(product.normals)
        try self.check()
        try self.add(product)

    ## Publish `source`'s per-face normal guides under their own key; the
    ## worker makes them only while the viewport shows normals.
    pub func guides(key: i64, node: i64, source: interop.Reference[geocore.Mesh]) -> !:
        try self.check()
        if self.merge(key, false):
            return
        if self.holds(key):
            try self.add(Product(key, none, node, false, false, false))
            return
        var product = Product(key, none, node, false, false, true)
        errdefer release_points(product.normals)
        product.normals = try mesh_overlay_points(try source.get(), Matrix4(), true)
        try self.check()
        try self.add(product)

    ## Publish analytic CAD boundaries and normal guides under a content key.
    pub func overlay(key: i64, node: i64, wires: interop.Reference[OverlayLines], normals: interop.Reference[OverlayLines], patches: interop.Reference[OverlayLines]) -> !:
        try self.check()
        var product = Product(key, none, node, false, false, true)
        errdefer:
            release_points(product.wires)
            release_points(product.normals)
            release_points(product.patches)
        product.wires = try copy_points(line_points(try wires.get()))
        product.normals = try copy_points(line_points(try normals.get()))
        product.patches = try copy_points(line_points(try patches.get()))
        try self.add(product)

    ## Publish the curves of `geometry` (evaluated lines and, with
    ## `with_hulls`, control hulls), its CAD curves among them, placed by
    ## `matrix`, under a content key; nothing when it has no curves.
    pub func curves(key: i64, node: i64, geometry: interop.Reference[GeometrySet], matrix: Matrix4 = Matrix4(), with_hulls: bool = true) -> !:
        try self.check()
        var lines = Growing[Vector3]()
        defer lines.close()
        var hulls = Growing[Vector3]()
        defer hulls.close()
        try append_curve_segments(try geometry.get(), matrix, &lines, &hulls)
        if not with_hulls: hulls.clear()
        # CAD curves (luce-cad's): their hulls go with the CV nets'.
        try curve_lines(try geometry.get(), set_models(try geometry.get()), matrix, &lines)
        if lines.count + hulls.count == 0:
            return
        var product = Product(key, none, node, false, false, true)
        errdefer:
            release_points(product.curves)
            release_points(product.hulls)
        product.curves = try copy_points(lines.view())
        product.hulls = try copy_points(hulls.view())
        try self.add(product)

    ## Publish a Check node's lines (luce-cad's CadCheck, by group), placed by
    ## `matrix`, under a content key.
    pub func checks(key: i64, node: i64, measured: interop.Reference[CadCheck], matrix: Matrix4 = Matrix4()) -> !:
        try self.check()
        var points = Growing[Vector3]()
        defer points.close()
        var ends: usize[6] = [0, 0, 0, 0, 0, 0]
        for group in 0..<(i64)5:
            for p in check_lines(measured.value(), group): try points.push(matrix.transform_point(p))
            ends[(usize)group] = points.count
        try check_label_pairs(measured.value(), matrix, &points)
        ends[5] = points.count
        if points.count == 0:
            return
        var product = Product(key, none, node, false, false, true)
        errdefer release_points(product.checks)
        product.checks = try copy_points(points.view())
        product.check_ends = ends
        try self.add(product)

    ## Publish control hulls (world-space endpoint pairs: control polygons,
    ## CV nets, handle arms) under a content key. Any family's hulls go here;
    ## the viewport draws them together, behind a visibility toggle.
    pub func hull(key: i64, node: i64, lines: interop.Reference[OverlayLines]) -> !:
        try self.check()
        let points = line_points(try lines.get())
        if points.length == 0:
            return
        var product = Product(key, none, node, false, false, true)
        errdefer release_points(product.hulls)
        product.hulls = try copy_points(points)
        try self.add(product)

    ## Publish fog drawing `index` of `geometry`'s own volume placed by
    ## `matrix`, shadowed for `light`, under its content key (FogVolume.key)
    ## with its grid's look: its texels are made here, off the UI thread,
    ## unless the UI holds the key, when only the look goes.
    pub func volume(key: i64, node: i64, geometry: interop.Reference[GeometrySet], index: i64, matrix: Matrix4, light: Vector3) -> !:
        try self.check()
        let set = try geometry.get()
        if self.merge(key, false):
            return
        let look = fog_look(set, index) else error(invalid, "the geometry has no such fog drawing")
        let held = try new VolumeLook[1] --- in memory.heap
        held[0] = look
        var product = Product(key, none, node, true, false, not self.holds(key))
        product.look = held.data
        if product.fresh:
            product.volume = fog_volume_of(set, index, matrix, light) catch failure:
                free(held) in memory.heap
                error(failure.code, failure.message)
        self.add(product) catch failure:
            if let made = product.volume:
                made.close()
                free(made) in memory.heap
            free(held) in memory.heap
            error(failure.code, failure.message)

    ## Publish `geometry`'s point cloud placed by `matrix` under its content
    ## key (GaussianSplats.key): packed here, off the UI thread, unless the UI
    ## holds the key, when only the key goes.
    pub func cloud(key: i64, node: i64, geometry: interop.Reference[GeometrySet], matrix: Matrix4) -> !:
        try self.check()
        if self.merge(key, false):
            return
        if self.holds(key):
            var reused = Product(key, none, node, true, false, false)
            reused.cloud = true
            try self.add(reused)
            return
        let made = try gaussian_splats_of(try geometry.get(), matrix)
        var product = Product(key, none, node, true, false, true)
        product.splats = made
        product.cloud = true
        self.add(product) catch failure:
            made.close()
            free(made) in memory.heap
            error(failure.code, failure.message)

    ## Publish a displayed output's set (its meshes, clouds, cameras, lights
    ## and materials, all but CAD models) under a content key, for the
    ## viewport to render: a new owner of the same immutable arrays, nothing
    ## copied. A key the UI holds goes alone.
    pub func scene(key: i64, node: i64, geometry: interop.Reference[GeometrySet]) -> !:
        try self.check()
        if self.merge(key, false):
            return
        var product = Product(key, none, node, true, false, not self.holds(key))
        product.scene = true
        if product.fresh:
            # CAD models are Luce objects of this thread: they stay here
            # (render_geometry added their shared viewport surface meshes).
            product.set = try (try geometry.get()).plain_storage()
        self.add(product) catch failure:
            if let made = product.set:
                made.close()
                free(made) in memory.heap
            error(failure.code, failure.message)

    ## A key already in this result gains the inspect role instead of a copy.
    func merge(key: i64, inspect: bool) -> bool:
        for index in 0..<self.state.count:
            if self.state.products[index].key == key:
                self.state.products[index].inspect = self.state.products[index].inspect or inspect
                return true
        return false

    func add(product: Product) -> !:
        if self.state.count == self.state.products.length:
            error(invalid, "Computed scene exceeds 1024 mesh batches")
        self.state.products[self.state.count] = product
        self.state.count += 1

    pub func report(text: str) -> !:
        let copied = try interop.text_transfer.copy(text)
        if let previous = self.state.report:
            previous.release()
        self.state.report = copied

pub let compute_channel_type: interop.Type[ComputeChannel] = interop.Type[ComputeChannel]("Worker compute channel", ComputeChannel.close)

## Called only by the named worker factory with its service-provided token.
pub func channel(token: i64) -> interop.Reference[ComputeChannel]!:
    return try interop.Reference[ComputeChannel].adopt(new ComputeChannel((State*)(usize)token) in memory.heap, compute_channel_type, memory.heap)

## Main-thread owner. poll never waits for geometry work; close cancels and joins.
pub struct ComputeService:
    var state: State*?

    pub func init(entry: interop.WorkerEntry[i64, str, unit]) -> !:
        let state = try new State(entry = entry) in memory.heap
        errdefer free(state) in memory.heap
        state.queue = try new Request[16] --- in memory.heap
        errdefer free(state.queue) in memory.heap
        state.handle = try thread.spawn(run, (void*)state, name = "luced-3d compute")
        self.state = state

    ## Queue a delta request and the stamps it wants kept cooking.
    pub func submit(text: str, generation: i64, wanted: const i64[]) -> !:
        let state = self.state else error(invalid, "Compute service closed")
        let message = try interop.text_transfer.copy(text)
        errdefer message.release()
        let stamps = try new i64[wanted.length + 1] --- in memory.heap
        errdefer free(stamps) in memory.heap
        memory.copy(stamps, wanted, wanted.length)
        stamps[wanted.length] = 0
        state.lock.lock()
        defer state.lock.unlock()
        if state.queued == state.queue.length:
            let grown = try new Request[state.queue.length * 2] --- in memory.heap
            memory.copy(grown, state.queue, state.queued)
            free(state.queue) in memory.heap
            state.queue = grown
        let current = try new i64[wanted.length + 1] --- in memory.heap
        memory.copy(current, stamps, stamps.length)
        if state.wanted.length > 0:
            free(state.wanted) in memory.heap
        state.wanted = current
        state.queue[state.queued] = Request(message, generation, stamps)
        state.queued += 1
        state.requested = generation
        state.changed.broadcast()
        if let news = state.news: news.notify()

    ## How many requests wait for the worker to take them.
    pub func queued() -> i64:
        let state = self.state else return 0
        state.lock.lock()
        defer state.lock.unlock()
        return (i64)state.queued

    ## Wake `notifier`'s callback on the UI loop whenever the worker has
    ## something for it: a result, progress, a request taken.
    pub func wake_with(notifier: interop.Reference[ui.Notifier]) -> !:
        let state = self.state else error(invalid, "Compute service closed")
        let handle = try ui.notify_handle(notifier)
        state.lock.lock()
        defer state.lock.unlock()
        if let old = state.waker: old.release()
        state.waker = handle

    pub func sequence() -> i64:
        let state = self.state else return 0
        state.lock.lock()
        defer state.lock.unlock()
        return state.sequence

    pub func active_node() -> i64:
        let state = self.state else return -1
        state.lock.lock()
        defer state.lock.unlock()
        return state.node

    pub func progress() -> f64:
        let state = self.state else return 0.0
        state.lock.lock()
        defer state.lock.unlock()
        return state.fraction

    pub func phase() -> interop.Outcome[str]:
        let state = self.state else return interop.Outcome[str].success(interop.Owned[str](""))
        state.lock.lock()
        defer state.lock.unlock()
        let value = (state.phase else interop.Packet[str]("")).value
        return interop.Outcome[str].success(interop.copy_text(value) catch failure: trap(failure.message))

    ## Claim completed data. The worker waits for release_result before reusing
    ## this slot, so readers never race a pending replacement job.
    pub func completed() -> i64:
        let state = self.state else return 0
        state.lock.lock()
        defer state.lock.unlock()
        return state.completed

    pub func mesh_count() -> i64:
        return (i64)(self.state else return 0).count

    pub func mesh_key(index: i64) -> i64:
        return (self.state else return 0).products[(usize)index].key

    pub func mesh_node(index: i64) -> i64:
        return (self.state else return -1).products[(usize)index].node

    pub func mesh_display(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].display

    pub func mesh_inspect(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].inspect

    ## Whether the product carries a new mesh to adopt (else the UI holds it).
    pub func mesh_fresh(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].mesh != none

    pub func take_mesh(index: i64) -> interop.Reference[geocore.Mesh]!:
        let state = self.state else error(invalid, "Compute service closed")
        if index < 0 or (usize)index >= state.count or state.completed == 0:
            error(invalid, "No completed mesh")
        let mesh = state.products[(usize)index].mesh else error(invalid, "Mesh already consumed")
        state.products[(usize)index].mesh = none
        return try interop.Reference[geocore.Mesh].adopt(mesh, geocore.mesh_type, memory.heap)

    ## Whether the product carries a new fog volume to adopt.
    pub func volume_fresh(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].volume != none

    ## Whether product `index` is a fog volume's (new or held).
    pub func volume_product(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].look != none

    ## Give `volume` the look product `index`'s fog drawing has (a held
    ## volume takes a new look; its atlas stays).
    pub func style_volume(index: i64, volume: interop.Reference[FogVolume]) -> !:
        let state = self.state else error(invalid, "Compute service closed")
        if index < 0 or (usize)index >= state.count: error(invalid, "No such product")
        let look = state.products[(usize)index].look else error(invalid, "Not a fog product")
        restyle_fog(volume.value(), look)

    ## Adopt product `index`'s fog volume (once; the UI keeps it by key).
    pub func take_volume(index: i64) -> interop.Reference[FogVolume]!:
        let state = self.state else error(invalid, "Compute service closed")
        if index < 0 or (usize)index >= state.count or state.completed == 0:
            error(invalid, "No completed fog volume")
        let volume = state.products[(usize)index].volume else error(invalid, "Fog volume already consumed")
        state.products[(usize)index].volume = none
        return try interop.Reference[FogVolume].adopt(volume, fog_volume_type, memory.heap)

    ## Whether the product carries a newly packed point cloud to adopt.
    pub func cloud_fresh(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].splats != none

    ## Whether product `index` is a point cloud's (new or held).
    pub func cloud_product(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].cloud

    ## Adopt product `index`'s point cloud (once; the UI keeps it by key).
    pub func take_cloud(index: i64) -> interop.Reference[GaussianSplats]!:
        let state = self.state else error(invalid, "Compute service closed")
        if index < 0 or (usize)index >= state.count or state.completed == 0:
            error(invalid, "No completed point cloud")
        let splats = state.products[(usize)index].splats else error(invalid, "Point cloud already consumed")
        state.products[(usize)index].splats = none
        return try interop.Reference[GaussianSplats].adopt(splats, gaussian_splats_type, memory.heap)

    ## Whether product `index` is a displayed set's (new or held).
    pub func scene_product(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].scene

    ## Whether the product carries a new set to adopt.
    pub func scene_fresh(index: i64) -> bool:
        return (self.state else return false).products[(usize)index].set != none

    ## Adopt product `index`'s set (once; the UI keeps it by key).
    pub func take_scene(index: i64) -> interop.Reference[GeometrySet]!:
        let state = self.state else error(invalid, "Compute service closed")
        if index < 0 or (usize)index >= state.count or state.completed == 0:
            error(invalid, "No completed scene")
        let set = state.products[(usize)index].set else error(invalid, "Scene already consumed")
        state.products[(usize)index].set = none
        return try interop.Reference[GeometrySet].adopt(set, geocore.geometry_set_type, memory.heap)

    ## A Check node's line group `group` (luce-cad's check_passed ...
    ## check_quills), of every product.
    pub func check_batch(group: i64, outside: const i64[]) -> interop.Reference[WireBatch]!:
        if group < 0 or group >= 5: error(invalid, "check line group out of range")
        return try self.batch(5 + group, outside, false)

    ## The Check nodes' labels of every product, as check_label_pairs makes
    ## them, into `into`.
    pub func check_labels(outside: const i64[], into: interop.Reference[OverlayLines]) -> !:
        let state = self.state else error(invalid, "Compute service closed")
        for product in state.products[..<state.count]:
            if listed(outside, product.node): continue
            let pairs = overlay_of(state, product, 10)
            for at in 0..<pairs.length // 2: try into.value().add_segment(pairs[at * 2], pairs[at * 2 + 1])

    ## What overlay `which`'s batches hold (of the products `outside` and
    ## `around` choose, as `batch_count` does): the keys of the products with some
    ## of it (equal keys, equal lines), so an unchanged batch is kept.
    pub func batch_key(which: i64, outside: const i64[], around: bool = false) -> i64!:
        let state = self.state else error(invalid, "Compute service closed")
        var key: u64 = 0x9E3779B97F4A7C15 ^ (u64)which ^ (0x5555 if around else 0)
        for product in state.products[..<state.count]:
            if listed(outside, product.node) != around: continue
            if overlay_of(state, product, which).length > 0: key = (key ^ (u64)product.key) *% 0x100000001B3
        return (i64)(key >> 1)

    ## The products with overlay `which` (0 wires, 1 normals, 2 patches, 3
    ## curves, 4 hulls) of the current result (fresh and held keys), of those
    ## whose node is (with `around`) or is not one of `outside` (the rest of
    ## the scene around a context draws apart), one batch each: how many, the key of the
    ## `at`th, and the batch of the product `key`. A viewport keeps each
    ## product's batch while its key stands, so a changed product sends its
    ## own lines, not its category's.
    pub func batch_count(which: i64, outside: const i64[], around: bool = false) -> i64!:
        let state = self.state else error(invalid, "Compute service closed")
        var count: i64 = 0
        for product in state.products[..<state.count]:
            if listed(outside, product.node) != around: continue
            if overlay_of(state, product, which).length > 0: count += 1
        return count

    pub func batch_product(which: i64, outside: const i64[], around: bool, at: i64) -> i64!:
        let state = self.state else error(invalid, "Compute service closed")
        var seen: i64 = 0
        for product in state.products[..<state.count]:
            if listed(outside, product.node) != around: continue
            if overlay_of(state, product, which).length == 0: continue
            if seen == at: return product.key
            seen += 1
        error(invalid, "no such product batch")

    pub func product_lines(which: i64, key: i64) -> interop.Reference[WireBatch]!:
        let state = self.state else error(invalid, "Compute service closed")
        for product in state.products[..<state.count]:
            if product.key != key: continue
            return try interop.Reference[WireBatch].adopt(try new WireBatch(overlay_of(state, product, which)) in memory.heap, wire_batch_type, memory.heap)
        error(invalid, "no such product")

    func batch(which: i64, outside: const i64[], around: bool) -> interop.Reference[WireBatch]!:
        let state = self.state else error(invalid, "Compute service closed")
        var total: usize = 0
        for product in state.products[..<state.count]:
            if listed(outside, product.node) != around: continue
            total += overlay_of(state, product, which).length
        let points = try new Vector3[total] --- in memory.heap
        defer free(points) in memory.heap
        var at: usize = 0
        for product in state.products[..<state.count]:
            if listed(outside, product.node) != around: continue
            let part = overlay_of(state, product, which)
            memory.copy(points[at..], part, part.length)
            at += part.length
        return try interop.Reference[WireBatch].adopt(try new WireBatch(points) in memory.heap, wire_batch_type, memory.heap)

    pub func report() -> str:
        return ((self.state else trap("closed compute service")).report else interop.Packet[str]("")).value

    pub func failed() -> bool:
        return (self.state else trap("closed compute service")).failed

    ## Release the result. `kept` lists every key the UI holds from now on:
    ## held keys it names stay, and so do this result's fresh products the UI
    ## adopted (or that carry only overlays). All other held data is freed.
    pub func release_result(kept: const i64[]):
        let state = self.state else return
        state.lock.lock()
        defer state.lock.unlock()
        var count: usize = 0
        for index in 0..<state.held_count:
            if listed(kept, state.held[index].key):
                state.held[count] = state.held[index]
                count += 1
            else:
                release_points(state.held[index].wires)
                release_points(state.held[index].normals)
                release_points(state.held[index].patches)
                release_points(state.held[index].curves)
                release_points(state.held[index].hulls)
                release_points(state.held[index].checks)
        state.held_count = count
        for index in 0..<state.count:
            let product = &state.products[index]
            if not product.fresh or product.mesh != none or product.volume != none or product.splats != none or product.set != none or not listed(kept, product.key) or state.held_count == state.held.length:
                continue
            state.held[state.held_count] = Held(product.key, product.wires, product.normals, product.patches, product.curves, product.hulls, product.checks, product.check_ends)
            state.held_count += 1
            var empty: Vector3[]
            product.wires = empty
            product.normals = empty
            product.patches = empty
            product.curves = empty
            product.hulls = empty
            product.checks = empty
        state.clear()
        state.completed = 0
        state.changed.broadcast()

    pub func close():
        let state = self.state else return
        state.lock.lock()
        state.stopping = true
        state.changed.broadcast()
        if let news = state.news: news.notify()
        state.lock.unlock()
        state.handle.join() catch failure: trap(failure.message)
        if let handle = state.waker: handle.release()
        state.waker = none
        if let news = state.news: release_core(news)
        state.news = none
        state.clear()
        for request in state.queue[..<state.queued]:
            request.message.release()
            free(request.wanted) in memory.heap
        free(state.queue) in memory.heap
        if state.wanted.length > 0:
            free(state.wanted) in memory.heap
        for held in state.held[..<state.held_count]:
            release_points(held.wires)
            release_points(held.normals)
            release_points(held.patches)
            release_points(held.curves)
            release_points(held.hulls)
            release_points(held.checks)
        if let phase = state.phase:
            phase.release()
        free(state) in memory.heap
        self.state = none

pub let compute_service_type: interop.Type[ComputeService] = interop.Type[ComputeService]("3D compute service", ComputeService.close, closeable = true, main_thread = true)

func listed(keys: const i64[], key: i64) -> bool:
    for candidate in keys:
        if candidate == key:
            return true
    return false

func overlay_of(state: const State*, product: const Product, which: i64) -> const Vector3[]:
    if product.fresh:
        if which >= 5: return check_group(product.checks, &product.check_ends, which - 5)
        return pick(which, product.wires, product.normals, product.patches, product.curves, product.hulls)
    for held in state.held[..<state.held_count]:
        if held.key == product.key:
            if which >= 5: return check_group(held.checks, &held.check_ends, which - 5)
            return pick(which, held.wires, held.normals, held.patches, held.curves, held.hulls)
    var empty: Vector3[]
    return empty

## Check group `group` of `checks` (its groups end at `ends`).
func check_group(checks: const Vector3[], ends: const usize[6]*, group: i64) -> const Vector3[]:
    let first = (*ends)[(usize)group - 1] if group > 0 else 0
    return checks[first..<(*ends)[(usize)group]]

## Overlay `which`: 0 wires, 1 normals, 2 patches, 3 curves, 4 curve hulls,
## 5 to 9 a Check node's line groups (check_lines), 10 its labels' pairs.
func pick(which: i64, wires: const Vector3[], normals: const Vector3[], patches: const Vector3[], curves: const Vector3[], hulls: const Vector3[]) -> const Vector3[]:
    match which:
        0: return wires
        1: return normals
        2: return patches
        3: return curves
        _: return hulls

func run(raw: void*?):
    let state = (State*)(raw else return)
    state.entry.enter()
    defer state.entry.leave()
    let opened = state.entry.open(state.entry.context, (i64)(usize)state)
    defer opened.release()
    let handler = opened.get() catch failure: trap(failure.message)
    while true:
        state.lock.lock()
        while (state.queued == 0 or state.completed != 0) and not state.stopping:
            state.changed.wait(&state.lock)
        if state.stopping:
            state.lock.unlock()
            return
        let request = state.queue[0]
        state.queued -= 1
        memory.move(state.queue, state.queue[1..], state.queued)
        state.active = request.generation
        state.depth = 0
        # The UI may send the request it kept back (compute_session.luc).
        state.wake()
        state.lock.unlock()
        let result = handler.invoke(request.message.value)
        result.get() catch failure:
            state.failed = true
            if let previous = state.report:
                previous.release()
            state.report = interop.text_transfer.copy(failure.message) catch exhausted: trap(exhausted.message)
            recover ()
        result.release()
        request.message.release()
        free(request.wanted) in memory.heap
        state.lock.lock()
        if state.queued == 0 and state.active == state.requested and not state.stopping:
            state.completed = state.active
        else:
            state.clear()
        state.sequence += 1
        state.wake()
        state.lock.unlock()