Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-gpu

Source of release 0.5.7

0.5.7 / src / gpu / mesh.lucb

#==============================================================================================
#
#   mesh - Indexed mesh drawing
#
#   DESCRIPTION:
#       A mesh draw pulls its vertices from up to seven buffers (buffer.lucb, shaders/mesh.glsl):
#       a mesh's positions, topology, normals or colors, so a changed position array redraws
#       after one upload with no per-vertex CPU work. The same buffers draw surfaces, constant-width
#       wires and face ids for picking; the shading (Lambert, flat, zebra, isophotes, normals)
#       is a parameter, so switching it re-uploads nothing.
#
#==============================================================================================

# mark: Mesh draws =============================================================================
## What a mesh draw produces: shaded surfaces, wires between point pairs, or
## face ids (into an rgba8_linear target) for picking.
pub enum MeshKind as u8:
    surface = 0
    wires = 1
    ids = 2

## The buffers a mesh draw reads (shaders/mesh.glsl); unused ones stay closed.
## Surfaces and ids: `triangles` holds three corner ids per triangle, `faces`
## one face id per triangle. Wires: `triangles` holds two point ids per edge.
pub struct MeshBuffers:
    pub var triangles: Buffer
    pub var corners: Buffer
    pub var positions: Buffer
    pub var normals: Buffer
    pub var colors: Buffer
    pub var faces: Buffer
    pub var flags: Buffer

## Parameter block size in f32 values; the layout is mesh.glsl's `Parameters`.
## The block only grows at its end: a new parameter is appended, and its
## default, zero, leaves its feature off. draw_mesh takes any block from
## `mesh_base_parameter_count` values up to this size and fills the values
## a shorter block leaves out with zeros, so a caller written against an
## older layout draws as it did.
pub let mesh_parameter_count: usize = 128
## The block's first layout, through `mesh_accent`.
pub let mesh_base_parameter_count: usize = 120

## Parameter offsets, in f32 values, into the block `draw_mesh` takes.
pub let mesh_clip: usize = 0
pub let mesh_world: usize = 16
pub let mesh_normal_matrix: usize = 32
pub let mesh_tint: usize = 48
pub let mesh_ambient: usize = 52
pub let mesh_light_direction: usize = 56
pub let mesh_light_color: usize = 72
pub let mesh_eye: usize = 88
pub let mesh_mode: usize = 92
pub let mesh_zebra: usize = 96
## Zebra's stripe axis (xyz); draft shading's pull direction (xyz) and the
## draft angle it asks for in degrees (w).
pub let mesh_zebra_axis: usize = 100
pub let mesh_zebra_dark: usize = 104
pub let mesh_zebra_light: usize = 108
pub let mesh_line: usize = 112
pub let mesh_accent: usize = 116
## Curvature shading: x the value (0 mean, 1 Gaussian, 2 k1, 3 k2, 4 the
## larger |k|), y the value the color map spans, z and w a radius band: a
## point whose smallest radius of curvature is under z draws magenta, over w
## grey (0: no limit). Only the curvature shading reads it.
pub let mesh_curvature: usize = 120
## Fading: x from 0 (opaque, as shaded) to 1 (most see-through and grey),
## for objects drawn as context around what is being edited. Faded draws
## blend over what is already drawn, so they go last.
pub let mesh_fade: usize = 124

## Shading modes (the block's mode.x).
pub enum Shading as u8:
    lit = 0
    flat = 1
    zebra = 2
    isophote = 3
    normals = 4
    unlit = 5
    ## A diverging colour map of principal curvatures (k1, k2) the colors
    ## buffer carries: blue below zero, green at zero, red above.
    curvature = 6
    ## Draft angle against a pull direction (mesh_zebra_axis): green past
    ## the angle asked for, yellow within it either way, red past it facing
    ## away (Fusion's and Alias's draft analysis).
    draft = 7

## A recorded mesh draw: retained buffers and its parameter block.
struct MeshDraw:
    var buffers: BufferState*?[7]
    var parameters: f32[128]
    var kind: MeshKind

## A faded draw (its mesh_fade above 0) blends over the scene without
## writing depth, so what lies behind it, drawn after it, still shows.
func mesh_faded(draw: const MeshDraw*) -> bool:
    return draw.kind != MeshKind.ids and draw.parameters[mesh_fade] > 0.0

## The pipeline variant a draw takes: its kind, or past the kinds for a
## faded surface or wire (no depth writes).
func mesh_variant(draw: const MeshDraw*) -> usize:
    return (usize)(u8)draw.kind + (3 if mesh_faded(draw) else 0)

func release_mesh_draw(draw: MeshDraw*):
    for buffer in draw.buffers:
        if let state = buffer: release_buffer(state)
    free(draw) in memory.heap

## Record `vertices` mesh vertices (3 per triangle, 6 per wire edge) into
## `target`, depth tested. `parameters` is the block, `mesh_base_parameter_count`
## to `mesh_parameter_count` values (see mesh_parameter_count); draw_mesh
## fills its viewport size and clip-space y sign. slope_bias
## pushes surfaces back for a coplanar wire overlay, in logical pixels.
pub func draw_mesh(target: const RenderTarget*, buffers: const MeshBuffers*, vertices: usize, parameters: const f32[], kind: MeshKind, slope_bias: f64 = 0.0) -> !:
    try target.frame.check()
    if parameters.length < mesh_base_parameter_count or parameters.length > mesh_parameter_count or vertices == 0 or vertices % (6 if kind == MeshKind.wires else 3) != 0:
        error(invalid_geometry, "a mesh draw needs its parameter block and whole triangles or edges")
    if not (slope_bias >= 0.0 and slope_bias <= 32.0) or (kind == MeshKind.wires and slope_bias != 0.0):
        error(invalid_geometry, "slope bias requires surfaces and a finite factor in 0..32")
    # mode.w holds the id base as bits, not a number.
    for index in 0..<parameters.length:
        if index != mesh_mode + 3 and not math32.is_finite(parameters[index]): error(invalid_geometry, "nonfinite mesh parameters")
    let device = target.frame.device else error(unavailable, "a standalone frame cannot draw device buffers")
    let handles: Buffer[7] = [buffers.triangles, buffers.corners, buffers.positions, buffers.normals, buffers.colors, buffers.faces, buffers.flags]
    for handle in handles:
        if let state = handle.state:
            if state.device != device: error(wrong_device, "a mesh buffer belongs to another device")
    if handles[0].state == none or handles[2].state == none:
        error(invalid_geometry, "a mesh draw needs its triangles (or edges) and positions")
    let size = try target.size()
    if size.width <= 0.0 or size.height <= 0.0: return
    let scale_x = frame_scale(target.frame.size.pixel_width, target.frame.size.width)
    let scale_y = frame_scale(target.frame.size.pixel_height, target.frame.size.height)
    let depth_slope = slope_bias * math.max(scale_x, scale_y)
    let region = Viewport(target.rectangle.x * scale_x, target.rectangle.y * scale_y, size.pixel_width, size.pixel_height)
    var draw = try new MeshDraw(kind = kind) in memory.heap
    memory.copy(draw.parameters[..<parameters.length], parameters, parameters.length)
    # Parameters an older, shorter block leaves out are off.
    for index in parameters.length..<mesh_parameter_count: draw.parameters[index] = 0.0
    draw.parameters[mesh_line + 1] = (f32)size.width
    draw.parameters[mesh_line + 2] = (f32)size.height
    draw.parameters[mesh_eye + 3] = -1.0 if device.backend == Backend.vulkan else 1.0
    for index in 0..<handles.length:
        if let state = handles[index].state:
            state.references += 1
            draw.buffers[index] = state
    target.frame.canvas.mesh(draw, target.clipping, region, vertices, (f32)depth_slope) catch failure:
        release_mesh_draw(draw)
        error(failure.code, failure.message)