indexed_quad.cpp

cross platform rendering playground

src/backend/conformance/indexed_quad/indexed_quad.cpp

7.79 KB
#include "backend/rhi.h"
#include "core/logger.h"
#include "core/platform.h"

#include <chrono>
#include <cmath>
#include <cstring>
#include <stddef.h>

static constexpr u32 QUAD_VERTEX_BINDING = 1;

struct QuadVertex {
    f32 pos[2];
    f32 color[3];
};

static constexpr QuadVertex QUAD_VERTICES[4] = {
    {{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}},
    {{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}},
    {{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}},
    {{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}},
};

static constexpr u32 QUAD_INDICES[6] = {0, 1, 2, 2, 3, 0};

struct QuadPush {
    f32 time;
    f32 _pad0;
    f32 offset[2];
    f32 tint[4];
};

int main() {
    vel::Logger::init();
    rhi::Config config{};
    config.vsync_enabled = true;
    config.enable_validation = true;

    rhi::Device device{};
    rhi::Swapchain swapchain{};
    rhi::CmdPool pool{};
    rhi::CmdBuffer cmd{};
    rhi::Sync *frame_sync = nullptr;
    rhi::ShaderCompiler sc{};
    rhi::Buffer vertex_buffer{};
    rhi::Buffer index_buffer{};
    rhi::RenderPipeline pipeline{};

    Platform platform{};
    platform.width = 800;
    platform.height = 800;

    init_platform(config.instance_extensions);
    rhi::create_context(device, config);
    if (!rhi::create_memory_allocator(device)) {
        VEL_CRITICAL("indexed-quad-example: failed to create memory allocator");
        return 1;
    }
    if (!rhi::init_compiler(sc)) {
        VEL_CRITICAL("indexed-quad-example: failed to init shader compiler");
        return 1;
    }
    create_window(device, platform, "indexed-quad-example", WindowMode::Windowed, true);

    rhi::SwapchainDesc swapchain_desc{};
    swapchain_desc.native_window = platform_native_window(platform);
    swapchain_desc.width = platform.width;
    swapchain_desc.height = platform.height;
    swapchain_desc.vsync_enabled = config.vsync_enabled;
    swapchain_desc.image_count = config.swapchain_image_count;
    rhi::create_swapchain(device, swapchain_desc, swapchain);

    rhi::Queue graphics_queue = rhi::graphics_queue(device);

    rhi::CmdPoolDesc cmd_pool_desc;
    cmd_pool_desc.queue_family_index = rhi::queue_family_index(graphics_queue);
    cmd_pool_desc.flags = rhi::CmdPoolUsage::Transient | rhi::CmdPoolUsage::ResetCommandBuffer;
    rhi::create_cmd_pool(device, cmd_pool_desc, pool);
    rhi::CmdBufferDesc cmd_desc{};
    cmd_desc.pool = &pool;
    cmd_desc.level = rhi::CmdBufferLevel::Primary;
    rhi::create_cmd_buffer(device, cmd_desc, cmd);

    frame_sync = rhi::sync_create(device, 0);

    rhi::BufferDesc vb_desc{};
    vb_desc.size = sizeof(QUAD_VERTICES);
    vb_desc.usage = rhi::BufferUsage::VertexBuffer;
    vb_desc.memory = rhi::BufferMemType::Upload;
    rhi::create_buffer(device, vb_desc, vertex_buffer);
    std::memcpy(vertex_buffer.mapped, QUAD_VERTICES, sizeof(QUAD_VERTICES));

    rhi::BufferDesc ib_desc{};
    ib_desc.size = sizeof(QUAD_INDICES);
    ib_desc.usage = rhi::BufferUsage::IndexBuffer;
    ib_desc.memory = rhi::BufferMemType::Upload;
    rhi::create_buffer(device, ib_desc, index_buffer);
    std::memcpy(index_buffer.mapped, QUAD_INDICES, sizeof(QUAD_INDICES));

    rhi::RenderPipelineDesc pd{};
    pd.device = &device;
    pd.set_shaders(sc, "conformance/indexed_quad.slang", "vsMain", "fsMain");
    pd.add_vertex_binding(QUAD_VERTEX_BINDING, sizeof(QuadVertex));
    pd.add_vertex_attribute(0, QUAD_VERTEX_BINDING, rhi::ImageFormat::RG32_FLOAT, offsetof(QuadVertex, pos));
    pd.add_vertex_attribute(1, QUAD_VERTEX_BINDING, rhi::ImageFormat::RGB32_FLOAT, offsetof(QuadVertex, color));
    pd.set_depth_testing(false, false, rhi::PipelineCompareOp::LESS);
    pd.set_cull_mode(rhi::PipelineCullMode::NONE, rhi::PipelineTriangleWindingOrder::CCW);
    pd.set_color_format(rhi::swapchain_format(swapchain));
    pipeline = pd.build();

    const auto start_time = std::chrono::steady_clock::now();

    u64 frame_count = 0;
    while (platform_update(platform)) {
        if (platform.framebuffer_resized || rhi::swapchain_needs_recreate(swapchain)) {
            platform.framebuffer_resized = false;
            if (!platform_wait_for_valid_framebuffer(platform)) {
                break;
            }
            rhi::queue_wait_idle(device);
            rhi::destroy_swapchain(device, swapchain);
            swapchain_desc.width = platform.width;
            swapchain_desc.height = platform.height;
            rhi::create_swapchain(device, swapchain_desc, swapchain);
            continue;
        }

        const f32 time = std::chrono::duration<f32>(std::chrono::steady_clock::now() - start_time).count();
        QuadPush push{};
        push.time = time;
        push.offset[0] = 0.25f * std::sin(time * 0.7f);
        push.offset[1] = 0.25f * std::cos(time * 0.9f);
        const f32 pulse = 0.75f + 0.25f * std::sin(time * 2.0f);
        push.tint[0] = pulse;
        push.tint[1] = pulse;
        push.tint[2] = pulse;
        push.tint[3] = 1.0f;

        rhi::reset_cmd_buffer(cmd);
        rhi::begin_cmd_buffer(cmd, rhi::CmdBufferBeginDesc{.usage = rhi::CmdBufferUsage::OneTimeSubmit});

        u32 image_index = 0;
        if (!rhi::acquire_swapchain_image(device, swapchain, image_index, cmd)) {
            rhi::reset_cmd_buffer(cmd);
            continue;
        }

        rhi::Image *swap_image = rhi::swapchain_image(swapchain, image_index);
        rhi::Extent2D extent = rhi::swapchain_extent(swapchain);
        rhi::ImageView swap_view = rhi::get_cached_image_view(device, *swap_image, {.aspect = rhi::ImageAspect::Color});

        rhi::AttachmentDesc color_att{};
        color_att.img = &swap_view;
        color_att.loadOp = rhi::LoadOp::CLEAR;
        color_att.storeOp = rhi::StoreOp::STORE;
        color_att.clearValue.color.float32[0] = 0.1f;
        color_att.clearValue.color.float32[1] = 0.1f;
        color_att.clearValue.color.float32[2] = 0.1f;
        color_att.clearValue.color.float32[3] = 1.0f;

        rhi::RenderingInfo ri{};
        ri.colorAttachments[0] = color_att;
        ri.colorAttachmentCount = 1;
        ri.width = extent.width;
        ri.height = extent.height;

        rhi::begin_rendering(cmd, ri);
        rhi::set_pipeline(cmd, pipeline);

        rhi::Viewport vp{};
        vp.width = (f32)extent.width;
        vp.height = (f32)extent.height;
        rhi::set_viewports(cmd, &vp);

        rhi::Rect scissor{};
        scissor.width = (i16)extent.width;
        scissor.height = (i16)extent.height;
        rhi::set_scissors(cmd, &scissor);

        rhi::set_vertex_buffer(cmd, vertex_buffer, QUAD_VERTEX_BINDING, 0);
        rhi::set_index_buffer(cmd, index_buffer, 0, rhi::IndexType::UINT32);
        rhi::set_constants(cmd, pipeline, rhi::ShaderStage::VERTEX | rhi::ShaderStage::FRAGMENT, sizeof(push), &push);
        rhi::draw_indexed(cmd, 6, 1, 0, 0, 0);
        rhi::end_rendering(cmd);

        rhi::ImageRange range{};
        rhi::barrier(cmd, *swap_image, range, swap_image->state, rhi::ResourceState::Display);
        rhi::end_cmd_buffer(cmd);

        rhi::QueueSignal completion{{frame_sync, frame_count + 1}};
        rhi::QueueSubmitDesc submit{};
        submit.cmd_count = 1;
        submit.cmds = &cmd;
        submit.signal_count = 1;
        submit.signals = &completion;
        rhi::queue_submit(device, graphics_queue, submit);

        rhi::present_swapchain(device, swapchain, image_index, {frame_sync, frame_count + 1});
        ++frame_count;

        rhi::sync_host_wait(frame_sync, frame_count);
    }

    rhi::device_wait_idle(device);

    rhi::destroy_pipeline(device, pipeline);
    rhi::destroy_buffer(device, index_buffer);
    rhi::destroy_buffer(device, vertex_buffer);
    rhi::sync_destroy(frame_sync);
    rhi::destroy_cmd_buffer(device, pool, cmd);
    rhi::destroy_cmd_pool(device, pool);
    rhi::destroy_swapchain(device, swapchain);
    rhi::destroy_memory_allocator(device);
    destroy_window(device, platform);
    rhi::destroy_context(device);

    vel::Logger::shutdown();
    return 0;
}