From 71449ae29bf09426d8b745bf0ea7b9c7418d2ab7 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 12 Apr 2023 10:28:48 -0400 Subject: [PATCH] Move shader vertices into a vertex buffer --- shaders/shader.vert | 19 ++++--------- shaders/vert.spv | Bin 1504 -> 1080 bytes src/app.rs | 59 ++++++++++++++++++++++++++++++++++++++- src/app/functions.rs | 64 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 126 insertions(+), 16 deletions(-) diff --git a/shaders/shader.vert b/shaders/shader.vert index f5b2f8d..9f27f54 100644 --- a/shaders/shader.vert +++ b/shaders/shader.vert @@ -1,20 +1,11 @@ #version 450 +layout(location = 0) in vec2 inPosition; +layout(location = 1) in vec3 inColor; + 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() { - gl_Position = vec4(positions[gl_VertexIndex], 0.0, 1.0); - fragColor = colors[gl_VertexIndex]; + gl_Position = vec4(inPosition, 0.0, 1.0); + fragColor = inColor; } diff --git a/shaders/vert.spv b/shaders/vert.spv index a41dd2cd675e3469d59dc6e98d84c97a7d2d2693..1e4ce0c041e7ee15f8cf030b9c3e352942361e75 100644 GIT binary patch literal 1080 zcmYk4Uuzmc6vZd%Mx)Wx7-O5JsUeSr(1)fJN*h8_whw}qKwlTpZ5Y_BvTjP-r+l`2 zs=gF@ezQB`$o1ZP?!Pm4wpux>8?$9vrfp75ak{1=#0cAVIvm}O&R6;T{N2S{GCHQ} z63N*!JI=1@|9)yyoVH|N@=EerQq`{_{iK4LX_{~ph2wEJ`V!5S%V?GVPU0xBX&lXM z7SD3~GbXRGk!RCc@-W{_2$ZooGZ5F7X51ywB+kCaSswqAE409|i7i$(w~JJ0-Q{x! zhubv2wSP33nj!{g#jX>(ys@i%n$F^Nj13TbNRo9d&^@_3C(w@_*mOP8VeI5bHod!E zB#X@D)!dG3S|DGQ#XUG)d#rd9UdtGd!I3=pcnlki{e+5OlNSns(}{$G51&n+_rhmJ zPgT^Nss}x>4`ppj4*H}gv-Rwj>{|hG6#Q8!hzQ_Y39J0eqCuefYT43U4T(f?tz5k{l4=aFR6bao7r%s z|4V6Vz=$80HaPw9*{zTJo%%RFyJr4-y*WJDA%~j3LIUYeLgCz#!1tR_<{p-q)EXO< u7(FLq3fJcna*1(2?sTOd+~-KbPTAXMO~oglneZG+;7E+S;Qtfj50d|?qgO8g literal 1504 zcmYk5ZBNud6oqGZ>4G32BH#;R0mT<^MFnDF)EG3?WD_tXer-10N+zk@OW-Q!$6U%CCwBbK=EWe5;z^DZB6pD_lbols z;A~j*!x>3aHS;kY(h;+8ZeOy&`7ymK{vghmXU$b^!qFcb-s$KIjvgFG49B?z%J}l= z0x|SK?oo}|e?!JvmI~dbYWN26s-mvEFI!W+9#DzNtqAiXd>L!E#+MXRzb-s0PYs+e z%-(zt{$-81PdMuF^D>sh3l;pmr?cT(i!wCuPIE=E)*Gi;5`e=TcU3Vp71u3$SQh4c z=*ctVHF^4QGps0vb2F^gd3a_3^ZuGMTo*Rxm-^|JwKs&|=o@qV%^JI$<8L*zhH;ugQp(6Q*-1WD5ekY5ZsgJ+w=n7uQ6v$J(%~2hWvAR>d7DJE${}JnT6)B z7*GDS5O0dRCFX88w^vfr+kF{*y_K4t9?H(LSvj4QYY=-~< diff --git a/src/app.rs b/src/app.rs index c120222..88901f9 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2,12 +2,15 @@ mod functions; use functions::{ create_command_buffers, create_command_pool, create_framebuffers, create_instance, 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 ::anyhow::{anyhow, Result}; +use ::lazy_static::lazy_static; use ::log::*; +use ::nalgebra_glm as glm; +use ::std::mem::size_of; use ::thiserror::Error; use ::vulkanalia::loader::{LibloadingLoader, LIBRARY}; use ::vulkanalia::prelude::v1_0::*; @@ -63,6 +66,7 @@ impl App { create_pipeline(&device, &mut data)?; create_framebuffers(&device, &mut data)?; create_command_pool(&instance, &device, &mut data)?; + create_vertex_buffer(&instance, &device, &mut data)?; create_command_buffers(&device, &mut data)?; create_sync_objects(&device, &mut data)?; @@ -82,6 +86,9 @@ impl App { /// Here be Dragons pub unsafe fn destroy(&mut self) { self.destroy_swapchain(); + self.device.destroy_buffer(self.data.vertex_buffer, None); + self.device + .free_memory(self.data.vertex_buffer_memory, None); self.data .in_flight_fences @@ -248,6 +255,9 @@ pub struct AppData { framebuffers: Vec, // Command Pool command_pool: vk::CommandPool, + // Buffers + vertex_buffer: vk::Buffer, + vertex_buffer_memory: vk::DeviceMemory, // Command Buffers command_buffers: Vec, // 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::() 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::() as u32) + .build(); + + [pos, color] + } +} + +lazy_static! { + pub(crate) static ref VERTICES: Vec = 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)), + ]; +} diff --git a/src/app/functions.rs b/src/app/functions.rs index 9474c15..ce21a77 100644 --- a/src/app/functions.rs +++ b/src/app/functions.rs @@ -6,6 +6,7 @@ use ::log::*; use ::std::collections::HashSet; use ::std::ffi::CStr; use ::std::os::raw::c_void; +use ::std::ptr::copy_nonoverlapping as memcpy; use ::vulkanalia::prelude::v1_0::*; use ::vulkanalia::window as vk_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) .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() .topology(vk::PrimitiveTopology::TRIANGLE_LIST) @@ -618,6 +623,7 @@ pub(super) unsafe fn create_command_buffers(device: &Device, data: &mut AppData) vk::PipelineBindPoint::GRAPHICS, 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_end_render_pass(*command_buffer); @@ -649,3 +655,59 @@ pub(super) unsafe fn create_sync_objects(device: &Device, data: &mut AppData) -> 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::() * 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 { + 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.")) +}