Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-render

Source of release 0.1.3

0.1.3 / src / render / device.lucb

#==============================================================================================
#
#   render/device - A compiled scene on the GPU, and the primary-ray probe
#
#   DESCRIPTION:
#       GpuScene holds the scene's buffers: BVH nodes, positions and indices (every
#       tracing kernel's bindings 0..2), each triangle's polygon (the probe's), and
#       each triangle's shading attributes (normals and material); and the splats'
#       records, harmonics, boxes and BVH, which kernels reach by address. `probe` traces one ray per pixel through a camera's
#       frame and reads back each pixel's polygon and distance: the check that the GPU
#       BVH agrees with the host, and what picking through a render camera uses.
#       Device calls happen on the main thread (luce-gpu's rule).
#
#==============================================================================================

pub struct GpuScene:
    pub var nodes: gpu.Buffer
    pub var positions: gpu.Buffer
    pub var indices: gpu.Buffer
    pub var faces: gpu.Buffer
    pub var shading: gpu.Buffer
    ## Hardware ray tracing's view of the scene, where the device has it: a
    ## BLAS of the triangles (instance mask 1) and one of the splats' boxes
    ## (mask 2), each where the scene has some, in one TLAS.
    pub var accelerated: bool
    pub var blas: gpu.Blas
    pub var splat_blas: gpu.Blas
    pub var tlas: gpu.Tlas
    ## The splats (splats.lucb): records, harmonics, boxes and the software BVH.
    pub var splat_count: usize
    pub var splat_records: gpu.Buffer
    pub var splat_harmonics: gpu.Buffer
    pub var splat_boxes: gpu.Buffer
    pub var splat_nodes: gpu.Buffer

    ## The scene's buffers on `device`; an empty array still gets a word. With
    ## `accelerate` and a device that traces rays, the TLAS is built too.
    pub static func upload(device: gpu.Device, scene: const CompiledScene*, accelerate: bool = true) -> GpuScene!:
        var nodes = try buffer_of(device, u8[]((u8*)scene.nodes.items.data, scene.nodes.count * memory.size_of(BvhNode)))
        errdefer nodes.destroy()
        var positions = try buffer_of(device, u8[]((u8*)scene.positions.items.data, scene.positions.count * 4))
        errdefer positions.destroy()
        var indices = try buffer_of(device, u8[]((u8*)scene.indices.items.data, scene.indices.count * 4))
        errdefer indices.destroy()
        var faces = try buffer_of(device, u8[]((u8*)scene.faces.items.data, scene.faces.count * 4))
        errdefer faces.destroy()
        var shading = try buffer_of(device, u8[]((u8*)scene.shading.items.data, scene.shading.count * 4))
        errdefer shading.destroy()
        let splats = &scene.splats
        var splat_records = try buffer_of(device, u8[]((u8*)splats.records.items.data, splats.records.count * 4))
        errdefer splat_records.destroy()
        var splat_harmonics = try buffer_of(device, u8[]((u8*)splats.harmonics.items.data, splats.harmonics.count * 4))
        errdefer splat_harmonics.destroy()
        var splat_boxes = try buffer_of(device, u8[]((u8*)splats.boxes.items.data, splats.boxes.count * 4))
        errdefer splat_boxes.destroy()
        var splat_nodes = try buffer_of(device, u8[]((u8*)splats.nodes.items.data, splats.nodes.count * memory.size_of(BvhNode)))
        errdefer splat_nodes.destroy()
        var uploaded = GpuScene(nodes, positions, indices, faces, shading, false, gpu.Blas(), gpu.Blas(), gpu.Tlas(), splats.count(),
                                splat_records, splat_harmonics, splat_boxes, splat_nodes)
        if not accelerate or (scene.triangle_count() == 0 and splats.count() == 0) or not (try device.limits()).ray_query:
            return uploaded
        errdefer uploaded.destroy()
        var instances: gpu.Instance[2] = [gpu.Instance(blas = gpu.Blas()), gpu.Instance(blas = gpu.Blas())]
        var instance_count: usize = 0
        var pass = try gpu.Compute.begin(device)
        defer pass.close()
        if scene.triangle_count() > 0:
            let triangles = gpu.Triangles(vertices = positions, vertex_count = (u32)scene.point_count(), indices = indices, triangle_count = (u32)scene.triangle_count())
            uploaded.blas = try gpu.Blas.create(device, triangles, false)
            try pass.build_blas(uploaded.blas, triangles)
            instances[instance_count] = gpu.Instance(blas = uploaded.blas, mask = 1)
            instance_count += 1
        if splats.count() > 0:
            let boxes = gpu.Boxes(buffer = splat_boxes, count = (u32)splats.count())
            uploaded.splat_blas = try gpu.Blas.create_boxes(device, boxes, false)
            try pass.build_boxes(uploaded.splat_blas, boxes)
            instances[instance_count] = gpu.Instance(blas = uploaded.splat_blas, mask = 2)
            instance_count += 1
        uploaded.tlas = try gpu.Tlas.create(device, (u32)instance_count)
        try pass.build_tlas(uploaded.tlas, instances[..<instance_count])
        # Later passes are ordered after this one; nothing waits for it.
        try pass.submit()
        uploaded.accelerated = true
        return uploaded

    ## Upload `scene`'s triangle shading attributes (normals and materials) in
    ## place of these: the same geometry with its materials assigned anew
    ## (Renderer.reload).
    pub func replace_shading(device: gpu.Device, scene: const CompiledScene*) -> !:
        let shading = try buffer_of(device, u8[]((u8*)scene.shading.items.data, scene.shading.count * 4))
        self.shading.destroy()
        self.shading = shading

    ## The splat buffers' addresses for the kernels' constants (splats.glsl):
    ## records, harmonics and the software BVH.
    pub func splat_addresses() -> u64[3]!:
        return [try self.splat_records.address(), try self.splat_harmonics.address(), try self.splat_nodes.address()]

    pub func destroy():
        self.nodes.destroy()
        self.positions.destroy()
        self.indices.destroy()
        self.faces.destroy()
        self.shading.destroy()
        self.splat_records.destroy()
        self.splat_harmonics.destroy()
        self.splat_boxes.destroy()
        self.splat_nodes.destroy()
        self.tlas.destroy()
        self.blas.destroy()
        self.splat_blas.destroy()

## A buffer of `bytes`; an empty one still gets 64 zero bytes, since Metal wants
## room for at least one element of whatever the kernel declares (a vec4, a node).
func buffer_of(device: gpu.Device, bytes: const u8[]) -> gpu.Buffer!:
    if bytes.length == 0:
        return try gpu.Buffer.allocate(device, 64)
    return try gpu.Buffer.create(device, bytes)

## One pixel of a probe: the polygon hit (none: the ray missed) and its distance
## along the frame's unnormalized direction.
pub struct Probe:
    pub let face: u32?
    pub let distance: f32

## Trace `frame`'s pixel-center rays through `scene`: width × height probes, row
## by row from the top, into `out`.
pub func probe(device: gpu.Device, scene: const GpuScene*, frame: const RayFrame*, out: Probe[]) -> !:
    let count = (usize)frame.width * (usize)frame.height
    if out.length != count: error(invalid, "a probe needs one result per pixel")
    var kernel = try gpu.Kernel.create(device, probe_comp_words, probe_comp_msl, probe_comp_group, probe_comp_bindings)
    defer kernel.destroy()
    var results = try gpu.Buffer.allocate(device, count * 8)
    defer results.destroy()
    var block: f32[16]
    try frame.pack(block)
    var pass = try gpu.Compute.begin(device)
    defer pass.close()
    let bindings: gpu.Binding[5] = [gpu.Binding(buffer = scene.nodes), gpu.Binding(buffer = scene.positions), gpu.Binding(buffer = scene.indices),
                                    gpu.Binding(buffer = scene.faces), gpu.Binding(buffer = results)]
    try pass.dispatch(kernel, bindings, u8[]((u8*)&block[0], 64), (frame.width + 7) // 8, (frame.height + 7) // 8)
    try pass.submit()
    try pass.wait()
    let bytes = try new u8[count * 8] --- in memory.heap
    defer free(bytes) in memory.heap
    try results.read(0, bytes)
    for at in 0..<count:
        let face = memory.read[u32]((const void*)&bytes[at * 8])
        let distance = memory.read[f32]((const void*)&bytes[at * 8 + 4])
        out[at] = Probe(none if face == 4294967295 else face, distance)