Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-gpu

Source of release 0.5.3

0.5.3 / src / gpu / canvas.lucb

#==============================================================================================
#
#   canvas - Portable colored-triangle input
#
#   DESCRIPTION:
#       Portable triangle input. Positions are homogeneous clip coordinates: -w..w for x/y and
#       0..w for z. Colors are straight-alpha linear sRGB in 0..1. The backend interpolates
#       color perspectively and blends into the sRGB target.
#
#==============================================================================================

# mark: Vertices, clips and viewports =========================================================
## One triangle vertex: a clip-space position and a straight-alpha linear-sRGB color.
pub struct Vertex:
    ## The clip-space x, in -w..w.
    pub var x: f32
    ## The clip-space y, in -w..w.
    pub var y: f32
    ## The clip-space z, in 0..w.
    pub var z: f32
    ## The homogeneous w.
    pub var w: f32 = 1.0
    ## The linear-sRGB red, 0..1.
    pub var red: f32
    ## The linear-sRGB green, 0..1.
    pub var green: f32
    ## The linear-sRGB blue, 0..1.
    pub var blue: f32
    ## The straight alpha, 0..1.
    pub var alpha: f32 = 1.0

## Scissor rectangle in backing pixels, measured from the target's top left.
## Rectangles are intersected with the target at submission; zero extent is empty.
pub struct Clip:
    ## The left edge in backing pixels.
    pub var x: u32
    ## The top edge in backing pixels.
    pub var y: u32
    ## The width in backing pixels.
    pub var width: u32
    ## The height in backing pixels.
    pub var height: u32

## Destination of clip coordinates, in backing pixels from the top left.
pub struct Viewport:
    ## The left edge in backing pixels.
    pub var x: f64
    ## The top edge in backing pixels.
    pub var y: f64
    ## The width in backing pixels.
    pub var width: f64
    ## The height in backing pixels.
    pub var height: f64

# mark: Draws and the canvas ==================================================================
struct Draw:
    var first: usize
    var count: usize
    var clip: Clip
    var depth: bool
    var depth_slope: f32
    var viewport: Viewport?
    var params: DrawParams
    # Sampled images (bindings 1..4) and a client pipeline are retained until
    # the canvas is cleared or destroyed.
    var images: TextureState*?[4]
    var filter: Filter
    var pipeline: PipelineState*?
    var uniforms: u8[128]
    var uniform_count: u32
    var geometry: GeometryState*?
    var geometry_uniforms: f32[28]
    var mesh: MeshDraw*?
    # An instanced draw (shade_instances): `first..<first + count` of the
    # canvas's instances rather than of its vertices.
    var instanced: bool
    # Instanced quads from GPU buffers (shade_quads), retained until cleared.
    var quads: QuadDraw*?

## A reusable CPU command list, independent of any backend or window. triangles
## copies its input, so callers may reuse it immediately. A failed append leaves
## the visible command list unchanged. Copies alias storage; destroy one owner.
## Recording is single-threaded but does not require a device or a main thread.
pub struct Canvas:
    var vertices: Vertex[]
    var draws: Draw[]
    var vertex_count: usize
    var draw_count: usize
    var coverage: u32[]
    var coverage_count: usize
    var vertex_budget: usize
    var draw_budget: usize
    # Instanced rectangles, their `rect` already in clip space.
    var instances: ShadeInstance[]
    var instance_count: usize

    ## Opt in to a larger bounded frame; this changes no allocation until append.
    ## The default UI budget and the draw-count limit remain unchanged.
    pub func allow_vertices(count: usize) -> !:
        if count > 8388608:
            error(command_limit, "canvas vertex budget cannot exceed 8388608")
        self.vertex_budget = canvas_max(self.vertex_budget, count)

    ## Raise the draw limit from 4096 up to `count` (at most 65536), as
    ## `allow_vertices` raises the vertex budget: for a frame several clients
    ## share. Allocates nothing until draws are recorded.
    pub func allow_draws(count: usize) -> !:
        if count > canvas_draw_ceiling:
            error(command_limit, "canvas draw limit cannot exceed 65536")
        self.draw_budget = canvas_max(self.draw_budget, count)

    ## The most draws the canvas records.
    pub func draw_limit() -> usize:
        return canvas_max(canvas_draw_default, self.draw_budget)

    ## The number of vertices recorded so far.
    pub func count() -> usize:
        return self.vertex_count

    ## Discard every recorded triangle, keeping the storage.
    pub func clear():
        self.release_textures()
        self.vertex_count = 0
        self.draw_count = 0
        self.coverage_count = 0
        self.instance_count = 0

    func release_textures():
        for draw in self.draws[..<self.draw_count]:
            for image in draw.images:
                if let texture = image:
                    release_texture(texture)
            if let pipeline = draw.pipeline:
                release_pipeline(pipeline)
            if let geometry = draw.geometry:
                release_geometry(geometry)
            if let mesh = draw.mesh:
                release_mesh_draw(mesh)
            if let quads = draw.quads:
                release_quad_draw(quads)

    func retained(geometry: GeometryState*, clip: Clip, viewport: Viewport, uniforms: f32[28], depth_slope: f32 = 0.0) -> !:
        if clip.width == 0 or clip.height == 0: return
        try self.reserve_draw()
        self.draws[self.draw_count] = Draw(first = 0, count = geometry.count * (6 if geometry.lines else 1), clip = clip, depth = true, depth_slope = depth_slope, viewport = viewport, geometry = geometry, geometry_uniforms = uniforms)
        geometry.references += 1
        self.draw_count += 1

    ## A mesh draw of `count` vertices; the canvas takes `mesh` and releases it
    ## when cleared. On failure the caller still owns it.
    func mesh(mesh: MeshDraw*, clip: Clip, viewport: Viewport, count: usize, depth_slope: f32) -> !:
        if clip.width == 0 or clip.height == 0:
            release_mesh_draw(mesh)
            return
        try self.reserve_draw()
        self.draws[self.draw_count] = Draw(first = 0, count = count, clip = clip, depth = true, depth_slope = depth_slope, viewport = viewport, mesh = mesh)
        self.draw_count += 1

    ## Independent triangles, in submission order. Depth-enabled draws use less
    ## comparison and write depth; other draws leave depth untouched. Each frame
    ## starts with depth 1.0. No culling, multisampling, or texture sampling yet.
    ## slope_bias is a nonnegative raster depth-slope factor in backing pixels;
    ## zero is ordinary depth. It moves fills away for coplanar wire overlays.
    pub func triangles(vertices: const Vertex[], clip: Clip, depth: bool = false, viewport: Viewport? = none, slope_bias: f64 = 0.0) -> !:
        if not (slope_bias >= 0.0 and slope_bias <= 256.0) or (not depth and slope_bias != 0.0):
            error(invalid_geometry, "depth slope bias requires depth testing and a finite factor in 0..256")
        if vertices.length % 3 != 0:
            error(invalid_geometry, "triangle input must contain a multiple of three vertices")
        for vertex in vertices:
            if not valid_vertex(vertex):
                error(invalid_geometry, "vertices need finite positions and linear colors in 0..1")
        if let region = viewport:
            if not (region.x >= -16384.0 and region.x <= 16384.0 and region.y >= -16384.0 and region.y <= 16384.0 and region.width >= 0.0 and region.width <= 16384.0 and region.height >= 0.0 and region.height <= 16384.0):
                error(invalid_geometry, "GPU viewport origins must be finite and in -16384..16384; extents in 0..16384")
            if region.width == 0.0 or region.height == 0.0:
                return
        if vertices.length == 0 or clip.width == 0 or clip.height == 0:
            return
        let budget = canvas_max(1048576, self.vertex_budget)
        if vertices.length > budget - self.vertex_count:
            error(command_limit, "canvas exceeds its vertex budget")
        try self.reserve_draw()
        let needed = self.vertex_count + vertices.length
        if needed > self.vertices.length:
            let capacity = canvas_max(needed, canvas_min(budget, canvas_max(256, self.vertices.length * 2)))
            let grown = try new Vertex[capacity] --- in memory.heap
            if self.vertex_count > 0:
                memory.copy(grown, self.vertices, self.vertex_count)
            if self.vertices.length > 0:
                free(self.vertices) in memory.heap
            self.vertices = grown
        memory.copy(self.vertices[self.vertex_count..], vertices, vertices.length)
        self.draws[self.draw_count] = Draw(first = self.vertex_count, count = vertices.length, clip = clip, depth = depth, depth_slope = (f32)slope_bias, viewport = viewport)
        self.vertex_count = needed
        self.draw_count += 1

    ## Room for one more draw within the draw limit; on failure nothing changes.
    func reserve_draw() -> !:
        if self.draw_count >= self.draw_limit():
            error(command_limit, "canvas exceeds its draw limit (4096 unless allow_draws raised it)")
        if self.draw_count == self.draws.length:
            let grown = try new Draw[canvas_max(16, self.draws.length * 2)] --- in memory.heap
            if self.draw_count > 0: memory.copy(grown, self.draws, self.draw_count)
            if self.draws.length > 0: free(self.draws) in memory.heap
            self.draws = grown

    ## Draw `source` of `texture` onto `rectangle`, given in backing pixels of the
    ## target, modulated by `opacity`. The texture stays retained until the canvas
    ## is cleared or destroyed, so destroying the handle meanwhile is safe.
    func image(texture: TextureState*, source: Region, rectangle: Rect, opacity: f64, filter: Filter,
                        clip: Clip, target_width: f64, target_height: f64, mode: u32 = draw_sampled) -> !:
        # Widths compared before subtracting: a released texture is 0 wide.
        if source.width == 0 or source.height == 0 or source.width > texture.width or source.height > texture.height or source.x > texture.width - source.width or source.y > texture.height - source.height:
            error(invalid_geometry, "an image source region must lie inside its texture")
        if not (opacity >= 0.0 and opacity <= 1.0):
            error(invalid_color, "image opacity must be finite and in 0..1")
        if rectangle.width == 0.0 or rectangle.height == 0.0 or clip.width == 0 or clip.height == 0:
            return
        try self.triangles(quad_vertices(rectangle, Color(1.0, 1.0, 1.0, opacity), target_width, target_height), clip)
        var draw = &self.draws[self.draw_count - 1]
        draw.params = image_params(rectangle, source, texture.width, texture.height, mode)
        draw.images[0] = texture
        draw.filter = filter
        texture.references += 1

    ## One instanced draw of `instances` (their rectangles already in clip space)
    ## with a client pipeline, under `clip`: one draw against the draw limit.
    ## The pipeline and images stay retained until the canvas is cleared.
    func shade_instances(pipeline: PipelineState*, instances: const ShadeInstance[], uniforms: const u8[], images: TextureState*?[], filter: Filter, clip: Clip) -> !:
        try check_client(pipeline, uniforms, images)
        if instances.length == 0 or clip.width == 0 or clip.height == 0:
            return
        if instances.length > canvas_instance_limit - self.instance_count:
            error(command_limit, "canvas exceeds 1048576 instances")
        try self.reserve_draw()
        let needed = self.instance_count + instances.length
        if needed > self.instances.length:
            let grown = try new ShadeInstance[canvas_max(needed, canvas_min(canvas_instance_limit, canvas_max(256, self.instances.length * 2)))] --- in memory.heap
            if self.instance_count > 0:
                memory.copy(grown, self.instances, self.instance_count)
            if self.instances.length > 0:
                free(self.instances) in memory.heap
            self.instances = grown
        memory.copy(self.instances[self.instance_count..], instances, instances.length)
        var draw = Draw(first = self.instance_count, count = instances.length, clip = clip, instanced = true, filter = filter, pipeline = pipeline)
        if uniforms.length > 0:
            memory.copy(draw.uniforms[..<uniforms.length], uniforms, uniforms.length)
        draw.uniform_count = (u32)uniforms.length
        for index in 0..<images.length:
            if let texture = images[index]:
                draw.images[index] = texture
                texture.references += 1
        pipeline.references += 1
        self.draws[self.draw_count] = draw
        self.draw_count += 1
        self.instance_count = needed

    ## Draw `rectangle` (backing pixels) with a client pipeline: `uniforms` go to
    ## the push-constant block, `images` to bindings 1.., `color` is the vertex
    ## color every fragment starts from. Pipeline and images stay retained
    ## until the canvas is cleared or destroyed.
    func shade(pipeline: PipelineState*, rectangle: Rect, color: Color, uniforms: const u8[], images: TextureState*?[],
                        filter: Filter, clip: Clip, target_width: f64, target_height: f64) -> !:
        try check_client(pipeline, uniforms, images)
        try check_color(color)
        if rectangle.width == 0.0 or rectangle.height == 0.0 or clip.width == 0 or clip.height == 0:
            return
        try self.triangles(quad_vertices(rectangle, color, target_width, target_height), clip)
        var draw = &self.draws[self.draw_count - 1]
        draw.params = DrawParams((f32)rectangle.x, (f32)rectangle.y, (f32)rectangle.width, (f32)rectangle.height, 0, 0, 0, draw_solid, 0.0, 0.0, 0.0, 0.0)
        attach_client(draw, pipeline, uniforms, images, filter)

    ## Clip-space triangles drawn with a client pipeline into `viewport`
    ## (backing pixels): each vertex color reaches the fragment stage. The
    ## pipeline and images stay retained until the canvas is cleared.
    func shade_triangles(pipeline: PipelineState*, vertices: const Vertex[], uniforms: const u8[], images: TextureState*?[],
                         filter: Filter, clip: Clip, viewport: Viewport) -> !:
        try check_client(pipeline, uniforms, images)
        let before = self.draw_count
        try self.triangles(vertices, clip, false, viewport)
        if self.draw_count == before:
            return
        attach_client(&self.draws[self.draw_count - 1], pipeline, uniforms, images, filter)

    ## Quads from GPU buffers drawn with a client pipeline into `viewport`
    ## (backing pixels); the canvas takes `quads` and releases it when
    ## cleared. On failure the caller still owns it. The pipeline and images
    ## stay retained until the canvas is cleared.
    func quads(quads: QuadDraw*, pipeline: PipelineState*, uniforms: const u8[], images: TextureState*?[], filter: Filter, clip: Clip, viewport: Viewport) -> !:
        try check_client(pipeline, uniforms, images)
        if clip.width == 0 or clip.height == 0 or viewport.width == 0.0 or viewport.height == 0.0:
            release_quad_draw(quads)
            return
        try self.reserve_draw()
        var draw = Draw(first = 0, count = quads.count, clip = clip, viewport = viewport, quads = quads)
        attach_client(&draw, pipeline, uniforms, images, filter)
        self.draws[self.draw_count] = draw
        self.draw_count += 1

    ## Release the recorded storage.
    pub func destroy():
        self.release_textures()
        if self.coverage.length > 0:
            free(self.coverage) in memory.heap
        if self.instances.length > 0:
            free(self.instances) in memory.heap
        if self.vertices.length > 0:
            free(self.vertices) in memory.heap
        if self.draws.length > 0:
            free(self.draws) in memory.heap
        self = Canvas()

## The draws a canvas allows unless raised, and the most it can be raised to.
let canvas_draw_default: usize = 4096
let canvas_draw_ceiling: usize = 65536
## The most instanced rectangles one canvas holds (64 MiB of them).
let canvas_instance_limit: usize = 1048576

## Whether a client draw of `pipeline` with `uniforms` and `images` fits the
## fragment contract: 128 uniform bytes, 4 images (3 when binding 4 holds the
## scene depth).
func check_client(pipeline: PipelineState*, uniforms: const u8[], images: TextureState*?[]) -> !:
    if uniforms.length > uniform_limit:
        error(invalid_geometry, "a draw carries at most 128 uniform bytes")
    if images.length > image_limit:
        error(invalid_geometry, "a draw samples at most 4 images")
    if pipeline.scene_depth and images.length == image_limit:
        error(invalid_geometry, "a draw reading the scene depth samples at most 3 images: binding 4 is the depth")

## Whether `draw` reads the frame's depth at binding 4 (its pipeline was made
## with scene_depth).
func reads_scene_depth(draw: const Draw*) -> bool:
    let pipeline = draw.pipeline else return false
    return pipeline.scene_depth

## Whether any draw of `canvas` reads the scene depth.
func reads_scene_depth_anywhere(canvas: const Canvas*) -> bool:
    for index in 0..<canvas.draw_count:
        if reads_scene_depth(&canvas.draws[index]): return true
    return false

## Whether a backend copies the frame's depth for draw `index` of `canvas`
## before encoding it: the draw reads the scene depth, and no copy made for an
## earlier such draw is current (some draw wrote depth since, or there was
## none). Backends end the render pass there, copy, and resume over both
## attachments.
func depth_copy_before(canvas: const Canvas*, index: usize) -> bool:
    if not reads_scene_depth(&canvas.draws[index]): return false
    var at = index
    while at > 0:
        at -= 1
        if canvas.draws[at].depth: return true
        if reads_scene_depth(&canvas.draws[at]): return false
    return true

## Make `draw` a client pipeline's: its uniforms, images and filter, the
## pipeline and images retained.
func attach_client(draw: Draw*, pipeline: PipelineState*, uniforms: const u8[], images: TextureState*?[], filter: Filter):
    if uniforms.length > 0:
        memory.copy(draw.uniforms[..<uniforms.length], uniforms, uniforms.length)
    draw.uniform_count = (u32)uniforms.length
    draw.filter = filter
    for index in 0..<images.length:
        if let texture = images[index]:
            draw.images[index] = texture
            texture.references += 1
    draw.pipeline = pipeline
    pipeline.references += 1

## Which vertex stage a client pipeline's draw runs: 0 the ordinary one, 1
## shade_instances', 2 shade_quads'. Backends build a pipeline per variant.
func client_variant(draw: Draw) -> usize:
    if draw.quads != none: return 2
    return 1 if draw.instanced else 0

# mark: Geometry helpers ======================================================================
## Two clip-space triangles covering `rectangle`, given in backing pixels of a
## target `target_width` by `target_height` pixels, colored `color`.
func quad_vertices(rectangle: Rect, color: Color, target_width: f64, target_height: f64) -> Vertex[6]:
    let left = (f32)(rectangle.x * 2.0 / target_width - 1.0)
    let right = (f32)((rectangle.x + rectangle.width) * 2.0 / target_width - 1.0)
    let top = (f32)(1.0 - rectangle.y * 2.0 / target_height)
    let bottom = (f32)(1.0 - (rectangle.y + rectangle.height) * 2.0 / target_height)
    let a = Vertex(x = left, y = top, red = (f32)color.red, green = (f32)color.green, blue = (f32)color.blue, alpha = (f32)color.alpha)
    var b = a
    var lower_right = a
    var d = a
    b.x = right
    lower_right.x = right
    lower_right.y = bottom
    d.y = bottom
    return [a, b, lower_right, a, lower_right, d]

func valid_vertex(v: Vertex) -> bool:
    return math32.is_finite(v.x) and math32.is_finite(v.y) and math32.is_finite(v.z) and math32.is_finite(v.w) and v.red >= 0.0 and v.red <= 1.0 and v.green >= 0.0 and v.green <= 1.0 and v.blue >= 0.0 and v.blue <= 1.0 and v.alpha >= 0.0 and v.alpha <= 1.0

func canvas_min(a: usize, b: usize) -> usize:
    return a if a < b else b

func canvas_max(a: usize, b: usize) -> usize:
    return a if a > b else b