Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-render

Source of release 0.1.1

0.1.1 / src / render / scene.lucb

#==============================================================================================
#
#   render/scene - A scene in the kernels' layout
#
#   DESCRIPTION:
#       Every polygon of a set and its visible instances as world-space triangles: f32
#       positions (x, y, z per point), three point indices per triangle, each
#       triangle's polygon (its face in its mesh, offset by the faces of the meshes
#       before it), and its shading attributes: the normals of its three corners
#       (octahedral, snorm16 × 2) and its material, four u32s. A triangle's material
#       is its face's `material` attribute looked up among the set's materials
#       (flattened, `materials`): its index + 1, or 0 (the render's default
#       material) when the face names none or a material the set lacks. Shading normals follow
#       the viewport (luce-3d's mesh batches): an authored N on the first domain that
#       has one (corner, point, face, detail), else the mesh's smooth normals. Texture
#       coordinates come the same way from `uv` (two f32 a corner, six a triangle;
#       zero without one).
#       Cameras and lights come flattened to world space. Analytic CAD has no
#       triangles until a Tessellate node; such components are counted in
#       `skipped`, not drawn.
#
#       Instances are realized into one triangle list for now; a two-level hierarchy
#       (one BVH per prototype, instances above) replaces this with hardware ray tracing.
#
#==============================================================================================

pub struct CompiledScene:
    pub var positions: Growing[f32]
    ## Three point indices per triangle; build_bvh reorders them into leaf order.
    pub var indices: Growing[u32]
    ## Each triangle's polygon, reordered with it.
    pub var faces: Growing[u32]
    ## Four u32s a triangle: its corners' normals (octahedral) and its material.
    pub var shading: Growing[u32]
    ## Six f32s a triangle: its corners' texture coordinates.
    pub var uvs: Growing[f32]
    pub var nodes: Growing[BvhNode]
    pub var objects: SceneObjects
    ## Every material definition of the set and its instances.
    pub var materials: Materials
    ## Components with no triangles to trace (CAD before Tessellate).
    pub var skipped: usize

    pub func init():
        self.positions = Growing[f32]()
        self.indices = Growing[u32]()
        self.faces = Growing[u32]()
        self.shading = Growing[u32]()
        self.uvs = Growing[f32]()
        self.nodes = Growing[BvhNode]()
        self.objects = SceneObjects()
        self.materials = Materials()
        self.skipped = 0

    pub func triangle_count() -> usize:
        return self.indices.count // 3

    pub func point_count() -> usize:
        return self.positions.count // 3

    pub func close():
        self.positions.close()
        self.indices.close()
        self.faces.close()
        self.shading.close()
        self.uvs.close()
        self.nodes.close()
        self.objects.close()
        self.materials.close()

## `set` compiled: its triangles in world space with their BVH, and its cameras
## and lights.
pub func compile_scene(set: const GeometrySet*) -> CompiledScene!:
    var scene = CompiledScene()
    errdefer scene.close()
    var face_base: u32 = 0
    try materials_flattened(set, &scene.materials)
    try add_set(&scene, set, Matrix4(), &face_base, 0)
    if scene.point_count() > 4294967295: error(limit, "a scene holds at most 2^32 points")
    try scene_flattened(set, Matrix4(), &scene.objects)
    try build_bvh(&scene)
    return scene

func add_set(scene: CompiledScene*, set: const GeometrySet*, matrix: Matrix4, face_base: u32*, depth: usize) -> !:
    if depth > 64: error(invalid, "instances nest more than 64 deep")
    for index in 0..<set.component_count():
        let entry = set.component(index)
        if entry.kind == mesh_component():
            try add_mesh(scene, (const Mesh*)entry.data, matrix, face_base)
        elif entry.kind == instances_component():
            let instances = (const Instances*)entry.data
            for at in 0..<instances.count():
                let item = instances.item(at)
                if not item.visible: continue
                try add_set(scene, item.set, matrix.multiply(item.matrix()), face_base, depth + 1)
        elif entry.kind.unrealizable != "":
            scene.skipped += 1

## One mesh's points placed by `matrix`, and its display triangles.
func add_mesh(scene: CompiledScene*, mesh: const Mesh*, matrix: Matrix4, face_base: u32*) -> !:
    let points = mesh.point_span()
    let origin = mesh.position_origin()
    let corners = mesh.corner_span()
    let triangles = mesh.triangle_span()
    let corner_faces = try mesh.corner_face_span()
    let base = (u32)scene.point_count()
    try scene.positions.reserve(scene.positions.count + points.length * 3)
    for point in points:
        let placed = matrix.transform_point(point.vector().add(origin))
        scene.positions.items[scene.positions.count] = (f32)placed.x
        scene.positions.items[scene.positions.count + 1] = (f32)placed.y
        scene.positions.items[scene.positions.count + 2] = (f32)placed.z
        scene.positions.count += 3
    let count = triangles.length // 3
    var normals = try shading_normals(mesh)
    defer normals.close()
    let face_materials = try material_indices(&scene.materials, mesh)
    defer free(face_materials) in memory.heap
    let uv = texture_coordinates(mesh)
    try scene.uvs.reserve(scene.uvs.count + count * 6)
    try scene.indices.reserve(scene.indices.count + count * 3)
    try scene.faces.reserve(scene.faces.count + count)
    try scene.shading.reserve(scene.shading.count + count * 4)
    for at in 0..<count:
        for k in 0..<(usize)3:
            let corner = (usize)triangles[at * 3 + k]
            scene.indices.items[scene.indices.count + k] = base + (u32)corners[corner]
            let element = normals.element(corner, (usize)corners[corner], (usize)corner_faces[corner])
            # A singular placement leaves no normal to transform: any will do, as
            # it flattens the triangle to nothing.
            let normal = matrix.transform_normal(normals.values.items[element].vector()) catch failure:
                _ = failure
                recover Vector3(0.0, 1.0, 0.0)
            scene.shading.items[scene.shading.count + k] = octahedral(normal)
            var u: f64 = 0.0
            var v: f64 = 0.0
            if uv.0 >= 0:
                let uv_at = (i64)uv_element(uv.1, corner, (usize)corners[corner], (usize)corner_faces[corner], uv.2)
                u = mesh.attribute_value(uv.0, uv_at, 0) catch failure:
                    _ = failure
                    recover 0.0
                v = mesh.attribute_value(uv.0, uv_at, 1) catch failure:
                    _ = failure
                    recover 0.0
            scene.uvs.items[scene.uvs.count + k * 2] = (f32)u
            scene.uvs.items[scene.uvs.count + k * 2 + 1] = (f32)v
        scene.shading.items[scene.shading.count + 3] = face_materials[(usize)corner_faces[(usize)triangles[at * 3]]]
        scene.indices.count += 3
        scene.shading.count += 4
        scene.uvs.count += 6
        scene.faces.items[scene.faces.count] = *face_base + (u32)corner_faces[(usize)triangles[at * 3]]
        scene.faces.count += 1
    *face_base += (u32)mesh.face_count()

## Each face's material: index + 1 in `materials` of the path its `material`
## attribute names, else 0. Each distinct path is looked up once.
func material_indices(materials: const Materials*, mesh: const Mesh*) -> u32[]!:
    let faces = (usize)mesh.face_count()
    let out = try new u32[faces] in memory.heap
    let attribute = mesh.find_attribute("material", 2)
    if attribute < 0 or materials.count() == 0: return out
    let names = (usize)(try mesh.attribute_string_count(attribute))
    let looked = try new u32[names] in memory.heap
    defer free(looked) in memory.heap
    for at in 0..<names:
        let found = materials.index_of(try mesh.attribute_string(attribute, (i64)at))
        looked[at] = (u32)(found + 1)
    for face in 0..<faces:
        let path = try mesh.attribute_text(attribute, (i64)face)
        for at in 0..<names:
            if (try mesh.attribute_string(attribute, (i64)at)) == path:
                out[face] = looked[at]
                break
    return out

## A mesh's `uv` attribute: its index (-1: none), its domain (0 point, 1
## corner, 2 face) and whether it stores one value for all.
func texture_coordinates(mesh: const Mesh*) -> (i64, i64, bool):
    let domains: i64[3] = [1, 0, 2]
    for domain in domains:
        let index = mesh.find_attribute("uv", domain)
        if index < 0: continue
        let width = mesh.attribute_width(index) catch failure:
            _ = failure
            recover 0
        let integer = mesh.attribute_integer(index) catch failure:
            _ = failure
            recover true
        if width < 2 or integer: continue
        let single = (mesh.attribute_storage(index) catch failure:
            _ = failure
            recover 0) == 1
        return (index, domain, single)
    return (-1, 0, false)

func uv_element(domain: i64, corner: usize, point: usize, face: usize, single: bool) -> usize:
    if single: return 0
    if domain == 1: return corner
    if domain == 0: return point
    return face

## A mesh's shading normals and the domain they are indexed by.
struct ShadingNormals:
    var values: Growing[Float3]
    ## 0 point, 1 corner, 2 face, 3 detail.
    var domain: i64

    func element(corner: usize, point: usize, face: usize) -> usize:
        if self.domain == 1: return corner
        if self.domain == 0: return point
        if self.domain == 2: return face
        return 0

    func close():
        self.values.close()

func shading_normals(mesh: const Mesh*) -> ShadingNormals!:
    var values = Growing[Float3]()
    errdefer values.close()
    let domains: i64[4] = [1, 0, 2, 3]
    for domain in domains:
        let index = mesh.find_attribute("N", domain)
        if index < 0 or (try mesh.attribute_width(index)) < 3 or (try mesh.attribute_integer(index)): continue
        let tuples = try mesh.attribute_tuples(index)
        try values.fill(tuples, Float3(0.0, 1.0, 0.0))
        try mesh.pack_attribute3(index, f32[]((f32*)values.items.data, tuples * 3))
        return ShadingNormals(values, 3 if (try mesh.attribute_storage(index)) == 1 else domain)
    let smooth = try mesh.smooth_normal_span()
    try values.assign(smooth)
    return ShadingNormals(values, 1 if (try mesh.smooth_normals_corner_domain()) else 0)

## A unit vector as two snorm16 octahedral coordinates (x in the low half), as
## GLSL's unpackSnorm2x16 reads them.
pub func octahedral(n: Vector3) -> u32:
    let length = math.abs(n.x) + math.abs(n.y) + math.abs(n.z)
    if length <= 0.0: return octahedral(Vector3(0.0, 1.0, 0.0))
    var x = n.x / length
    var y = n.y / length
    if n.z < 0.0:
        let fx = (1.0 - math.abs(y)) * (1.0 if x >= 0.0 else -1.0)
        let fy = (1.0 - math.abs(x)) * (1.0 if y >= 0.0 else -1.0)
        x = fx
        y = fy
    let qx = (i64)math.round(math.clamp(x, -1.0, 1.0) * 32767.0)
    let qy = (i64)math.round(math.clamp(y, -1.0, 1.0) * 32767.0)
    return ((u32)(qx & 0xffff)) | ((u32)(qy & 0xffff) << 16)