Move shader vertices into a vertex buffer

This commit is contained in:
Timothy Warren 2023-04-12 10:28:48 -04:00
parent 96447196a2
commit 71449ae29b
4 changed files with 126 additions and 16 deletions

View File

@ -1,20 +1,11 @@
#version 450 #version 450
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;
layout(location = 0) out vec3 fragColor; layout(location = 0) out vec3 fragColor;
vec2 positions[3] = vec2[](
vec2(0.0, -0.5),
vec2(0.5, 0.5),
vec2(-0.5, 0.5)
);
vec3 colors[3] = vec3[](
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
void main() { void main() {
gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); gl_Position = vec4(inPosition, 0.0, 1.0);
fragColor = colors[gl_VertexIndex]; fragColor = inColor;
} }

Binary file not shown.

View File

@ -2,12 +2,15 @@ mod functions;
use functions::{ use functions::{
create_command_buffers, create_command_pool, create_framebuffers, create_instance, create_command_buffers, create_command_pool, create_framebuffers, create_instance,
create_logical_device, create_pipeline, create_render_pass, create_swapchain, create_logical_device, create_pipeline, create_render_pass, create_swapchain,
create_swapchain_image_views, create_sync_objects, pick_physical_device, create_swapchain_image_views, create_sync_objects, create_vertex_buffer, pick_physical_device,
}; };
use crate::VALIDATION_ENABLED; use crate::VALIDATION_ENABLED;
use ::anyhow::{anyhow, Result}; use ::anyhow::{anyhow, Result};
use ::lazy_static::lazy_static;
use ::log::*; use ::log::*;
use ::nalgebra_glm as glm;
use ::std::mem::size_of;
use ::thiserror::Error; use ::thiserror::Error;
use ::vulkanalia::loader::{LibloadingLoader, LIBRARY}; use ::vulkanalia::loader::{LibloadingLoader, LIBRARY};
use ::vulkanalia::prelude::v1_0::*; use ::vulkanalia::prelude::v1_0::*;
@ -63,6 +66,7 @@ impl App {
create_pipeline(&device, &mut data)?; create_pipeline(&device, &mut data)?;
create_framebuffers(&device, &mut data)?; create_framebuffers(&device, &mut data)?;
create_command_pool(&instance, &device, &mut data)?; create_command_pool(&instance, &device, &mut data)?;
create_vertex_buffer(&instance, &device, &mut data)?;
create_command_buffers(&device, &mut data)?; create_command_buffers(&device, &mut data)?;
create_sync_objects(&device, &mut data)?; create_sync_objects(&device, &mut data)?;
@ -82,6 +86,9 @@ impl App {
/// Here be Dragons /// Here be Dragons
pub unsafe fn destroy(&mut self) { pub unsafe fn destroy(&mut self) {
self.destroy_swapchain(); self.destroy_swapchain();
self.device.destroy_buffer(self.data.vertex_buffer, None);
self.device
.free_memory(self.data.vertex_buffer_memory, None);
self.data self.data
.in_flight_fences .in_flight_fences
@ -248,6 +255,9 @@ pub struct AppData {
framebuffers: Vec<vk::Framebuffer>, framebuffers: Vec<vk::Framebuffer>,
// Command Pool // Command Pool
command_pool: vk::CommandPool, command_pool: vk::CommandPool,
// Buffers
vertex_buffer: vk::Buffer,
vertex_buffer_memory: vk::DeviceMemory,
// Command Buffers // Command Buffers
command_buffers: Vec<vk::CommandBuffer>, command_buffers: Vec<vk::CommandBuffer>,
// Sync Objects // Sync Objects
@ -327,3 +337,50 @@ impl SwapchainSupport {
}) })
} }
} }
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub(crate) struct Vertex {
pos: glm::Vec2,
color: glm::Vec3,
}
impl Vertex {
fn new(pos: glm::Vec2, color: glm::Vec3) -> Self {
Self { pos, color }
}
pub fn binding_description() -> vk::VertexInputBindingDescription {
vk::VertexInputBindingDescription::builder()
.binding(0)
.stride(size_of::<Vertex>() as u32)
.input_rate(vk::VertexInputRate::VERTEX)
.build()
}
pub fn attribute_descriptions() -> [vk::VertexInputAttributeDescription; 2] {
let pos = vk::VertexInputAttributeDescription::builder()
.binding(0)
.location(0)
.format(vk::Format::R32G32_SFLOAT)
.offset(0)
.build();
let color = vk::VertexInputAttributeDescription::builder()
.binding(0)
.location(1)
.format(vk::Format::R32G32B32_SFLOAT)
.offset(size_of::<glm::Vec2>() as u32)
.build();
[pos, color]
}
}
lazy_static! {
pub(crate) static ref VERTICES: Vec<Vertex> = vec![
Vertex::new(glm::vec2(0.0, -0.5), glm::vec3(1.0, 0.0, 0.0)),
Vertex::new(glm::vec2(0.5, 0.5), glm::vec3(0.0, 1.0, 0.0)),
Vertex::new(glm::vec2(-0.5, 0.5), glm::vec3(0.0, 0.0, 1.0)),
];
}

View File

@ -6,6 +6,7 @@ use ::log::*;
use ::std::collections::HashSet; use ::std::collections::HashSet;
use ::std::ffi::CStr; use ::std::ffi::CStr;
use ::std::os::raw::c_void; use ::std::os::raw::c_void;
use ::std::ptr::copy_nonoverlapping as memcpy;
use ::vulkanalia::prelude::v1_0::*; use ::vulkanalia::prelude::v1_0::*;
use ::vulkanalia::window as vk_window; use ::vulkanalia::window as vk_window;
use ::winit::window::Window; use ::winit::window::Window;
@ -437,7 +438,11 @@ pub(super) unsafe fn create_pipeline(device: &Device, data: &mut AppData) -> Res
.module(frag_shader_module) .module(frag_shader_module)
.name(b"main\0"); .name(b"main\0");
let vertex_input_state = vk::PipelineVertexInputStateCreateInfo::builder(); let binding_descriptions = &[Vertex::binding_description()];
let attribute_descriptions = Vertex::attribute_descriptions();
let vertex_input_state = vk::PipelineVertexInputStateCreateInfo::builder()
.vertex_binding_descriptions(binding_descriptions)
.vertex_attribute_descriptions(&attribute_descriptions);
let input_assembly_state = vk::PipelineInputAssemblyStateCreateInfo::builder() let input_assembly_state = vk::PipelineInputAssemblyStateCreateInfo::builder()
.topology(vk::PrimitiveTopology::TRIANGLE_LIST) .topology(vk::PrimitiveTopology::TRIANGLE_LIST)
@ -618,6 +623,7 @@ pub(super) unsafe fn create_command_buffers(device: &Device, data: &mut AppData)
vk::PipelineBindPoint::GRAPHICS, vk::PipelineBindPoint::GRAPHICS,
data.pipeline, data.pipeline,
); );
device.cmd_bind_vertex_buffers(*command_buffer, 0, &[data.vertex_buffer], &[0]);
device.cmd_draw(*command_buffer, 3, 1, 0, 0); device.cmd_draw(*command_buffer, 3, 1, 0, 0);
device.cmd_end_render_pass(*command_buffer); device.cmd_end_render_pass(*command_buffer);
@ -649,3 +655,59 @@ pub(super) unsafe fn create_sync_objects(device: &Device, data: &mut AppData) ->
Ok(()) Ok(())
} }
pub(super) unsafe fn create_vertex_buffer(
instance: &Instance,
device: &Device,
data: &mut AppData,
) -> Result<()> {
let buffer_info = vk::BufferCreateInfo::builder()
.size((size_of::<Vertex>() * VERTICES.len()) as u64)
.usage(vk::BufferUsageFlags::VERTEX_BUFFER)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
data.vertex_buffer = device.create_buffer(&buffer_info, None)?;
let requirements = device.get_buffer_memory_requirements(data.vertex_buffer);
let memory_info = vk::MemoryAllocateInfo::builder()
.allocation_size(requirements.size)
.memory_type_index(get_memory_type_index(
instance,
data,
vk::MemoryPropertyFlags::HOST_COHERENT | vk::MemoryPropertyFlags::HOST_VISIBLE,
requirements,
)?);
data.vertex_buffer_memory = device.allocate_memory(&memory_info, None)?;
device.bind_buffer_memory(data.vertex_buffer, data.vertex_buffer_memory, 0)?;
let memory = device.map_memory(
data.vertex_buffer_memory,
0,
buffer_info.size,
vk::MemoryMapFlags::empty(),
)?;
memcpy(VERTICES.as_ptr(), memory.cast(), VERTICES.len());
device.unmap_memory(data.vertex_buffer_memory);
Ok(())
}
unsafe fn get_memory_type_index(
instance: &Instance,
data: &AppData,
properties: vk::MemoryPropertyFlags,
requirements: vk::MemoryRequirements,
) -> Result<u32> {
let memory = instance.get_physical_device_memory_properties(data.physical_device);
(0..memory.memory_type_count)
.find(|i| {
let suitable = (requirements.memory_type_bits & (1 << i)) != 0;
let memory_type = memory.memory_types[*i as usize];
suitable && memory_type.property_flags.contains(properties)
})
.ok_or_else(|| anyhow!("Failed to find suitable memory type."))
}