Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-3d

Source of release 0.9.6

0.9.6 / src / renderers / mesh_batch.lucb

## Drawing a polygon mesh from retained GPU arrays: positions, corner points,
## triangles, triangle faces, normals and colors are each a buffer keyed by the
## mesh array it came from, and the vertex stage pulls from them. Nothing is
## prepared per vertex on the CPU; lighting and the analysis modes run in the
## shaders, so changing lights or shading uploads nothing.
from luce_gpu import gpu
import memory
from luce_std import math
from luce_geocore.geocore import Mesh, Matrix4, Vector3
from core.material import Color
from cameras.camera import Projection
from renderers.projection import projection_matrix
from renderers.gpu_arrays import GpuArrays, ArrayKey
from luce_geocore.core.growing import Growing

let tag_positions: u8 = 1
let tag_corners: u8 = 2
let tag_normals: u8 = 3
let tag_smooth_normals: u8 = 4
let tag_colors: u8 = 5
let tag_triangles: u8 = 6
let tag_faces: u8 = 7
let tag_edges: u8 = 8
let tag_curvature: u8 = 9
let tag_flags: u8 = 10

## Triangles per draw: the triangle and face buffers stay under luce-gpu's
## buffer limit (12 bytes per triangle).
let chunk_triangles: usize = 11184810
## Pixels of a mesh's footprint each wire edge needs, or its wires are left
## out (too_dense).
let dense_wires = 2.0

## How surfaces are shaded: a luce-gpu Shading mode and the zebra / isophote
## stripe settings. Stripes run around (cylinder) or along (planar) `axis`;
## draft shading measures against `axis` as its pull direction.
pub struct MeshShading:
    pub var mode: gpu.Shading = gpu.Shading.lit
    pub var stripes: f64 = 20.0
    pub var duty: f64 = 0.5
    pub var planar: bool = false
    pub var stripes_only: bool = false
    pub var axis: Vector3 = Vector3(0.0, 1.0, 0.0)
    pub var dark: Color = Color(0.0, 0.0, 0.0)
    pub var light: Color = Color(1.0, 1.0, 1.0)
    ## Curvature mode: which value (0 mean, 1 Gaussian, 2 k1, 3 k2, 4 the
    ## larger |k|) and the value the map spans (0: the 98th percentile).
    pub var curvature: i64 = 0
    pub var curvature_range: f64 = 0.0
    ## Curvature mode's radius band: smallest radii under `band_low` draw
    ## magenta, over `band_high` grey (0: no limit).
    pub var band_low: f64 = 0.0
    pub var band_high: f64 = 0.0
    ## Draft mode: the draft angle asked for, in degrees.
    pub var draft: f64 = 1.0

## Faces tinted with an accent (a face selection), or hidden: one bit per
## face of the topology whose corners array is `topology`. `key` names the
## bits' version; `drawn` the version the GPU copies were last made for (of
## topology `drawn_topology`), which a new version's copies replace in place.
pub struct FaceHighlight:
    pub var topology: u64 = 0
    pub var key: u64 = 0
    pub var words: Growing[u32] = Growing[u32]()
    pub var color: Color = Color(1.0, 0.5, 0.0)
    pub var weight: f64 = 0.45
    pub var drawn: u64 = 0
    pub var drawn_topology: u64 = 0

    ## Mark `faces` (ids outside `count` faces are ignored) of the topology
    ## `topology`; cheap when nothing changed.
    pub func set(topology: u64, count: usize, faces: const i64[], color: Color, weight: f64) -> !:
        var key: u64 = 0xCBF29CE484222325 ^ topology
        for face in faces: key = (key ^ (u64)face) *% 0x100000001B3
        self.color = color
        self.weight = weight
        if key == self.key and topology == self.topology: return
        self.topology = topology
        self.key = key
        if faces.length == 0:
            self.words.clear()
            return
        try self.words.fill((count + 31) // 32, 0)
        for face in faces:
            if face >= 0 and (usize)face < count: self.words.items[(usize)face // 32] |= (u32)1 << (u32)((usize)face % 32)

    ## Mark the set bits of `words` (64 faces a word); `key` names the bits'
    ## contents (a selection's column id), so an unchanged selection is free.
    pub func set_words(topology: u64, count: usize, words: const u64[], key: u64, color: Color, weight: f64) -> !:
        self.color = color
        self.weight = weight
        let combined = (key *% 0x9E3779B97F4A7C15) ^ topology
        if combined == self.key and topology == self.topology: return
        self.topology = topology
        self.key = combined
        try self.words.fill((count + 31) // 32, 0)
        for at in 0..<self.words.count:
            let word = words[at // 2] if at // 2 < words.length else 0
            self.words.items[at] = (u32)(word >> 32) if at % 2 == 1 else (u32)(word & 0xFFFFFFFF)

    pub func close():
        self.words.close()

## What every object in a frame shares: the camera and the lights. Up to four
## directional lights reach the shader; ambient lights add up.
pub struct FrameLighting:
    pub var ambient: Color = Color(0.0, 0.0, 0.0)
    pub var directions: Vector3[4] = [Vector3(), Vector3(), Vector3(), Vector3()]
    pub var colors: Color[4] = [Color(0.0, 0.0, 0.0), Color(0.0, 0.0, 0.0), Color(0.0, 0.0, 0.0), Color(0.0, 0.0, 0.0)]
    pub var count: usize = 0

## Draw `mesh` placed by `world`: its surfaces (unless `surfaces` is false)
## and, when `wire_width` > 0, its edges in `wire_color`. Faces marked in
## `hidden` (of this topology) are left out, and edges all of whose faces
## are: their triangles and edges collapse to a point.
pub func draw_polygon(arrays: GpuArrays*, target: const gpu.RenderTarget*, mesh: const Mesh*, world: Matrix4, projection: Projection,
                      lighting: const FrameLighting*, tint: Color, lit: bool, shading: const MeshShading*, slope_bias: f64,
                      surfaces: bool, wire_width: f64, wire_color: Color, highlight: FaceHighlight*? = none, fade: f64 = 0.0, hidden: FaceHighlight*? = none) -> !:
    if mesh.face_count() == 0: return
    var buffers = gpu.MeshBuffers()
    buffers.positions = try positions(arrays, mesh)
    var block = parameters(mesh, world, projection, lighting, tint, lit, shading)
    block[gpu.mesh_fade] = (f32)fade
    if let marked = highlight:
        if marked.words.count > 0 and marked.topology == mesh.corners_id():
            buffers.flags = try flag_buffer(arrays, marked)
            block[gpu.mesh_accent] = (f32)marked.color.red
            block[gpu.mesh_accent + 1] = (f32)marked.color.green
            block[gpu.mesh_accent + 2] = (f32)marked.color.blue
            block[gpu.mesh_accent + 3] = (f32)marked.weight
    let versions = hidden_versions(mesh, hidden)
    if surfaces:
        buffers.corners = try corner_points(arrays, mesh)
        # Flat and unlit shading read no normals: none are made for them.
        let unlit = shading.mode == gpu.Shading.unlit or ((shading.mode == gpu.Shading.lit or shading.mode == gpu.Shading.flat) and not lit)
        if shading.mode != gpu.Shading.flat and not unlit:
            let normals = try normal_buffer(arrays, mesh)
            buffers.normals = normals.0
            block[gpu.mesh_mode + 1] = (f32)normals.1
        if shading.mode == gpu.Shading.curvature:
            let curvature = try curvature_buffer(arrays, mesh, shading)
            buffers.colors = curvature.0
            block[gpu.mesh_mode + 2] = (f32)curvature.1
            block[gpu.mesh_curvature] = (f32)shading.curvature
            block[gpu.mesh_curvature + 1] = (f32)curvature.2
            block[gpu.mesh_curvature + 2] = (f32)shading.band_low
            block[gpu.mesh_curvature + 3] = (f32)shading.band_high
        else:
            let colors = try color_buffer(arrays, mesh)
            if let buffer = colors.0: buffers.colors = buffer
            block[gpu.mesh_mode + 2] = (f32)colors.1
        let total = (usize)mesh.index_count() // 3
        var first: usize = 0
        var part: u32 = 0
        while first < total:
            let count = chunk_triangles if total - first > chunk_triangles else total - first
            buffers.triangles = try triangles(arrays, mesh, first, count, part, hidden, versions)
            buffers.faces = try triangle_faces(arrays, mesh, first, count, part)
            try gpu.draw_mesh(target, &buffers, count * 3, block, gpu.MeshKind.surface, slope_bias)
            first += count
            part += 1
    if wire_width > 0.0 and (try mesh.edge_count()) > 0 and not (try too_dense(target, mesh, world, projection)):
        var wires = gpu.MeshBuffers()
        wires.positions = buffers.positions
        wires.triangles = try edges(arrays, mesh, hidden, versions)
        var line = block
        line[gpu.mesh_tint] = (f32)wire_color.red
        line[gpu.mesh_tint + 1] = (f32)wire_color.green
        line[gpu.mesh_tint + 2] = (f32)wire_color.blue
        line[gpu.mesh_mode] = (f32)(u8)gpu.Shading.unlit
        line[gpu.mesh_line] = (f32)wire_width
        line[gpu.mesh_line + 3] = 0.000001
        try gpu.draw_mesh(target, &wires, (usize)(try mesh.edge_count()) * 6, line, gpu.MeshKind.wires)
    settle_hidden(mesh, hidden, versions)

## Face ids of `mesh` from `base` + 1, into an rgba8_linear target
## (picking); faces marked in `hidden` are left out.
pub func draw_polygon_ids(arrays: GpuArrays*, target: const gpu.RenderTarget*, mesh: const Mesh*, world: Matrix4, projection: Projection, base: u32, hidden: FaceHighlight*? = none) -> !:
    if mesh.face_count() == 0: return
    let lighting = FrameLighting()
    let shading = MeshShading(mode = gpu.Shading.unlit)
    var block = parameters(mesh, world, projection, &lighting, Color(1.0, 1.0, 1.0), false, &shading)
    block[gpu.mesh_mode + 3] = f32.bits(base)
    var buffers = gpu.MeshBuffers()
    buffers.positions = try positions(arrays, mesh)
    buffers.corners = try corner_points(arrays, mesh)
    let versions = hidden_versions(mesh, hidden)
    let total = (usize)mesh.index_count() // 3
    var first: usize = 0
    var part: u32 = 0
    while first < total:
        let count = chunk_triangles if total - first > chunk_triangles else total - first
        buffers.triangles = try triangles(arrays, mesh, first, count, part, hidden, versions)
        buffers.faces = try triangle_faces(arrays, mesh, first, count, part)
        try gpu.draw_mesh(target, &buffers, count * 3, block, gpu.MeshKind.ids)
        first += count
        part += 1
    settle_hidden(mesh, hidden, versions)

func parameters(mesh: const Mesh*, world: Matrix4, projection: Projection, lighting: const FrameLighting*, tint: Color, lit: bool, shading: const MeshShading*) -> f32[128]:
    return parameters_at(mesh.position_origin(), world, projection, lighting, tint, lit, shading)

## The parameter block of positions stored as f32 offsets from `origin`.
func parameters_at(origin: Vector3, world: Matrix4, projection: Projection, lighting: const FrameLighting*, tint: Color, lit: bool, shading: const MeshShading*) -> f32[128]:
    var block: f32[128]
    let view = projection_matrix(projection)
    # Positions are f32 offsets from the f64 origin; the origin joins the
    # placement here, in f64.
    let placed = world.translation.add(world.x.multiply_scalar(origin.x)).add(world.y.multiply_scalar(origin.y)).add(world.z.multiply_scalar(origin.z))
    let columns: Vector3[4] = [world.x, world.y, world.z, placed]
    for column in 0..<(usize)4:
        let c = columns[column]
        let w = 1.0 if column == 3 else 0.0
        for row in 0..<(usize)4:
            block[gpu.mesh_clip + column * 4 + row] = (f32)((f64)view[row] * c.x + (f64)view[4 + row] * c.y + (f64)view[8 + row] * c.z + (f64)view[12 + row] * w)
        block[gpu.mesh_world + column * 4] = (f32)c.x
        block[gpu.mesh_world + column * 4 + 1] = (f32)c.y
        block[gpu.mesh_world + column * 4 + 2] = (f32)c.z
        block[gpu.mesh_world + column * 4 + 3] = (f32)w
    # Normals take the inverse transpose, as cofactors over the determinant.
    let determinant = world.determinant()
    let scale = 1.0 / determinant if determinant != 0.0 else 0.0
    let cofactors: Vector3[3] = [world.y.cross(world.z), world.z.cross(world.x), world.x.cross(world.y)]
    for column in 0..<(usize)3:
        block[gpu.mesh_normal_matrix + column * 4] = (f32)(cofactors[column].x * scale)
        block[gpu.mesh_normal_matrix + column * 4 + 1] = (f32)(cofactors[column].y * scale)
        block[gpu.mesh_normal_matrix + column * 4 + 2] = (f32)(cofactors[column].z * scale)
    block[gpu.mesh_normal_matrix + 15] = 1.0
    block[gpu.mesh_tint] = (f32)tint.red
    block[gpu.mesh_tint + 1] = (f32)tint.green
    block[gpu.mesh_tint + 2] = (f32)tint.blue
    block[gpu.mesh_tint + 3] = 1.0 if lit else 0.0
    block[gpu.mesh_ambient] = (f32)lighting.ambient.red
    block[gpu.mesh_ambient + 1] = (f32)lighting.ambient.green
    block[gpu.mesh_ambient + 2] = (f32)lighting.ambient.blue
    for light in 0..<lighting.count:
        let direction = lighting.directions[light]
        let color = lighting.colors[light]
        block[gpu.mesh_light_direction + light * 4] = (f32)direction.x
        block[gpu.mesh_light_direction + light * 4 + 1] = (f32)direction.y
        block[gpu.mesh_light_direction + light * 4 + 2] = (f32)direction.z
        block[gpu.mesh_light_direction + light * 4 + 3] = 1.0
        block[gpu.mesh_light_color + light * 4] = (f32)color.red
        block[gpu.mesh_light_color + light * 4 + 1] = (f32)color.green
        block[gpu.mesh_light_color + light * 4 + 2] = (f32)color.blue
    # The shaders look from the eye; an orthographic view looks along one
    # direction everywhere, as from an eye that far back.
    let eye = projection.position.add(projection.backward.multiply_scalar(projection.far * 10000.0)) if projection.orthographic() else projection.position
    block[gpu.mesh_eye] = (f32)eye.x
    block[gpu.mesh_eye + 1] = (f32)eye.y
    block[gpu.mesh_eye + 2] = (f32)eye.z
    block[gpu.mesh_mode] = (f32)(u8)shading.mode
    block[gpu.mesh_mode + 1] = -1.0
    block[gpu.mesh_mode + 2] = -1.0
    block[gpu.mesh_zebra] = (f32)shading.stripes
    block[gpu.mesh_zebra + 1] = (f32)shading.duty
    block[gpu.mesh_zebra + 2] = 1.0 if shading.planar else 0.0
    block[gpu.mesh_zebra + 3] = 1.0 if shading.stripes_only else 0.0
    block[gpu.mesh_zebra_axis] = (f32)shading.axis.x
    block[gpu.mesh_zebra_axis + 1] = (f32)shading.axis.y
    block[gpu.mesh_zebra_axis + 2] = (f32)shading.axis.z
    block[gpu.mesh_zebra_axis + 3] = (f32)shading.draft
    block[gpu.mesh_zebra_dark] = (f32)shading.dark.red
    block[gpu.mesh_zebra_dark + 1] = (f32)shading.dark.green
    block[gpu.mesh_zebra_dark + 2] = (f32)shading.dark.blue
    block[gpu.mesh_zebra_light] = (f32)shading.light.red
    block[gpu.mesh_zebra_light + 1] = (f32)shading.light.green
    block[gpu.mesh_zebra_light + 2] = (f32)shading.light.blue
    return block

# mark: Overlays ==============================================================================

## A faded mesh draw writes no depth; this little fade changes its color by
## under 0.03%. Overlay marks drawn under a selection's lines use it so the
## lines along the same edges draw over them.
let depth_kept: f64 = 0.000244140625

## Unlit lines between point pairs: `pairs` holds `segments` pairs of indices
## into `positions` (f32 triples, offsets from `origin`, in world space),
## `width` logical pixels wide in `color`, pulled `bias` toward the eye (as
## Projection.clip's bias). `writes_depth` false leaves the depth buffer to
## later draws.
pub func draw_lines(target: const gpu.RenderTarget*, points: gpu.Buffer, origin: Vector3, pairs: gpu.Buffer, segments: usize, projection: Projection,
                    color: gpu.Color, width: f64, bias: f64, writes_depth: bool = true) -> !:
    if segments == 0: return
    let lighting = FrameLighting()
    let shading = MeshShading(mode = gpu.Shading.unlit)
    var block = parameters_at(origin, Matrix4(), projection, &lighting, Color(color.red, color.green, color.blue), false, &shading)
    block[gpu.mesh_line] = (f32)width
    block[gpu.mesh_line + 3] = (f32)bias
    if not writes_depth: block[gpu.mesh_fade] = (f32)depth_kept
    var buffers = gpu.MeshBuffers()
    buffers.positions = points
    buffers.triangles = pairs
    try gpu.draw_mesh(target, &buffers, segments * 6, block, gpu.MeshKind.wires)

## Unlit triangles of a mesh's corners: `fill` holds `count` triangles
## of corner ids into `owners` (each corner's point in `points`, offsets
## from `origin`), in `color`, pulled `bias` toward the eye so they cover the
## surface they lie on.
pub func draw_fill(target: const gpu.RenderTarget*, points: gpu.Buffer, owners: gpu.Buffer, origin: Vector3, fill: gpu.Buffer, count: usize,
                   projection: Projection, color: gpu.Color, bias: f64) -> !:
    if count == 0: return
    let lighting = FrameLighting()
    let shading = MeshShading(mode = gpu.Shading.unlit)
    var block = parameters_at(origin, Matrix4(), projection, &lighting, Color(color.red, color.green, color.blue), false, &shading)
    # The bias as Projection.clip applies it: clip z less bias times w.
    for column in 0..<(usize)4:
        block[gpu.mesh_clip + column * 4 + 2] -= (f32)bias * block[gpu.mesh_clip + column * 4 + 3]
    var buffers = gpu.MeshBuffers()
    buffers.positions = points
    buffers.corners = owners
    buffers.triangles = fill
    # The vertex stage reads a face per triangle; with no accent bits it
    # only passes it on, so the triangle buffer (long enough) stands in.
    buffers.faces = fill
    try gpu.draw_mesh(target, &buffers, count * 3, block, gpu.MeshKind.surface)

## Unlit triangles laid out on the CPU in normalized device coordinates:
## `count` vertices of `points` (x, y, depth as f32 triples) with a color
## each in `colors`, drawn through `order` (0, 1, 2, ... for at least
## `count`); depth tested. Point markers, made once per camera.
pub func draw_screen(target: const gpu.RenderTarget*, points: gpu.Buffer, colors: gpu.Buffer, order: gpu.Buffer, count: usize) -> !:
    if count == 0: return
    let lighting = FrameLighting()
    let shading = MeshShading(mode = gpu.Shading.unlit)
    var block = parameters_at(Vector3(), Matrix4(), projection_identity(), &lighting, Color(1.0, 1.0, 1.0), false, &shading)
    for at in 0..<(usize)16: block[gpu.mesh_clip + at] = 1.0 if at % 5 == 0 else 0.0
    # Colors per point (domain 0), the points being the vertices themselves.
    block[gpu.mesh_mode + 2] = 0.0
    var buffers = gpu.MeshBuffers()
    buffers.positions = points
    buffers.colors = colors
    buffers.corners = order
    buffers.triangles = order
    buffers.faces = order
    try gpu.draw_mesh(target, &buffers, count, block, gpu.MeshKind.surface)

## A projection for blocks whose clip matrix is set by hand.
func projection_identity() -> Projection:
    return Projection(position = Vector3(), right = Vector3(1.0, 0.0, 0.0), up = Vector3(0.0, 1.0, 0.0), backward = Vector3(0.0, 0.0, 1.0),
                      focal = 1.0, aspect = 1.0, near = 0.1, far = 10.0, ortho = 1.0)

## The GPU copy of `mesh`'s positions and of its corners' points, from
## `arrays` (uploaded or patched as for drawing).
pub func position_buffer(arrays: GpuArrays*, mesh: const Mesh*) -> gpu.Buffer!:
    return try positions(arrays, mesh)

pub func corner_buffer(arrays: GpuArrays*, mesh: const Mesh*) -> gpu.Buffer!:
    return try corner_points(arrays, mesh)

# mark: Arrays ================================================================================

func positions(arrays: GpuArrays*, mesh: const Mesh*) -> gpu.Buffer!:
    let key = ArrayKey(mesh.points_id(), tag_positions, 0)
    if let found = arrays.find(key): return found
    let count = (usize)mesh.point_count()
    let parent = mesh.points_parent()
    let changed = mesh.points_changed()
    # A Move rewrites only its neighbourhood of the previous buffer.
    if parent != 0 and changed.1 - changed.0 < count:
        let part = try arrays.staging((changed.1 - changed.0) * 12)
        try mesh.pack_positions_range(changed.0, changed.1, as_f32(part))
        if let patched = try arrays.patch(key, parent, count * 12, changed.0 * 12, part): return patched
    let bytes = try arrays.staging(count * 12)
    try mesh.pack_positions(as_f32(bytes))
    return try arrays.store(key, bytes, parent)

func corner_points(arrays: GpuArrays*, mesh: const Mesh*) -> gpu.Buffer!:
    let key = ArrayKey(mesh.corners_id(), tag_corners, 0)
    if let found = arrays.find(key): return found
    let bytes = try arrays.staging((usize)mesh.vertex_count() * 4)
    try mesh.pack_corner_points(as_u32(bytes))
    return try arrays.store(key, bytes)

## The hidden faces' bits when they are of `mesh`'s topology, else none.
func hiding(mesh: const Mesh*, hidden: const FaceHighlight*?) -> const FaceHighlight*?:
    let marked = hidden else return none
    if marked.words.count == 0 or marked.topology != mesh.corners_id(): return none
    return marked

## The version of the hidden faces `mesh`'s triangles and edges show now (0:
## none hidden) and the one their copies were last made for, which the new
## copies replace.
func hidden_versions(mesh: const Mesh*, hidden: const FaceHighlight*?) -> (u64, u64):
    let marked = hidden else return (0, 0)
    let topology = mesh.corners_id()
    let current = marked.key if marked.words.count > 0 and marked.topology == topology else 0
    let previous = marked.drawn if marked.drawn_topology == topology else current
    return (current, previous)

## After a draw: `hidden`'s copies of `mesh` now hold `versions.0`.
func settle_hidden(mesh: const Mesh*, hidden: FaceHighlight*?, versions: (u64, u64)):
    let marked = hidden else return
    let topology = mesh.corners_id()
    if marked.topology != topology and marked.drawn_topology != topology: return
    marked.drawn = versions.0
    marked.drawn_topology = topology

## Array id `base` as shown with hidden version `version`.
func variant(base: u64, version: u64) -> u64:
    return base if version == 0 else (base *% 0x9E3779B97F4A7C15) ^ version

func hidden_face(marked: const FaceHighlight*, face: usize) -> bool:
    let words = marked.words.view()
    return face // 32 < words.length and (words[face // 32] >> (u32)(face % 32)) & 1 != 0

## Triangles first..<first + count, those of hidden faces collapsed onto
## their first corner (nothing rasterizes, ids and faces keep their place).
func triangles(arrays: GpuArrays*, mesh: const Mesh*, first: usize, count: usize, part: u32, hidden: const FaceHighlight*?, versions: (u64, u64)) -> gpu.Buffer!:
    let marked = hiding(mesh, hidden)
    let key = ArrayKey(variant(mesh.triangles_id(), versions.0), tag_triangles, part)
    if let found = arrays.find(key): return found
    let bytes = try arrays.staging(count * 12)
    let corners = as_u32(bytes)
    try mesh.pack_triangles(first, corners)
    if let mask = marked:
        let faces = try new u32[count] --- in memory.heap
        defer free(faces) in memory.heap
        try mesh.pack_triangle_faces(first, faces)
        for at in 0..<count:
            if hidden_face(mask, (usize)faces[at]):
                corners[at * 3 + 1] = corners[at * 3]
                corners[at * 3 + 2] = corners[at * 3]
    return try arrays.store(key, bytes, variant(mesh.triangles_id(), versions.1))

## Whether `mesh`'s wires would cover its faces: more than one edge for every
## `dense_wires` pixels of its bounds on screen (a 1M-face grid filling
## part of the view). Its faces then show their shading (a sculpted
## surface) instead of a solid wire color; as the camera nears, the wires
## come back.
func too_dense(target: const gpu.RenderTarget*, mesh: const Mesh*, world: Matrix4, projection: Projection) -> bool!:
    let size = try target.size()
    let area = size.width * size.height
    let wires = (f64)(try mesh.edge_count())
    if area <= 0.0 or wires * dense_wires <= area: return false
    let box = mesh.bounds()
    var low_x = size.width
    var low_y = size.height
    var high_x = 0.0
    var high_y = 0.0
    for corner in 0..<8:
        let local = Vector3(box.maximum.x if corner & 1 != 0 else box.minimum.x, box.maximum.y if corner & 2 != 0 else box.minimum.y, box.maximum.z if corner & 4 != 0 else box.minimum.z)
        let on = projection.screen(world.transform_point(local), size.width, size.height)
        # A corner behind the camera: the mesh may fill the view.
        if on.z <= 0.0: return true
        low_x = math.min(low_x, on.x)
        low_y = math.min(low_y, on.y)
        high_x = math.max(high_x, on.x)
        high_y = math.max(high_y, on.y)
    let covered = math.max(0.0, math.min(size.width, high_x) - math.max(0.0, low_x)) * math.max(0.0, math.min(size.height, high_y) - math.max(0.0, low_y))
    return wires * dense_wires > covered

## Faces follow triangles and corners: keyed by both ids.
func triangle_faces(arrays: GpuArrays*, mesh: const Mesh*, first: usize, count: usize, part: u32) -> gpu.Buffer!:
    let key = ArrayKey(mesh.triangles_id() *% 0x9E3779B97F4A7C15 ^ mesh.corners_id(), tag_faces, part)
    if let found = arrays.find(key): return found
    let bytes = try arrays.staging(count * 4)
    try mesh.pack_triangle_faces(first, as_u32(bytes))
    return try arrays.store(key, bytes)

## Every edge as its two points; an edge all of whose faces are hidden
## collapses onto its first point.
func edges(arrays: GpuArrays*, mesh: const Mesh*, hidden: const FaceHighlight*?, versions: (u64, u64)) -> gpu.Buffer!:
    let marked = hiding(mesh, hidden)
    let key = ArrayKey(variant(mesh.edges_id(), versions.0), tag_edges, 0)
    if let found = arrays.find(key): return found
    let count = (usize)(try mesh.edge_count())
    let bytes = try arrays.staging(count * 8)
    let ends = as_u32(bytes)
    try mesh.pack_edges(ends)
    if let mask = marked:
        let around = try mesh.edge_corner_span()
        let corner_faces = try mesh.corner_face_span()
        for edge in 0..<count:
            var shown = false
            for at in (usize)around.0[edge]..<(usize)around.0[edge + 1]:
                shown = shown or not hidden_face(mask, (usize)corner_faces[(usize)around.1[at]])
            if not shown and around.0[edge] < around.0[edge + 1]: ends[edge * 2 + 1] = ends[edge * 2]
    return try arrays.store(key, bytes, variant(mesh.edges_id(), versions.1))

## The shading normals and their domain: an authored N (corner, then point,
## face and detail), else the mesh's smooth normals (per point, or per corner
## where a 60-degree cusp splits a point). Flat shading reads neither.
func normal_buffer(arrays: GpuArrays*, mesh: const Mesh*) -> (gpu.Buffer, i64)!:
    let found = try preferred(mesh, "N", 3)
    if found.0 >= 0:
        return (try attribute_buffer(arrays, mesh, found.0, tag_normals), found.1)
    let ids = try mesh.smooth_ids()
    let domain = try mesh.smooth_domain()
    let key = ArrayKey(ids.0, tag_smooth_normals, 0)
    if let buffer = arrays.find(key): return (buffer, domain)
    let count = (usize)(mesh.vertex_count() if domain == 1 else mesh.point_count())
    let changed = try mesh.smooth_changed()
    if ids.1 != 0 and changed.1 - changed.0 < count:
        let part = try arrays.staging((changed.1 - changed.0) * 12)
        try mesh.pack_smooth_range(changed.0, changed.1, as_f32(part))
        if let patched = try arrays.patch(key, ids.1, count * 12, changed.0 * 12, part): return (patched, domain)
    let bytes = try arrays.staging(count * 12)
    try mesh.pack_smooth_normals(as_f32(bytes))
    return (try arrays.store(key, bytes, ids.1), domain)

## Principal curvatures (k1, k2) for the curvature map: the CAD analytic
## attributes (corners), else the discrete estimate (points); their domain;
## and the range the map spans.
## The automatic range is measured once per source and value kind and kept
## with the source's copy.
func curvature_buffer(arrays: GpuArrays*, mesh: const Mesh*, shading: const MeshShading*) -> (gpu.Buffer, i64, f64)!:
    let source = try mesh.curvature_source()
    let key = ArrayKey(source.key, tag_curvature, 0)
    var buffer = arrays.find(key)
    if buffer == none:
        let count = (usize)mesh.vertex_count() if source.domain == 1 else (usize)mesh.point_count()
        let bytes = try arrays.staging(count * 12)
        try mesh.pack_curvature(&source, as_f32(bytes))
        buffer = try arrays.store(key, bytes)
    var range = shading.curvature_range
    if range <= 0.0:
        if let known = arrays.range(key, shading.curvature): range = known
        else:
            range = try mesh.curvature_range(&source, shading.curvature)
            arrays.remember_range(key, shading.curvature, range)
    return (buffer else trap("curvature buffer"), source.domain, range)

## The highlight's bits, one u32 per 32 faces: a new selection rewrites the
## copy of the last one.
func flag_buffer(arrays: GpuArrays*, highlight: FaceHighlight*) -> gpu.Buffer!:
    let key = ArrayKey(highlight.key, tag_flags, 0)
    if let found = arrays.find(key): return found
    let words = highlight.words.view()
    let bytes = try arrays.staging(words.length * 4)
    memory.copy(u32[]((u32*)bytes.data, words.length), words, words.length)
    let buffer = try arrays.store(key, bytes, highlight.drawn)
    highlight.drawn = highlight.key
    return buffer

## Cd by the same precedence, or none.
func color_buffer(arrays: GpuArrays*, mesh: const Mesh*) -> (gpu.Buffer?, i64)!:
    let found = try preferred(mesh, "Cd", 3)
    if found.0 < 0: return (none, -1)
    return (try attribute_buffer(arrays, mesh, found.0, tag_colors), found.1)

func attribute_buffer(arrays: GpuArrays*, mesh: const Mesh*, index: i64, tag: u8) -> gpu.Buffer!:
    let key = ArrayKey(try mesh.attribute_id(index), tag, 0)
    if let found = arrays.find(key): return found
    let tuples = try mesh.attribute_tuples(index)
    let parent = try mesh.attribute_parent(index)
    # An edited column (N after a Move) rewrites its predecessor's buffer:
    # just the edited range when the attribute is plain float triples.
    if parent != 0 and (try mesh.attribute_width(index)) == 3 and (try mesh.attribute_storage(index)) == 0 and not (try mesh.attribute_integer(index)):
        let changed = try mesh.attribute_changed(index)
        if changed.1 - changed.0 < tuples:
            let part = try arrays.staging((changed.1 - changed.0) * 12)
            try mesh.pack_attribute3_range(index, changed.0, changed.1, as_f32(part))
            if let patched = try arrays.patch(key, parent, tuples * 12, changed.0 * 12, part): return patched
    let bytes = try arrays.staging(tuples * 12)
    try mesh.pack_attribute3(index, as_f32(bytes))
    return try arrays.store(key, bytes, parent)

## The attribute `name` of at least `width` components on the highest-priority
## domain (corner, point, face, detail) and the domain the shader indexes by;
## a single-storage attribute reads as detail.
func preferred(mesh: const Mesh*, name: str, width: i64) -> (i64, i64)!:
    let domains: i64[4] = [1, 0, 2, 3]
    for domain in domains:
        let index = mesh.find_attribute(name, domain)
        if index >= 0 and (try mesh.attribute_width(index)) >= width and not (try mesh.attribute_integer(index)):
            return (index, 3 if (try mesh.attribute_storage(index)) == 1 else domain)
    return (-1, -1)

func as_f32(bytes: u8[]) -> f32[]:
    return f32[]((f32*)bytes.data, bytes.length // 4)

func as_u32(bytes: u8[]) -> u32[]:
    return u32[]((u32*)bytes.data, bytes.length // 4)