169: Issue 142 r=MaikKlein a=coolmedium

Hey here is an attempt to address #142 .  

I have used builders in cases where a builder method accepts a structure that sets more than one struct field (e.g. fields like `x_count` and `p_to_some_x`).  Otherwise I have usually used `.. Default::default()` when doing so would save typing. 

If there is a preferred way to approach this I'm happy to make any changes.

Also, for creating shader modules I have added `examples::bytes_to_u32_vec` to convert the current shader code into a format suitable for passing to the `vk::ShaderModuleCreateInfo::code`.  It  uses `std::mem::transmute` and is based on the code for `u32::from_ne_bytes` in nightly. I have only tested this on Linux. 



Co-authored-by: colin <colin@coolmedium.games>
This commit is contained in:
bors[bot] 2018-12-09 21:02:11 +00:00
commit 25df12f1ce
3 changed files with 385 additions and 716 deletions

View file

@ -5,11 +5,9 @@ extern crate image;
use std::default::Default; use std::default::Default;
use std::ffi::CString; use std::ffi::CString;
use std::fs::File; use std::fs::File;
use std::io::Read;
use std::mem::{self, align_of}; use std::mem::{self, align_of};
use std::os::raw::c_void; use std::os::raw::c_void;
use std::path::Path; use std::path::Path;
use std::ptr;
use ash::util::*; use ash::util::*;
use ash::vk; use ash::vk;
@ -33,91 +31,70 @@ pub struct Vector3 {
fn main() { fn main() {
unsafe { unsafe {
let base = ExampleBase::new(1920, 1080); let base = ExampleBase::new(1920, 1080);
let renderpass_attachments = [ let renderpass_attachments = [
vk::AttachmentDescription { vk::AttachmentDescription {
format: base.surface_format.format, format: base.surface_format.format,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1, samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR, load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::STORE, store_op: vk::AttachmentStoreOp::STORE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::UNDEFINED,
final_layout: vk::ImageLayout::PRESENT_SRC_KHR, final_layout: vk::ImageLayout::PRESENT_SRC_KHR,
..Default::default()
}, },
vk::AttachmentDescription { vk::AttachmentDescription {
format: vk::Format::D16_UNORM, format: vk::Format::D16_UNORM,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1, samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR, load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::DONT_CARE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, initial_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
..Default::default()
}, },
]; ];
let color_attachment_ref = vk::AttachmentReference { let color_attachment_refs = [vk::AttachmentReference {
attachment: 0, attachment: 0,
layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
}; }];
let depth_attachment_ref = vk::AttachmentReference { let depth_attachment_ref = vk::AttachmentReference {
attachment: 1, attachment: 1,
layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
}; };
let dependency = vk::SubpassDependency { let dependencies = [vk::SubpassDependency {
dependency_flags: Default::default(),
src_subpass: vk::SUBPASS_EXTERNAL, src_subpass: vk::SUBPASS_EXTERNAL,
dst_subpass: Default::default(),
src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
src_access_mask: Default::default(),
dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ
| vk::AccessFlags::COLOR_ATTACHMENT_WRITE, | vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
}; ..Default::default()
let subpass = vk::SubpassDescription { }];
color_attachment_count: 1,
p_color_attachments: &color_attachment_ref, let subpasses = [vk::SubpassDescription::builder()
p_depth_stencil_attachment: &depth_attachment_ref, .color_attachments(&color_attachment_refs)
flags: Default::default(), .depth_stencil_attachment(&depth_attachment_ref)
pipeline_bind_point: vk::PipelineBindPoint::GRAPHICS, .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
input_attachment_count: 0, .build()];
p_input_attachments: ptr::null(),
p_resolve_attachments: ptr::null(), let renderpass_create_info = vk::RenderPassCreateInfo::builder()
preserve_attachment_count: 0, .attachments(&renderpass_attachments)
p_preserve_attachments: ptr::null(), .subpasses(&subpasses)
}; .dependencies(&dependencies);
let renderpass_create_info = vk::RenderPassCreateInfo {
s_type: vk::StructureType::RENDER_PASS_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
attachment_count: renderpass_attachments.len() as u32,
p_attachments: renderpass_attachments.as_ptr(),
subpass_count: 1,
p_subpasses: &subpass,
dependency_count: 1,
p_dependencies: &dependency,
};
let renderpass = base let renderpass = base
.device .device
.create_render_pass(&renderpass_create_info, None) .create_render_pass(&renderpass_create_info, None)
.unwrap(); .unwrap();
let framebuffers: Vec<vk::Framebuffer> = base let framebuffers: Vec<vk::Framebuffer> = base
.present_image_views .present_image_views
.iter() .iter()
.map(|&present_image_view| { .map(|&present_image_view| {
let framebuffer_attachments = [present_image_view, base.depth_image_view]; let framebuffer_attachments = [present_image_view, base.depth_image_view];
let frame_buffer_create_info = vk::FramebufferCreateInfo { let frame_buffer_create_info = vk::FramebufferCreateInfo::builder()
s_type: vk::StructureType::FRAMEBUFFER_CREATE_INFO, .render_pass(renderpass)
p_next: ptr::null(), .attachments(&framebuffer_attachments)
flags: Default::default(), .width(base.surface_resolution.width)
render_pass: renderpass, .height(base.surface_resolution.height)
attachment_count: framebuffer_attachments.len() as u32, .layers(1);
p_attachments: framebuffer_attachments.as_ptr(),
width: base.surface_resolution.width,
height: base.surface_resolution.height,
layers: 1,
};
base.device base.device
.create_framebuffer(&frame_buffer_create_info, None) .create_framebuffer(&frame_buffer_create_info, None)
.unwrap() .unwrap()
@ -125,14 +102,10 @@ fn main() {
.collect(); .collect();
let index_buffer_data = [0u32, 1, 2, 2, 3, 0]; let index_buffer_data = [0u32, 1, 2, 2, 3, 0];
let index_buffer_info = vk::BufferCreateInfo { let index_buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: std::mem::size_of_val(&index_buffer_data) as u64, size: std::mem::size_of_val(&index_buffer_data) as u64,
usage: vk::BufferUsageFlags::INDEX_BUFFER, usage: vk::BufferUsageFlags::INDEX_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
}; };
let index_buffer = base.device.create_buffer(&index_buffer_info, None).unwrap(); let index_buffer = base.device.create_buffer(&index_buffer_info, None).unwrap();
let index_buffer_memory_req = base.device.get_buffer_memory_requirements(index_buffer); let index_buffer_memory_req = base.device.get_buffer_memory_requirements(index_buffer);
@ -143,10 +116,9 @@ fn main() {
) )
.expect("Unable to find suitable memorytype for the index buffer."); .expect("Unable to find suitable memorytype for the index buffer.");
let index_allocate_info = vk::MemoryAllocateInfo { let index_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: index_buffer_memory_req.size, allocation_size: index_buffer_memory_req.size,
memory_type_index: index_buffer_memory_index, memory_type_index: index_buffer_memory_index,
..Default::default()
}; };
let index_buffer_memory = base let index_buffer_memory = base
.device .device
@ -191,14 +163,10 @@ fn main() {
}, },
]; ];
let vertex_input_buffer_info = vk::BufferCreateInfo { let vertex_input_buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: std::mem::size_of_val(&vertices) as u64, size: std::mem::size_of_val(&vertices) as u64,
usage: vk::BufferUsageFlags::VERTEX_BUFFER, usage: vk::BufferUsageFlags::VERTEX_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
}; };
let vertex_input_buffer = base let vertex_input_buffer = base
.device .device
@ -215,15 +183,15 @@ fn main() {
.expect("Unable to find suitable memorytype for the vertex buffer."); .expect("Unable to find suitable memorytype for the vertex buffer.");
let vertex_buffer_allocate_info = vk::MemoryAllocateInfo { let vertex_buffer_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: vertex_input_buffer_memory_req.size, allocation_size: vertex_input_buffer_memory_req.size,
memory_type_index: vertex_input_buffer_memory_index, memory_type_index: vertex_input_buffer_memory_index,
..Default::default()
}; };
let vertex_input_buffer_memory = base let vertex_input_buffer_memory = base
.device .device
.allocate_memory(&vertex_buffer_allocate_info, None) .allocate_memory(&vertex_buffer_allocate_info, None)
.unwrap(); .unwrap();
let vert_ptr = base let vert_ptr = base
.device .device
.map_memory( .map_memory(
@ -251,14 +219,10 @@ fn main() {
_pad: 0.0, _pad: 0.0,
}; };
let uniform_color_buffer_info = vk::BufferCreateInfo { let uniform_color_buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: std::mem::size_of_val(&uniform_color_buffer_data) as u64, size: std::mem::size_of_val(&uniform_color_buffer_data) as u64,
usage: vk::BufferUsageFlags::UNIFORM_BUFFER, usage: vk::BufferUsageFlags::UNIFORM_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
}; };
let uniform_color_buffer = base let uniform_color_buffer = base
.device .device
@ -275,10 +239,9 @@ fn main() {
.expect("Unable to find suitable memorytype for the vertex buffer."); .expect("Unable to find suitable memorytype for the vertex buffer.");
let uniform_color_buffer_allocate_info = vk::MemoryAllocateInfo { let uniform_color_buffer_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: uniform_color_buffer_memory_req.size, allocation_size: uniform_color_buffer_memory_req.size,
memory_type_index: uniform_color_buffer_memory_index, memory_type_index: uniform_color_buffer_memory_index,
..Default::default()
}; };
let uniform_color_buffer_memory = base let uniform_color_buffer_memory = base
.device .device
@ -308,14 +271,10 @@ fn main() {
let image_dimensions = image.dimensions(); let image_dimensions = image.dimensions();
let image_data = image.into_raw(); let image_data = image.into_raw();
let image_buffer_info = vk::BufferCreateInfo { let image_buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: (std::mem::size_of::<u8>() * image_data.len()) as u64, size: (std::mem::size_of::<u8>() * image_data.len()) as u64,
usage: vk::BufferUsageFlags::TRANSFER_SRC, usage: vk::BufferUsageFlags::TRANSFER_SRC,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
}; };
let image_buffer = base.device.create_buffer(&image_buffer_info, None).unwrap(); let image_buffer = base.device.create_buffer(&image_buffer_info, None).unwrap();
let image_buffer_memory_req = base.device.get_buffer_memory_requirements(image_buffer); let image_buffer_memory_req = base.device.get_buffer_memory_requirements(image_buffer);
@ -327,10 +286,9 @@ fn main() {
.expect("Unable to find suitable memorytype for the vertex buffer."); .expect("Unable to find suitable memorytype for the vertex buffer.");
let image_buffer_allocate_info = vk::MemoryAllocateInfo { let image_buffer_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: image_buffer_memory_req.size, allocation_size: image_buffer_memory_req.size,
memory_type_index: image_buffer_memory_index, memory_type_index: image_buffer_memory_index,
..Default::default()
}; };
let image_buffer_memory = base let image_buffer_memory = base
.device .device
@ -357,9 +315,6 @@ fn main() {
.unwrap(); .unwrap();
let texture_create_info = vk::ImageCreateInfo { let texture_create_info = vk::ImageCreateInfo {
s_type: vk::StructureType::IMAGE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
image_type: vk::ImageType::TYPE_2D, image_type: vk::ImageType::TYPE_2D,
format: vk::Format::R8G8B8A8_UNORM, format: vk::Format::R8G8B8A8_UNORM,
extent: vk::Extent3D { extent: vk::Extent3D {
@ -373,9 +328,7 @@ fn main() {
tiling: vk::ImageTiling::OPTIMAL, tiling: vk::ImageTiling::OPTIMAL,
usage: vk::ImageUsageFlags::TRANSFER_DST | vk::ImageUsageFlags::SAMPLED, usage: vk::ImageUsageFlags::TRANSFER_DST | vk::ImageUsageFlags::SAMPLED,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
initial_layout: vk::ImageLayout::UNDEFINED,
}; };
let texture_image = base let texture_image = base
.device .device
@ -390,10 +343,9 @@ fn main() {
.expect("Unable to find suitable memory index for depth image."); .expect("Unable to find suitable memory index for depth image.");
let texture_allocate_info = vk::MemoryAllocateInfo { let texture_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: texture_memory_req.size, allocation_size: texture_memory_req.size,
memory_type_index: texture_memory_index, memory_type_index: texture_memory_index,
..Default::default()
}; };
let texture_memory = base let texture_memory = base
.device .device
@ -407,27 +359,21 @@ fn main() {
&base.device, &base.device,
base.setup_command_buffer, base.setup_command_buffer,
base.present_queue, base.present_queue,
&[vk::PipelineStageFlags::TOP_OF_PIPE], &[],
&[], &[],
&[], &[],
|device, texture_command_buffer| { |device, texture_command_buffer| {
let texture_barrier = vk::ImageMemoryBarrier { let texture_barrier = vk::ImageMemoryBarrier {
s_type: vk::StructureType::IMAGE_MEMORY_BARRIER,
p_next: ptr::null(),
src_access_mask: Default::default(),
dst_access_mask: vk::AccessFlags::TRANSFER_WRITE, dst_access_mask: vk::AccessFlags::TRANSFER_WRITE,
old_layout: vk::ImageLayout::UNDEFINED,
new_layout: vk::ImageLayout::TRANSFER_DST_OPTIMAL, new_layout: vk::ImageLayout::TRANSFER_DST_OPTIMAL,
src_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
image: texture_image, image: texture_image,
subresource_range: vk::ImageSubresourceRange { subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR, aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1, level_count: 1,
base_array_layer: 0,
layer_count: 1, layer_count: 1,
..Default::default()
}, },
..Default::default()
}; };
device.cmd_pipeline_barrier( device.cmd_pipeline_barrier(
texture_command_buffer, texture_command_buffer,
@ -438,48 +384,39 @@ fn main() {
&[], &[],
&[texture_barrier], &[texture_barrier],
); );
let buffer_copy_regions = [vk::BufferImageCopy { let buffer_copy_regions = vk::BufferImageCopy::builder()
image_subresource: vk::ImageSubresourceLayers { .image_subresource(
aspect_mask: vk::ImageAspectFlags::COLOR, vk::ImageSubresourceLayers::builder()
mip_level: 0, .aspect_mask(vk::ImageAspectFlags::COLOR)
base_array_layer: 0, .layer_count(1)
layer_count: 1, .build(),
}, )
image_extent: vk::Extent3D { .image_extent(vk::Extent3D {
width: image_dimensions.0, width: image_dimensions.0,
height: image_dimensions.1, height: image_dimensions.1,
depth: 1, depth: 1,
}, });
buffer_offset: 0,
// FIX ME
buffer_image_height: 0,
buffer_row_length: 0,
image_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
}];
device.cmd_copy_buffer_to_image( device.cmd_copy_buffer_to_image(
texture_command_buffer, texture_command_buffer,
image_buffer, image_buffer,
texture_image, texture_image,
vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&buffer_copy_regions, &[buffer_copy_regions.build()],
); );
let texture_barrier_end = vk::ImageMemoryBarrier { let texture_barrier_end = vk::ImageMemoryBarrier {
s_type: vk::StructureType::IMAGE_MEMORY_BARRIER,
p_next: ptr::null(),
src_access_mask: vk::AccessFlags::TRANSFER_WRITE, src_access_mask: vk::AccessFlags::TRANSFER_WRITE,
dst_access_mask: vk::AccessFlags::SHADER_READ, dst_access_mask: vk::AccessFlags::SHADER_READ,
old_layout: vk::ImageLayout::TRANSFER_DST_OPTIMAL, old_layout: vk::ImageLayout::TRANSFER_DST_OPTIMAL,
new_layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, new_layout: vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
src_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED,
image: texture_image, image: texture_image,
subresource_range: vk::ImageSubresourceRange { subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR, aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1, level_count: 1,
base_array_layer: 0,
layer_count: 1, layer_count: 1,
..Default::default()
}, },
..Default::default()
}; };
device.cmd_pipeline_barrier( device.cmd_pipeline_barrier(
texture_command_buffer, texture_command_buffer,
@ -494,32 +431,21 @@ fn main() {
); );
let sampler_info = vk::SamplerCreateInfo { let sampler_info = vk::SamplerCreateInfo {
s_type: vk::StructureType::SAMPLER_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
mag_filter: vk::Filter::LINEAR, mag_filter: vk::Filter::LINEAR,
min_filter: vk::Filter::LINEAR, min_filter: vk::Filter::LINEAR,
mipmap_mode: vk::SamplerMipmapMode::LINEAR, mipmap_mode: vk::SamplerMipmapMode::LINEAR,
address_mode_u: vk::SamplerAddressMode::MIRRORED_REPEAT, address_mode_u: vk::SamplerAddressMode::MIRRORED_REPEAT,
address_mode_v: vk::SamplerAddressMode::MIRRORED_REPEAT, address_mode_v: vk::SamplerAddressMode::MIRRORED_REPEAT,
address_mode_w: vk::SamplerAddressMode::MIRRORED_REPEAT, address_mode_w: vk::SamplerAddressMode::MIRRORED_REPEAT,
mip_lod_bias: 0.0,
min_lod: 0.0,
max_lod: 0.0,
anisotropy_enable: 0,
max_anisotropy: 1.0, max_anisotropy: 1.0,
border_color: vk::BorderColor::FLOAT_OPAQUE_WHITE, border_color: vk::BorderColor::FLOAT_OPAQUE_WHITE,
compare_enable: 0,
compare_op: vk::CompareOp::NEVER, compare_op: vk::CompareOp::NEVER,
unnormalized_coordinates: 0, ..Default::default()
}; };
let sampler = base.device.create_sampler(&sampler_info, None).unwrap(); let sampler = base.device.create_sampler(&sampler_info, None).unwrap();
let tex_image_view_info = vk::ImageViewCreateInfo { let tex_image_view_info = vk::ImageViewCreateInfo {
s_type: vk::StructureType::IMAGE_VIEW_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
view_type: vk::ImageViewType::TYPE_2D, view_type: vk::ImageViewType::TYPE_2D,
format: texture_create_info.format, format: texture_create_info.format,
components: vk::ComponentMapping { components: vk::ComponentMapping {
@ -530,12 +456,12 @@ fn main() {
}, },
subresource_range: vk::ImageSubresourceRange { subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR, aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1, level_count: 1,
base_array_layer: 0,
layer_count: 1, layer_count: 1,
..Default::default()
}, },
image: texture_image, image: texture_image,
..Default::default()
}; };
let tex_image_view = base let tex_image_view = base
.device .device
@ -551,53 +477,40 @@ fn main() {
descriptor_count: 1, descriptor_count: 1,
}, },
]; ];
let descriptor_pool_info = vk::DescriptorPoolCreateInfo { let descriptor_pool_info = vk::DescriptorPoolCreateInfo::builder()
s_type: vk::StructureType::DESCRIPTOR_POOL_CREATE_INFO, .pool_sizes(&descriptor_sizes)
p_next: ptr::null(), .max_sets(1);
flags: Default::default(),
pool_size_count: descriptor_sizes.len() as u32,
p_pool_sizes: descriptor_sizes.as_ptr(),
max_sets: 1,
};
let descriptor_pool = base let descriptor_pool = base
.device .device
.create_descriptor_pool(&descriptor_pool_info, None) .create_descriptor_pool(&descriptor_pool_info, None)
.unwrap(); .unwrap();
let desc_layout_bindings = [ let desc_layout_bindings = [
vk::DescriptorSetLayoutBinding { vk::DescriptorSetLayoutBinding {
binding: 0,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER, descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
descriptor_count: 1, descriptor_count: 1,
stage_flags: vk::ShaderStageFlags::FRAGMENT, stage_flags: vk::ShaderStageFlags::FRAGMENT,
p_immutable_samplers: ptr::null(), ..Default::default()
}, },
vk::DescriptorSetLayoutBinding { vk::DescriptorSetLayoutBinding {
binding: 1, binding: 1,
descriptor_type: vk::DescriptorType::COMBINED_IMAGE_SAMPLER, descriptor_type: vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
descriptor_count: 1, descriptor_count: 1,
stage_flags: vk::ShaderStageFlags::FRAGMENT, stage_flags: vk::ShaderStageFlags::FRAGMENT,
p_immutable_samplers: ptr::null(), ..Default::default()
}, },
]; ];
let descriptor_info = vk::DescriptorSetLayoutCreateInfo { let descriptor_info =
s_type: vk::StructureType::DESCRIPTOR_SET_LAYOUT_CREATE_INFO, vk::DescriptorSetLayoutCreateInfo::builder().bindings(&desc_layout_bindings);
p_next: ptr::null(),
flags: Default::default(),
binding_count: desc_layout_bindings.len() as u32,
p_bindings: desc_layout_bindings.as_ptr(),
};
let desc_set_layouts = [base let desc_set_layouts = [base
.device .device
.create_descriptor_set_layout(&descriptor_info, None) .create_descriptor_set_layout(&descriptor_info, None)
.unwrap()]; .unwrap()];
let desc_alloc_info = vk::DescriptorSetAllocateInfo {
s_type: vk::StructureType::DESCRIPTOR_SET_ALLOCATE_INFO, let desc_alloc_info = vk::DescriptorSetAllocateInfo::builder()
p_next: ptr::null(), .descriptor_pool(descriptor_pool)
descriptor_pool: descriptor_pool, .set_layouts(&desc_set_layouts);
descriptor_set_count: desc_set_layouts.len() as u32,
p_set_layouts: desc_set_layouts.as_ptr(),
};
let descriptor_sets = base let descriptor_sets = base
.device .device
.allocate_descriptor_sets(&desc_alloc_info) .allocate_descriptor_sets(&desc_alloc_info)
@ -617,56 +530,36 @@ fn main() {
let write_desc_sets = [ let write_desc_sets = [
vk::WriteDescriptorSet { vk::WriteDescriptorSet {
s_type: vk::StructureType::WRITE_DESCRIPTOR_SET,
p_next: ptr::null(),
dst_set: descriptor_sets[0], dst_set: descriptor_sets[0],
dst_binding: 0,
dst_array_element: 0,
descriptor_count: 1, descriptor_count: 1,
descriptor_type: vk::DescriptorType::UNIFORM_BUFFER, descriptor_type: vk::DescriptorType::UNIFORM_BUFFER,
p_image_info: ptr::null(),
p_buffer_info: &uniform_color_buffer_descriptor, p_buffer_info: &uniform_color_buffer_descriptor,
p_texel_buffer_view: ptr::null(), ..Default::default()
}, },
vk::WriteDescriptorSet { vk::WriteDescriptorSet {
s_type: vk::StructureType::WRITE_DESCRIPTOR_SET,
p_next: ptr::null(),
dst_set: descriptor_sets[0], dst_set: descriptor_sets[0],
dst_binding: 1, dst_binding: 1,
dst_array_element: 0,
descriptor_count: 1, descriptor_count: 1,
descriptor_type: vk::DescriptorType::COMBINED_IMAGE_SAMPLER, descriptor_type: vk::DescriptorType::COMBINED_IMAGE_SAMPLER,
p_image_info: &tex_descriptor, p_image_info: &tex_descriptor,
p_buffer_info: ptr::null(), ..Default::default()
p_texel_buffer_view: ptr::null(),
}, },
]; ];
base.device.update_descriptor_sets(&write_desc_sets, &[]); base.device.update_descriptor_sets(&write_desc_sets, &[]);
let vertex_spv_file = let mut vertex_spv_file =
File::open(Path::new("shader/texture/vert.spv")).expect("Could not find vert.spv."); File::open(Path::new("shader/texture/vert.spv")).expect("Could not find vert.spv.");
let frag_spv_file = let mut frag_spv_file =
File::open(Path::new("shader/texture/frag.spv")).expect("Could not find frag.spv."); File::open(Path::new("shader/texture/frag.spv")).expect("Could not find frag.spv.");
let vertex_bytes: Vec<u8> = vertex_spv_file let vertex_code =
.bytes() read_spv(&mut vertex_spv_file).expect("Failed to read vertex shader spv file");
.filter_map(|byte| byte.ok()) let vertex_shader_info = vk::ShaderModuleCreateInfo::builder().code(&vertex_code);
.collect();
let vertex_shader_info = vk::ShaderModuleCreateInfo { let frag_code =
s_type: vk::StructureType::SHADER_MODULE_CREATE_INFO, read_spv(&mut frag_spv_file).expect("Failed to read fragment shader spv file");
p_next: ptr::null(), let frag_shader_info = vk::ShaderModuleCreateInfo::builder().code(&frag_code);
flags: Default::default(),
code_size: vertex_bytes.len(),
p_code: vertex_bytes.as_ptr() as *const u32,
};
let frag_bytes: Vec<u8> = frag_spv_file.bytes().filter_map(|byte| byte.ok()).collect();
let frag_shader_info = vk::ShaderModuleCreateInfo {
s_type: vk::StructureType::SHADER_MODULE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
code_size: frag_bytes.len(),
p_code: frag_bytes.as_ptr() as *const u32,
};
let vertex_shader_module = base let vertex_shader_module = base
.device .device
.create_shader_module(&vertex_shader_info, None) .create_shader_module(&vertex_shader_info, None)
@ -677,15 +570,8 @@ fn main() {
.create_shader_module(&frag_shader_info, None) .create_shader_module(&frag_shader_info, None)
.expect("Fragment shader module error"); .expect("Fragment shader module error");
let layout_create_info = vk::PipelineLayoutCreateInfo { let layout_create_info =
s_type: vk::StructureType::PIPELINE_LAYOUT_CREATE_INFO, vk::PipelineLayoutCreateInfo::builder().set_layouts(&desc_set_layouts);
p_next: ptr::null(),
flags: Default::default(),
set_layout_count: desc_set_layouts.len() as u32,
p_set_layouts: desc_set_layouts.as_ptr(),
push_constant_range_count: 0,
p_push_constant_ranges: ptr::null(),
};
let pipeline_layout = base let pipeline_layout = base
.device .device
@ -695,22 +581,16 @@ fn main() {
let shader_entry_name = CString::new("main").unwrap(); let shader_entry_name = CString::new("main").unwrap();
let shader_stage_create_infos = [ let shader_stage_create_infos = [
vk::PipelineShaderStageCreateInfo { vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
module: vertex_shader_module, module: vertex_shader_module,
p_name: shader_entry_name.as_ptr(), p_name: shader_entry_name.as_ptr(),
p_specialization_info: ptr::null(),
stage: vk::ShaderStageFlags::VERTEX, stage: vk::ShaderStageFlags::VERTEX,
..Default::default()
}, },
vk::PipelineShaderStageCreateInfo { vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
module: fragment_shader_module, module: fragment_shader_module,
p_name: shader_entry_name.as_ptr(), p_name: shader_entry_name.as_ptr(),
p_specialization_info: ptr::null(),
stage: vk::ShaderStageFlags::FRAGMENT, stage: vk::ShaderStageFlags::FRAGMENT,
..Default::default()
}, },
]; ];
let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription { let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription {
@ -732,21 +612,13 @@ fn main() {
offset: offset_of!(Vertex, uv) as u32, offset: offset_of!(Vertex, uv) as u32,
}, },
]; ];
let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo { let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo::builder()
s_type: vk::StructureType::PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, .vertex_attribute_descriptions(&vertex_input_attribute_descriptions)
p_next: ptr::null(), .vertex_binding_descriptions(&vertex_input_binding_descriptions);
flags: Default::default(),
vertex_attribute_description_count: vertex_input_attribute_descriptions.len() as u32,
p_vertex_attribute_descriptions: vertex_input_attribute_descriptions.as_ptr(),
vertex_binding_description_count: vertex_input_binding_descriptions.len() as u32,
p_vertex_binding_descriptions: vertex_input_binding_descriptions.as_ptr(),
};
let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo { let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo {
s_type: vk::StructureType::PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
primitive_restart_enable: 0,
topology: vk::PrimitiveTopology::TRIANGLE_LIST, topology: vk::PrimitiveTopology::TRIANGLE_LIST,
..Default::default()
}; };
let viewports = [vk::Viewport { let viewports = [vk::Viewport {
x: 0.0, x: 0.0,
@ -757,67 +629,40 @@ fn main() {
max_depth: 1.0, max_depth: 1.0,
}]; }];
let scissors = [vk::Rect2D { let scissors = [vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 },
extent: base.surface_resolution.clone(), extent: base.surface_resolution.clone(),
..Default::default()
}]; }];
let viewport_state_info = vk::PipelineViewportStateCreateInfo { let viewport_state_info = vk::PipelineViewportStateCreateInfo::builder()
s_type: vk::StructureType::PIPELINE_VIEWPORT_STATE_CREATE_INFO, .scissors(&scissors)
p_next: ptr::null(), .viewports(&viewports);
flags: Default::default(),
scissor_count: scissors.len() as u32,
p_scissors: scissors.as_ptr(),
viewport_count: viewports.len() as u32,
p_viewports: viewports.as_ptr(),
};
let rasterization_info = vk::PipelineRasterizationStateCreateInfo { let rasterization_info = vk::PipelineRasterizationStateCreateInfo {
s_type: vk::StructureType::PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
cull_mode: vk::CullModeFlags::NONE,
depth_bias_clamp: 0.0,
depth_bias_constant_factor: 0.0,
depth_bias_enable: 0,
depth_bias_slope_factor: 0.0,
depth_clamp_enable: 0,
front_face: vk::FrontFace::COUNTER_CLOCKWISE, front_face: vk::FrontFace::COUNTER_CLOCKWISE,
line_width: 1.0, line_width: 1.0,
polygon_mode: vk::PolygonMode::FILL, polygon_mode: vk::PolygonMode::FILL,
rasterizer_discard_enable: 0, ..Default::default()
};
let multisample_state_info = vk::PipelineMultisampleStateCreateInfo {
s_type: vk::StructureType::PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
rasterization_samples: vk::SampleCountFlags::TYPE_1,
sample_shading_enable: 0,
min_sample_shading: 0.0,
p_sample_mask: ptr::null(),
alpha_to_one_enable: 0,
alpha_to_coverage_enable: 0,
}; };
let multisample_state_info = vk::PipelineMultisampleStateCreateInfo::builder()
.rasterization_samples(vk::SampleCountFlags::TYPE_1);
let noop_stencil_state = vk::StencilOpState { let noop_stencil_state = vk::StencilOpState {
fail_op: vk::StencilOp::KEEP, fail_op: vk::StencilOp::KEEP,
pass_op: vk::StencilOp::KEEP, pass_op: vk::StencilOp::KEEP,
depth_fail_op: vk::StencilOp::KEEP, depth_fail_op: vk::StencilOp::KEEP,
compare_op: vk::CompareOp::ALWAYS, compare_op: vk::CompareOp::ALWAYS,
compare_mask: 0, ..Default::default()
write_mask: 0,
reference: 0,
}; };
let depth_state_info = vk::PipelineDepthStencilStateCreateInfo { let depth_state_info = vk::PipelineDepthStencilStateCreateInfo {
s_type: vk::StructureType::PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
depth_test_enable: 1, depth_test_enable: 1,
depth_write_enable: 1, depth_write_enable: 1,
depth_compare_op: vk::CompareOp::LESS_OR_EQUAL, depth_compare_op: vk::CompareOp::LESS_OR_EQUAL,
depth_bounds_test_enable: 0,
stencil_test_enable: 0,
front: noop_stencil_state.clone(), front: noop_stencil_state.clone(),
back: noop_stencil_state.clone(), back: noop_stencil_state.clone(),
max_depth_bounds: 1.0, max_depth_bounds: 1.0,
min_depth_bounds: 0.0, ..Default::default()
}; };
let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState { let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState {
blend_enable: 0, blend_enable: 0,
src_color_blend_factor: vk::BlendFactor::SRC_COLOR, src_color_blend_factor: vk::BlendFactor::SRC_COLOR,
@ -828,48 +673,34 @@ fn main() {
alpha_blend_op: vk::BlendOp::ADD, alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: vk::ColorComponentFlags::all(), color_write_mask: vk::ColorComponentFlags::all(),
}]; }];
let color_blend_state = vk::PipelineColorBlendStateCreateInfo { let color_blend_state = vk::PipelineColorBlendStateCreateInfo::builder()
s_type: vk::StructureType::PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .logic_op(vk::LogicOp::CLEAR)
p_next: ptr::null(), .attachments(&color_blend_attachment_states);
flags: Default::default(),
logic_op_enable: 0,
logic_op: vk::LogicOp::CLEAR,
attachment_count: color_blend_attachment_states.len() as u32,
p_attachments: color_blend_attachment_states.as_ptr(),
blend_constants: [0.0, 0.0, 0.0, 0.0],
};
let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
let dynamic_state_info = vk::PipelineDynamicStateCreateInfo { let dynamic_state_info =
s_type: vk::StructureType::PIPELINE_DYNAMIC_STATE_CREATE_INFO, vk::PipelineDynamicStateCreateInfo::builder().dynamic_states(&dynamic_state);
p_next: ptr::null(),
flags: Default::default(), let graphic_pipeline_infos = vk::GraphicsPipelineCreateInfo::builder()
dynamic_state_count: dynamic_state.len() as u32, .stages(&shader_stage_create_infos)
p_dynamic_states: dynamic_state.as_ptr(), .vertex_input_state(&vertex_input_state_info)
}; .input_assembly_state(&vertex_input_assembly_state_info)
let graphic_pipeline_info = vk::GraphicsPipelineCreateInfo { .viewport_state(&viewport_state_info)
s_type: vk::StructureType::GRAPHICS_PIPELINE_CREATE_INFO, .rasterization_state(&rasterization_info)
p_next: ptr::null(), .multisample_state(&multisample_state_info)
flags: vk::PipelineCreateFlags::empty(), .depth_stencil_state(&depth_state_info)
stage_count: shader_stage_create_infos.len() as u32, .color_blend_state(&color_blend_state)
p_stages: shader_stage_create_infos.as_ptr(), .dynamic_state(&dynamic_state_info)
p_vertex_input_state: &vertex_input_state_info, .layout(pipeline_layout)
p_input_assembly_state: &vertex_input_assembly_state_info, .render_pass(renderpass);
p_tessellation_state: ptr::null(),
p_viewport_state: &viewport_state_info,
p_rasterization_state: &rasterization_info,
p_multisample_state: &multisample_state_info,
p_depth_stencil_state: &depth_state_info,
p_color_blend_state: &color_blend_state,
p_dynamic_state: &dynamic_state_info,
layout: pipeline_layout,
render_pass: renderpass,
subpass: 0,
base_pipeline_handle: vk::Pipeline::null(),
base_pipeline_index: 0,
};
let graphics_pipelines = base let graphics_pipelines = base
.device .device
.create_graphics_pipelines(vk::PipelineCache::null(), &[graphic_pipeline_info], None) .create_graphics_pipelines(
vk::PipelineCache::null(),
&[graphic_pipeline_infos.build()],
None,
)
.unwrap(); .unwrap();
let graphic_pipeline = graphics_pipelines[0]; let graphic_pipeline = graphics_pipelines[0];
@ -898,18 +729,15 @@ fn main() {
}, },
]; ];
let render_pass_begin_info = vk::RenderPassBeginInfo { let render_pass_begin_info = vk::RenderPassBeginInfo::builder()
s_type: vk::StructureType::RENDER_PASS_BEGIN_INFO, .render_pass(renderpass)
p_next: ptr::null(), .framebuffer(framebuffers[present_index as usize])
render_pass: renderpass, .render_area(vk::Rect2D {
framebuffer: framebuffers[present_index as usize],
render_area: vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 }, offset: vk::Offset2D { x: 0, y: 0 },
extent: base.surface_resolution.clone(), extent: base.surface_resolution.clone(),
}, })
clear_value_count: clear_values.len() as u32, .clear_values(&clear_values);
p_clear_values: clear_values.as_ptr(),
};
record_submit_commandbuffer( record_submit_commandbuffer(
&base.device, &base.device,
base.draw_command_buffer, base.draw_command_buffer,
@ -965,14 +793,12 @@ fn main() {
); );
//let mut present_info_err = mem::uninitialized(); //let mut present_info_err = mem::uninitialized();
let present_info = vk::PresentInfoKHR { let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PRESENT_INFO_KHR,
p_next: ptr::null(),
wait_semaphore_count: 1, wait_semaphore_count: 1,
p_wait_semaphores: &base.rendering_complete_semaphore, p_wait_semaphores: &base.rendering_complete_semaphore,
swapchain_count: 1, swapchain_count: 1,
p_swapchains: &base.swapchain, p_swapchains: &base.swapchain,
p_image_indices: &present_index, p_image_indices: &present_index,
p_results: ptr::null_mut(), ..Default::default()
}; };
base.swapchain_loader base.swapchain_loader
.queue_present(base.present_queue, &present_info) .queue_present(base.present_queue, &present_info)

View file

@ -7,11 +7,9 @@ use examples::*;
use std::default::Default; use std::default::Default;
use std::ffi::CString; use std::ffi::CString;
use std::fs::File; use std::fs::File;
use std::io::Read;
use std::mem; use std::mem;
use std::mem::align_of; use std::mem::align_of;
use std::path::Path; use std::path::Path;
use std::ptr;
#[derive(Clone, Debug, Copy)] #[derive(Clone, Debug, Copy)]
struct Vertex { struct Vertex {
@ -25,104 +23,78 @@ fn main() {
let renderpass_attachments = [ let renderpass_attachments = [
vk::AttachmentDescription { vk::AttachmentDescription {
format: base.surface_format.format, format: base.surface_format.format,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1, samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR, load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::STORE, store_op: vk::AttachmentStoreOp::STORE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::UNDEFINED,
final_layout: vk::ImageLayout::PRESENT_SRC_KHR, final_layout: vk::ImageLayout::PRESENT_SRC_KHR,
..Default::default()
}, },
vk::AttachmentDescription { vk::AttachmentDescription {
format: vk::Format::D16_UNORM, format: vk::Format::D16_UNORM,
flags: vk::AttachmentDescriptionFlags::empty(),
samples: vk::SampleCountFlags::TYPE_1, samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR, load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::DONT_CARE,
stencil_load_op: vk::AttachmentLoadOp::DONT_CARE,
stencil_store_op: vk::AttachmentStoreOp::DONT_CARE,
initial_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, initial_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
..Default::default()
}, },
]; ];
let color_attachment_ref = vk::AttachmentReference { let color_attachment_refs = [vk::AttachmentReference {
attachment: 0, attachment: 0,
layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
}; }];
let depth_attachment_ref = vk::AttachmentReference { let depth_attachment_ref = vk::AttachmentReference {
attachment: 1, attachment: 1,
layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
}; };
let dependency = vk::SubpassDependency { let dependencies = [vk::SubpassDependency {
dependency_flags: Default::default(),
src_subpass: vk::SUBPASS_EXTERNAL, src_subpass: vk::SUBPASS_EXTERNAL,
dst_subpass: Default::default(),
src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
src_access_mask: Default::default(),
dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ
| vk::AccessFlags::COLOR_ATTACHMENT_WRITE, | vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT, dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
}; ..Default::default()
let subpass = vk::SubpassDescription { }];
color_attachment_count: 1,
p_color_attachments: &color_attachment_ref, let subpasses = [vk::SubpassDescription::builder()
p_depth_stencil_attachment: &depth_attachment_ref, .color_attachments(&color_attachment_refs)
flags: Default::default(), .depth_stencil_attachment(&depth_attachment_ref)
pipeline_bind_point: vk::PipelineBindPoint::GRAPHICS, .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
input_attachment_count: 0, .build()];
p_input_attachments: ptr::null(),
p_resolve_attachments: ptr::null(), let renderpass_create_info = vk::RenderPassCreateInfo::builder()
preserve_attachment_count: 0, .attachments(&renderpass_attachments)
p_preserve_attachments: ptr::null(), .subpasses(&subpasses)
}; .dependencies(&dependencies);
let renderpass_create_info = vk::RenderPassCreateInfo {
s_type: vk::StructureType::RENDER_PASS_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
attachment_count: renderpass_attachments.len() as u32,
p_attachments: renderpass_attachments.as_ptr(),
subpass_count: 1,
p_subpasses: &subpass,
dependency_count: 1,
p_dependencies: &dependency,
};
let renderpass = base let renderpass = base
.device .device
.create_render_pass(&renderpass_create_info, None) .create_render_pass(&renderpass_create_info, None)
.unwrap(); .unwrap();
let framebuffers: Vec<vk::Framebuffer> = base let framebuffers: Vec<vk::Framebuffer> = base
.present_image_views .present_image_views
.iter() .iter()
.map(|&present_image_view| { .map(|&present_image_view| {
let framebuffer_attachments = [present_image_view, base.depth_image_view]; let framebuffer_attachments = [present_image_view, base.depth_image_view];
let frame_buffer_create_info = vk::FramebufferCreateInfo { let frame_buffer_create_info = vk::FramebufferCreateInfo::builder()
s_type: vk::StructureType::FRAMEBUFFER_CREATE_INFO, .render_pass(renderpass)
p_next: ptr::null(), .attachments(&framebuffer_attachments)
flags: Default::default(), .width(base.surface_resolution.width)
render_pass: renderpass, .height(base.surface_resolution.height)
attachment_count: framebuffer_attachments.len() as u32, .layers(1);
p_attachments: framebuffer_attachments.as_ptr(),
width: base.surface_resolution.width,
height: base.surface_resolution.height,
layers: 1,
};
base.device base.device
.create_framebuffer(&frame_buffer_create_info, None) .create_framebuffer(&frame_buffer_create_info, None)
.unwrap() .unwrap()
}) })
.collect(); .collect();
let index_buffer_data = [0u32, 1, 2]; let index_buffer_data = [0u32, 1, 2];
let index_buffer_info = vk::BufferCreateInfo { let index_buffer_info = vk::BufferCreateInfo::builder()
s_type: vk::StructureType::BUFFER_CREATE_INFO, .size(std::mem::size_of_val(&index_buffer_data) as u64)
p_next: ptr::null(), .usage(vk::BufferUsageFlags::INDEX_BUFFER)
flags: vk::BufferCreateFlags::empty(), .sharing_mode(vk::SharingMode::EXCLUSIVE);
size: std::mem::size_of_val(&index_buffer_data) as u64,
usage: vk::BufferUsageFlags::INDEX_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0,
p_queue_family_indices: ptr::null(),
};
let index_buffer = base.device.create_buffer(&index_buffer_info, None).unwrap(); let index_buffer = base.device.create_buffer(&index_buffer_info, None).unwrap();
let index_buffer_memory_req = base.device.get_buffer_memory_requirements(index_buffer); let index_buffer_memory_req = base.device.get_buffer_memory_requirements(index_buffer);
let index_buffer_memory_index = find_memorytype_index( let index_buffer_memory_index = find_memorytype_index(
@ -131,11 +103,11 @@ fn main() {
vk::MemoryPropertyFlags::HOST_VISIBLE, vk::MemoryPropertyFlags::HOST_VISIBLE,
) )
.expect("Unable to find suitable memorytype for the index buffer."); .expect("Unable to find suitable memorytype for the index buffer.");
let index_allocate_info = vk::MemoryAllocateInfo { let index_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: index_buffer_memory_req.size, allocation_size: index_buffer_memory_req.size,
memory_type_index: index_buffer_memory_index, memory_type_index: index_buffer_memory_index,
..Default::default()
}; };
let index_buffer_memory = base let index_buffer_memory = base
.device .device
@ -162,22 +134,21 @@ fn main() {
.unwrap(); .unwrap();
let vertex_input_buffer_info = vk::BufferCreateInfo { let vertex_input_buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: 3 * std::mem::size_of::<Vertex>() as u64, size: 3 * std::mem::size_of::<Vertex>() as u64,
usage: vk::BufferUsageFlags::VERTEX_BUFFER, usage: vk::BufferUsageFlags::VERTEX_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE, sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0, ..Default::default()
p_queue_family_indices: ptr::null(),
}; };
let vertex_input_buffer = base let vertex_input_buffer = base
.device .device
.create_buffer(&vertex_input_buffer_info, None) .create_buffer(&vertex_input_buffer_info, None)
.unwrap(); .unwrap();
let vertex_input_buffer_memory_req = base let vertex_input_buffer_memory_req = base
.device .device
.get_buffer_memory_requirements(vertex_input_buffer); .get_buffer_memory_requirements(vertex_input_buffer);
let vertex_input_buffer_memory_index = find_memorytype_index( let vertex_input_buffer_memory_index = find_memorytype_index(
&vertex_input_buffer_memory_req, &vertex_input_buffer_memory_req,
&base.device_memory_properties, &base.device_memory_properties,
@ -186,15 +157,16 @@ fn main() {
.expect("Unable to find suitable memorytype for the vertex buffer."); .expect("Unable to find suitable memorytype for the vertex buffer.");
let vertex_buffer_allocate_info = vk::MemoryAllocateInfo { let vertex_buffer_allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: vertex_input_buffer_memory_req.size, allocation_size: vertex_input_buffer_memory_req.size,
memory_type_index: vertex_input_buffer_memory_index, memory_type_index: vertex_input_buffer_memory_index,
..Default::default()
}; };
let vertex_input_buffer_memory = base let vertex_input_buffer_memory = base
.device .device
.allocate_memory(&vertex_buffer_allocate_info, None) .allocate_memory(&vertex_buffer_allocate_info, None)
.unwrap(); .unwrap();
let vertices = [ let vertices = [
Vertex { Vertex {
pos: [-1.0, 1.0, 0.0, 1.0], pos: [-1.0, 1.0, 0.0, 1.0],
@ -209,6 +181,7 @@ fn main() {
color: [1.0, 0.0, 0.0, 1.0], color: [1.0, 0.0, 0.0, 1.0],
}, },
]; ];
let vert_ptr = base let vert_ptr = base
.device .device
.map_memory( .map_memory(
@ -218,6 +191,7 @@ fn main() {
vk::MemoryMapFlags::empty(), vk::MemoryMapFlags::empty(),
) )
.unwrap(); .unwrap();
let mut vert_align = Align::new( let mut vert_align = Align::new(
vert_ptr, vert_ptr,
align_of::<Vertex>() as u64, align_of::<Vertex>() as u64,
@ -228,30 +202,19 @@ fn main() {
base.device base.device
.bind_buffer_memory(vertex_input_buffer, vertex_input_buffer_memory, 0) .bind_buffer_memory(vertex_input_buffer, vertex_input_buffer_memory, 0)
.unwrap(); .unwrap();
let vertex_spv_file = let mut vertex_spv_file =
File::open(Path::new("shader/triangle/vert.spv")).expect("Could not find vert.spv."); File::open(Path::new("shader/triangle/vert.spv")).expect("Could not find vert.spv.");
let frag_spv_file = let mut frag_spv_file =
File::open(Path::new("shader/triangle/frag.spv")).expect("Could not find frag.spv."); File::open(Path::new("shader/triangle/frag.spv")).expect("Could not find frag.spv.");
let vertex_bytes: Vec<u8> = vertex_spv_file let vertex_code =
.bytes() read_spv(&mut vertex_spv_file).expect("Failed to read vertex shader spv file");
.filter_map(|byte| byte.ok()) let vertex_shader_info = vk::ShaderModuleCreateInfo::builder().code(&vertex_code);
.collect();
let vertex_shader_info = vk::ShaderModuleCreateInfo { let frag_code =
s_type: vk::StructureType::SHADER_MODULE_CREATE_INFO, read_spv(&mut frag_spv_file).expect("Failed to read fragment shader spv file");
p_next: ptr::null(), let frag_shader_info = vk::ShaderModuleCreateInfo::builder().code(&frag_code);
flags: Default::default(),
code_size: vertex_bytes.len(),
p_code: vertex_bytes.as_ptr() as *const u32,
};
let frag_bytes: Vec<u8> = frag_spv_file.bytes().filter_map(|byte| byte.ok()).collect();
let frag_shader_info = vk::ShaderModuleCreateInfo {
s_type: vk::StructureType::SHADER_MODULE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
code_size: frag_bytes.len(),
p_code: frag_bytes.as_ptr() as *const u32,
};
let vertex_shader_module = base let vertex_shader_module = base
.device .device
.create_shader_module(&vertex_shader_info, None) .create_shader_module(&vertex_shader_info, None)
@ -262,15 +225,7 @@ fn main() {
.create_shader_module(&frag_shader_info, None) .create_shader_module(&frag_shader_info, None)
.expect("Fragment shader module error"); .expect("Fragment shader module error");
let layout_create_info = vk::PipelineLayoutCreateInfo { let layout_create_info = vk::PipelineLayoutCreateInfo::default();
s_type: vk::StructureType::PIPELINE_LAYOUT_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
set_layout_count: 0,
p_set_layouts: ptr::null(),
push_constant_range_count: 0,
p_push_constant_ranges: ptr::null(),
};
let pipeline_layout = base let pipeline_layout = base
.device .device
@ -280,22 +235,17 @@ fn main() {
let shader_entry_name = CString::new("main").unwrap(); let shader_entry_name = CString::new("main").unwrap();
let shader_stage_create_infos = [ let shader_stage_create_infos = [
vk::PipelineShaderStageCreateInfo { vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
module: vertex_shader_module, module: vertex_shader_module,
p_name: shader_entry_name.as_ptr(), p_name: shader_entry_name.as_ptr(),
p_specialization_info: ptr::null(),
stage: vk::ShaderStageFlags::VERTEX, stage: vk::ShaderStageFlags::VERTEX,
..Default::default()
}, },
vk::PipelineShaderStageCreateInfo { vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO, s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
module: fragment_shader_module, module: fragment_shader_module,
p_name: shader_entry_name.as_ptr(), p_name: shader_entry_name.as_ptr(),
p_specialization_info: ptr::null(),
stage: vk::ShaderStageFlags::FRAGMENT, stage: vk::ShaderStageFlags::FRAGMENT,
..Default::default()
}, },
]; ];
let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription { let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription {
@ -317,21 +267,17 @@ fn main() {
offset: offset_of!(Vertex, color) as u32, offset: offset_of!(Vertex, color) as u32,
}, },
]; ];
let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo { let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo {
s_type: vk::StructureType::PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
vertex_attribute_description_count: vertex_input_attribute_descriptions.len() as u32, vertex_attribute_description_count: vertex_input_attribute_descriptions.len() as u32,
p_vertex_attribute_descriptions: vertex_input_attribute_descriptions.as_ptr(), p_vertex_attribute_descriptions: vertex_input_attribute_descriptions.as_ptr(),
vertex_binding_description_count: vertex_input_binding_descriptions.len() as u32, vertex_binding_description_count: vertex_input_binding_descriptions.len() as u32,
p_vertex_binding_descriptions: vertex_input_binding_descriptions.as_ptr(), p_vertex_binding_descriptions: vertex_input_binding_descriptions.as_ptr(),
..Default::default()
}; };
let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo { let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo {
s_type: vk::StructureType::PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
primitive_restart_enable: 0,
topology: vk::PrimitiveTopology::TRIANGLE_LIST, topology: vk::PrimitiveTopology::TRIANGLE_LIST,
..Default::default()
}; };
let viewports = [vk::Viewport { let viewports = [vk::Viewport {
x: 0.0, x: 0.0,
@ -345,63 +291,35 @@ fn main() {
offset: vk::Offset2D { x: 0, y: 0 }, offset: vk::Offset2D { x: 0, y: 0 },
extent: base.surface_resolution.clone(), extent: base.surface_resolution.clone(),
}]; }];
let viewport_state_info = vk::PipelineViewportStateCreateInfo { let viewport_state_info = vk::PipelineViewportStateCreateInfo::builder()
s_type: vk::StructureType::PIPELINE_VIEWPORT_STATE_CREATE_INFO, .scissors(&scissors)
p_next: ptr::null(), .viewports(&viewports);
flags: Default::default(),
scissor_count: scissors.len() as u32,
p_scissors: scissors.as_ptr(),
viewport_count: viewports.len() as u32,
p_viewports: viewports.as_ptr(),
};
let rasterization_info = vk::PipelineRasterizationStateCreateInfo { let rasterization_info = vk::PipelineRasterizationStateCreateInfo {
s_type: vk::StructureType::PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
cull_mode: vk::CullModeFlags::NONE,
depth_bias_clamp: 0.0,
depth_bias_constant_factor: 0.0,
depth_bias_enable: 0,
depth_bias_slope_factor: 0.0,
depth_clamp_enable: 0,
front_face: vk::FrontFace::COUNTER_CLOCKWISE, front_face: vk::FrontFace::COUNTER_CLOCKWISE,
line_width: 1.0, line_width: 1.0,
polygon_mode: vk::PolygonMode::FILL, polygon_mode: vk::PolygonMode::FILL,
rasterizer_discard_enable: 0, ..Default::default()
}; };
let multisample_state_info = vk::PipelineMultisampleStateCreateInfo { let multisample_state_info = vk::PipelineMultisampleStateCreateInfo {
s_type: vk::StructureType::PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
flags: Default::default(),
p_next: ptr::null(),
rasterization_samples: vk::SampleCountFlags::TYPE_1, rasterization_samples: vk::SampleCountFlags::TYPE_1,
sample_shading_enable: 0, ..Default::default()
min_sample_shading: 0.0,
p_sample_mask: ptr::null(),
alpha_to_one_enable: 0,
alpha_to_coverage_enable: 0,
}; };
let noop_stencil_state = vk::StencilOpState { let noop_stencil_state = vk::StencilOpState {
fail_op: vk::StencilOp::KEEP, fail_op: vk::StencilOp::KEEP,
pass_op: vk::StencilOp::KEEP, pass_op: vk::StencilOp::KEEP,
depth_fail_op: vk::StencilOp::KEEP, depth_fail_op: vk::StencilOp::KEEP,
compare_op: vk::CompareOp::ALWAYS, compare_op: vk::CompareOp::ALWAYS,
compare_mask: 0, ..Default::default()
write_mask: 0,
reference: 0,
}; };
let depth_state_info = vk::PipelineDepthStencilStateCreateInfo { let depth_state_info = vk::PipelineDepthStencilStateCreateInfo {
s_type: vk::StructureType::PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
p_next: ptr::null(),
flags: Default::default(),
depth_test_enable: 1, depth_test_enable: 1,
depth_write_enable: 1, depth_write_enable: 1,
depth_compare_op: vk::CompareOp::LESS_OR_EQUAL, depth_compare_op: vk::CompareOp::LESS_OR_EQUAL,
depth_bounds_test_enable: 0,
stencil_test_enable: 0,
front: noop_stencil_state.clone(), front: noop_stencil_state.clone(),
back: noop_stencil_state.clone(), back: noop_stencil_state.clone(),
max_depth_bounds: 1.0, max_depth_bounds: 1.0,
min_depth_bounds: 0.0, ..Default::default()
}; };
let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState { let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState {
blend_enable: 0, blend_enable: 0,
@ -413,48 +331,34 @@ fn main() {
alpha_blend_op: vk::BlendOp::ADD, alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: vk::ColorComponentFlags::all(), color_write_mask: vk::ColorComponentFlags::all(),
}]; }];
let color_blend_state = vk::PipelineColorBlendStateCreateInfo { let color_blend_state = vk::PipelineColorBlendStateCreateInfo::builder()
s_type: vk::StructureType::PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .logic_op(vk::LogicOp::CLEAR)
p_next: ptr::null(), .attachments(&color_blend_attachment_states);
flags: Default::default(),
logic_op_enable: 0,
logic_op: vk::LogicOp::CLEAR,
attachment_count: color_blend_attachment_states.len() as u32,
p_attachments: color_blend_attachment_states.as_ptr(),
blend_constants: [0.0, 0.0, 0.0, 0.0],
};
let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR]; let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
let dynamic_state_info = vk::PipelineDynamicStateCreateInfo { let dynamic_state_info =
s_type: vk::StructureType::PIPELINE_DYNAMIC_STATE_CREATE_INFO, vk::PipelineDynamicStateCreateInfo::builder().dynamic_states(&dynamic_state);
p_next: ptr::null(),
flags: Default::default(), let graphic_pipeline_info = vk::GraphicsPipelineCreateInfo::builder()
dynamic_state_count: dynamic_state.len() as u32, .stages(&shader_stage_create_infos)
p_dynamic_states: dynamic_state.as_ptr(), .vertex_input_state(&vertex_input_state_info)
}; .input_assembly_state(&vertex_input_assembly_state_info)
let graphic_pipeline_info = vk::GraphicsPipelineCreateInfo { .viewport_state(&viewport_state_info)
s_type: vk::StructureType::GRAPHICS_PIPELINE_CREATE_INFO, .rasterization_state(&rasterization_info)
p_next: ptr::null(), .multisample_state(&multisample_state_info)
flags: vk::PipelineCreateFlags::empty(), .depth_stencil_state(&depth_state_info)
stage_count: shader_stage_create_infos.len() as u32, .color_blend_state(&color_blend_state)
p_stages: shader_stage_create_infos.as_ptr(), .dynamic_state(&dynamic_state_info)
p_vertex_input_state: &vertex_input_state_info, .layout(pipeline_layout)
p_input_assembly_state: &vertex_input_assembly_state_info, .render_pass(renderpass);
p_tessellation_state: ptr::null(),
p_viewport_state: &viewport_state_info,
p_rasterization_state: &rasterization_info,
p_multisample_state: &multisample_state_info,
p_depth_stencil_state: &depth_state_info,
p_color_blend_state: &color_blend_state,
p_dynamic_state: &dynamic_state_info,
layout: pipeline_layout,
render_pass: renderpass,
subpass: 0,
base_pipeline_handle: vk::Pipeline::null(),
base_pipeline_index: 0,
};
let graphics_pipelines = base let graphics_pipelines = base
.device .device
.create_graphics_pipelines(vk::PipelineCache::null(), &[graphic_pipeline_info], None) .create_graphics_pipelines(
vk::PipelineCache::null(),
&[graphic_pipeline_info.build()],
None,
)
.expect("Unable to create graphics pipeline"); .expect("Unable to create graphics pipeline");
let graphic_pipeline = graphics_pipelines[0]; let graphic_pipeline = graphics_pipelines[0];
@ -483,18 +387,15 @@ fn main() {
}, },
]; ];
let render_pass_begin_info = vk::RenderPassBeginInfo { let render_pass_begin_info = vk::RenderPassBeginInfo::builder()
s_type: vk::StructureType::RENDER_PASS_BEGIN_INFO, .render_pass(renderpass)
p_next: ptr::null(), .framebuffer(framebuffers[present_index as usize])
render_pass: renderpass, .render_area(vk::Rect2D {
framebuffer: framebuffers[present_index as usize],
render_area: vk::Rect2D {
offset: vk::Offset2D { x: 0, y: 0 }, offset: vk::Offset2D { x: 0, y: 0 },
extent: base.surface_resolution.clone(), extent: base.surface_resolution.clone(),
}, })
clear_value_count: clear_values.len() as u32, .clear_values(&clear_values);
p_clear_values: clear_values.as_ptr(),
};
record_submit_commandbuffer( record_submit_commandbuffer(
&base.device, &base.device,
base.draw_command_buffer, base.draw_command_buffer,
@ -541,16 +442,14 @@ fn main() {
}, },
); );
//let mut present_info_err = mem::uninitialized(); //let mut present_info_err = mem::uninitialized();
let present_info = vk::PresentInfoKHR { let wait_semaphors = [base.rendering_complete_semaphore];
s_type: vk::StructureType::PRESENT_INFO_KHR, let swapchains = [base.swapchain];
p_next: ptr::null(), let image_indices = [present_index];
wait_semaphore_count: 1, let present_info = vk::PresentInfoKHR::builder()
p_wait_semaphores: &base.rendering_complete_semaphore, .wait_semaphores(&wait_semaphors) // &base.rendering_complete_semaphore)
swapchain_count: 1, .swapchains(&swapchains)
p_swapchains: &base.swapchain, .image_indices(&image_indices);
p_image_indices: &present_index,
p_results: ptr::null_mut(),
};
base.swapchain_loader base.swapchain_loader
.queue_present(base.present_queue, &present_info) .queue_present(base.present_queue, &present_info)
.unwrap(); .unwrap();

View file

@ -2,6 +2,7 @@
extern crate ash; extern crate ash;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
extern crate winapi; extern crate winapi;
extern crate winit; extern crate winit;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
@ -69,12 +70,10 @@ pub fn record_submit_commandbuffer<D: DeviceV1_0, F: FnOnce(&D, vk::CommandBuffe
vk::CommandBufferResetFlags::RELEASE_RESOURCES, vk::CommandBufferResetFlags::RELEASE_RESOURCES,
) )
.expect("Reset command buffer failed."); .expect("Reset command buffer failed.");
let command_buffer_begin_info = vk::CommandBufferBeginInfo {
s_type: vk::StructureType::COMMAND_BUFFER_BEGIN_INFO, let command_buffer_begin_info = vk::CommandBufferBeginInfo::builder()
p_next: ptr::null(), .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
p_inheritance_info: ptr::null(),
flags: vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT,
};
device device
.begin_command_buffer(command_buffer, &command_buffer_begin_info) .begin_command_buffer(command_buffer, &command_buffer_begin_info)
.expect("Begin commandbuffer"); .expect("Begin commandbuffer");
@ -82,27 +81,21 @@ pub fn record_submit_commandbuffer<D: DeviceV1_0, F: FnOnce(&D, vk::CommandBuffe
device device
.end_command_buffer(command_buffer) .end_command_buffer(command_buffer)
.expect("End commandbuffer"); .expect("End commandbuffer");
let fence_create_info = vk::FenceCreateInfo {
s_type: vk::StructureType::FENCE_CREATE_INFO,
p_next: ptr::null(),
flags: vk::FenceCreateFlags::empty(),
};
let submit_fence = device let submit_fence = device
.create_fence(&fence_create_info, None) .create_fence(&vk::FenceCreateInfo::default(), None)
.expect("Create fence failed."); .expect("Create fence failed.");
let submit_info = vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO, let command_buffers = vec![command_buffer];
p_next: ptr::null(),
wait_semaphore_count: wait_semaphores.len() as u32, let submit_info = vk::SubmitInfo::builder()
p_wait_semaphores: wait_semaphores.as_ptr(), .wait_semaphores(wait_semaphores)
p_wait_dst_stage_mask: wait_mask.as_ptr(), .wait_dst_stage_mask(wait_mask)
command_buffer_count: 1, .command_buffers(&command_buffers)
p_command_buffers: &command_buffer, .signal_semaphores(signal_semaphores);
signal_semaphore_count: signal_semaphores.len() as u32,
p_signal_semaphores: signal_semaphores.as_ptr(),
};
device device
.queue_submit(submit_queue, &[submit_info], submit_fence) .queue_submit(submit_queue, &[submit_info.build()], submit_fence)
.expect("queue submit failed."); .expect("queue submit failed.");
device device
.wait_for_fences(&[submit_fence], true, std::u64::MAX) .wait_for_fences(&[submit_fence], true, std::u64::MAX)
@ -120,13 +113,10 @@ unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>(
use winit::os::unix::WindowExt; use winit::os::unix::WindowExt;
let x11_display = window.get_xlib_display().unwrap(); let x11_display = window.get_xlib_display().unwrap();
let x11_window = window.get_xlib_window().unwrap(); let x11_window = window.get_xlib_window().unwrap();
let x11_create_info = vk::XlibSurfaceCreateInfoKHR { let x11_create_info = vk::XlibSurfaceCreateInfoKHR::builder()
s_type: vk::StructureType::XLIB_SURFACE_CREATE_INFO_KHR, .window(x11_window)
p_next: ptr::null(), .dpy(x11_display as *mut vk::Display);
flags: Default::default(),
window: x11_window as vk::Window,
dpy: x11_display as *mut vk::Display,
};
let xlib_surface_loader = XlibSurface::new(entry, instance); let xlib_surface_loader = XlibSurface::new(entry, instance);
xlib_surface_loader.create_xlib_surface(&x11_create_info, None) xlib_surface_loader.create_xlib_surface(&x11_create_info, None)
} }
@ -336,7 +326,6 @@ impl ExampleBase {
.unwrap(); .unwrap();
let entry = Entry::new().unwrap(); let entry = Entry::new().unwrap();
let app_name = CString::new("VulkanTriangle").unwrap(); let app_name = CString::new("VulkanTriangle").unwrap();
let raw_name = app_name.as_ptr();
let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()]; let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()];
let layers_names_raw: Vec<*const i8> = layer_names let layers_names_raw: Vec<*const i8> = layer_names
@ -345,37 +334,31 @@ impl ExampleBase {
.collect(); .collect();
let extension_names_raw = extension_names(); let extension_names_raw = extension_names();
let appinfo = vk::ApplicationInfo {
p_application_name: raw_name, let appinfo = vk::ApplicationInfo::builder()
s_type: vk::StructureType::APPLICATION_INFO, .application_name(&app_name)
p_next: ptr::null(), .application_version(0)
application_version: 0, .engine_name(&app_name)
p_engine_name: raw_name, .engine_version(0)
engine_version: 0, .api_version(vk_make_version!(1, 0, 36));
api_version: vk_make_version!(1, 0, 36),
}; let create_info = vk::InstanceCreateInfo::builder()
let create_info = vk::InstanceCreateInfo { .application_info(&appinfo)
s_type: vk::StructureType::INSTANCE_CREATE_INFO, .enabled_layer_names(&layers_names_raw)
p_next: ptr::null(), .enabled_extension_names(&extension_names_raw);
flags: Default::default(),
p_application_info: &appinfo,
pp_enabled_layer_names: layers_names_raw.as_ptr(),
enabled_layer_count: layers_names_raw.len() as u32,
pp_enabled_extension_names: extension_names_raw.as_ptr(),
enabled_extension_count: extension_names_raw.len() as u32,
};
let instance: Instance = entry let instance: Instance = entry
.create_instance(&create_info, None) .create_instance(&create_info, None)
.expect("Instance creation error"); .expect("Instance creation error");
let debug_info = vk::DebugReportCallbackCreateInfoEXT {
s_type: vk::StructureType::DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT, let debug_info = vk::DebugReportCallbackCreateInfoEXT::builder()
p_next: ptr::null(), .flags(
flags: vk::DebugReportFlagsEXT::ERROR vk::DebugReportFlagsEXT::ERROR
| vk::DebugReportFlagsEXT::WARNING | vk::DebugReportFlagsEXT::WARNING
| vk::DebugReportFlagsEXT::PERFORMANCE_WARNING, | vk::DebugReportFlagsEXT::PERFORMANCE_WARNING,
pfn_callback: Some(vulkan_debug_callback), )
p_user_data: ptr::null_mut(), .pfn_callback(Some(vulkan_debug_callback));
};
let debug_report_loader = DebugReport::new(&entry, &instance); let debug_report_loader = DebugReport::new(&entry, &instance);
let debug_call_back = debug_report_loader let debug_call_back = debug_report_loader
.create_debug_report_callback(&debug_info, None) .create_debug_report_callback(&debug_info, None)
@ -417,26 +400,17 @@ impl ExampleBase {
..Default::default() ..Default::default()
}; };
let priorities = [1.0]; let priorities = [1.0];
let queue_info = vk::DeviceQueueCreateInfo {
s_type: vk::StructureType::DEVICE_QUEUE_CREATE_INFO, let queue_info = [vk::DeviceQueueCreateInfo::builder()
p_next: ptr::null(), .queue_family_index(queue_family_index)
flags: Default::default(), .queue_priorities(&priorities)
queue_family_index: queue_family_index as u32, .build()];
p_queue_priorities: priorities.as_ptr(),
queue_count: priorities.len() as u32, let device_create_info = vk::DeviceCreateInfo::builder()
}; .queue_create_infos(&queue_info)
let device_create_info = vk::DeviceCreateInfo { .enabled_extension_names(&device_extension_names_raw)
s_type: vk::StructureType::DEVICE_CREATE_INFO, .enabled_features(&features);
p_next: ptr::null(),
flags: Default::default(),
queue_create_info_count: 1,
p_queue_create_infos: &queue_info,
enabled_layer_count: 0,
pp_enabled_layer_names: ptr::null(),
enabled_extension_count: device_extension_names_raw.len() as u32,
pp_enabled_extension_names: device_extension_names_raw.as_ptr(),
p_enabled_features: &features,
};
let device: Device = instance let device: Device = instance
.create_device(pdevice, &device_create_info, None) .create_device(pdevice, &device_create_info, None)
.unwrap(); .unwrap();
@ -489,43 +463,36 @@ impl ExampleBase {
.find(|&mode| mode == vk::PresentModeKHR::MAILBOX) .find(|&mode| mode == vk::PresentModeKHR::MAILBOX)
.unwrap_or(vk::PresentModeKHR::FIFO); .unwrap_or(vk::PresentModeKHR::FIFO);
let swapchain_loader = Swapchain::new(&instance, &device); let swapchain_loader = Swapchain::new(&instance, &device);
let swapchain_create_info = vk::SwapchainCreateInfoKHR {
s_type: vk::StructureType::SWAPCHAIN_CREATE_INFO_KHR, let swapchain_create_info = vk::SwapchainCreateInfoKHR::builder()
p_next: ptr::null(), .surface(surface)
flags: Default::default(), .min_image_count(desired_image_count)
surface: surface, .image_color_space(surface_format.color_space)
min_image_count: desired_image_count, .image_format(surface_format.format)
image_color_space: surface_format.color_space, .image_extent(surface_resolution.clone())
image_format: surface_format.format, .image_usage(vk::ImageUsageFlags::COLOR_ATTACHMENT)
image_extent: surface_resolution.clone(), .image_sharing_mode(vk::SharingMode::EXCLUSIVE)
image_usage: vk::ImageUsageFlags::COLOR_ATTACHMENT, .pre_transform(pre_transform)
image_sharing_mode: vk::SharingMode::EXCLUSIVE, .composite_alpha(vk::CompositeAlphaFlagsKHR::OPAQUE)
pre_transform: pre_transform, .present_mode(present_mode)
composite_alpha: vk::CompositeAlphaFlagsKHR::OPAQUE, .clipped(true)
present_mode: present_mode, .image_array_layers(1);
clipped: 1,
old_swapchain: vk::SwapchainKHR::null(),
image_array_layers: 1,
p_queue_family_indices: ptr::null(),
queue_family_index_count: 0,
};
let swapchain = swapchain_loader let swapchain = swapchain_loader
.create_swapchain(&swapchain_create_info, None) .create_swapchain(&swapchain_create_info, None)
.unwrap(); .unwrap();
let pool_create_info = vk::CommandPoolCreateInfo {
s_type: vk::StructureType::COMMAND_POOL_CREATE_INFO, let pool_create_info = vk::CommandPoolCreateInfo::builder()
p_next: ptr::null(), .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER)
flags: vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER, .queue_family_index(queue_family_index);
queue_family_index: queue_family_index,
};
let pool = device.create_command_pool(&pool_create_info, None).unwrap(); let pool = device.create_command_pool(&pool_create_info, None).unwrap();
let command_buffer_allocate_info = vk::CommandBufferAllocateInfo {
s_type: vk::StructureType::COMMAND_BUFFER_ALLOCATE_INFO, let command_buffer_allocate_info = vk::CommandBufferAllocateInfo::builder()
p_next: ptr::null(), .command_buffer_count(2)
command_buffer_count: 2, .command_pool(pool)
command_pool: pool, .level(vk::CommandBufferLevel::PRIMARY);
level: vk::CommandBufferLevel::PRIMARY,
};
let command_buffers = device let command_buffers = device
.allocate_command_buffers(&command_buffer_allocate_info) .allocate_command_buffers(&command_buffer_allocate_info)
.unwrap(); .unwrap();
@ -536,52 +503,42 @@ impl ExampleBase {
let present_image_views: Vec<vk::ImageView> = present_images let present_image_views: Vec<vk::ImageView> = present_images
.iter() .iter()
.map(|&image| { .map(|&image| {
let create_view_info = vk::ImageViewCreateInfo { let create_view_info = vk::ImageViewCreateInfo::builder()
s_type: vk::StructureType::IMAGE_VIEW_CREATE_INFO, .view_type(vk::ImageViewType::TYPE_2D)
p_next: ptr::null(), .format(surface_format.format)
flags: Default::default(), .components(vk::ComponentMapping {
view_type: vk::ImageViewType::TYPE_2D,
format: surface_format.format,
components: vk::ComponentMapping {
r: vk::ComponentSwizzle::R, r: vk::ComponentSwizzle::R,
g: vk::ComponentSwizzle::G, g: vk::ComponentSwizzle::G,
b: vk::ComponentSwizzle::B, b: vk::ComponentSwizzle::B,
a: vk::ComponentSwizzle::A, a: vk::ComponentSwizzle::A,
}, })
subresource_range: vk::ImageSubresourceRange { .subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR, aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0, base_mip_level: 0,
level_count: 1, level_count: 1,
base_array_layer: 0, base_array_layer: 0,
layer_count: 1, layer_count: 1,
}, })
image: image, .image(image);
};
device.create_image_view(&create_view_info, None).unwrap() device.create_image_view(&create_view_info, None).unwrap()
}) })
.collect(); .collect();
let device_memory_properties = instance.get_physical_device_memory_properties(pdevice); let device_memory_properties = instance.get_physical_device_memory_properties(pdevice);
let depth_image_create_info = vk::ImageCreateInfo { let depth_image_create_info = vk::ImageCreateInfo::builder()
s_type: vk::StructureType::IMAGE_CREATE_INFO, .image_type(vk::ImageType::TYPE_2D)
p_next: ptr::null(), .format(vk::Format::D16_UNORM)
flags: Default::default(), .extent(vk::Extent3D {
image_type: vk::ImageType::TYPE_2D,
format: vk::Format::D16_UNORM,
extent: vk::Extent3D {
width: surface_resolution.width, width: surface_resolution.width,
height: surface_resolution.height, height: surface_resolution.height,
depth: 1, depth: 1,
}, })
mip_levels: 1, .mip_levels(1)
array_layers: 1, .array_layers(1)
samples: vk::SampleCountFlags::TYPE_1, .samples(vk::SampleCountFlags::TYPE_1)
tiling: vk::ImageTiling::OPTIMAL, .tiling(vk::ImageTiling::OPTIMAL)
usage: vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT, .usage(vk::ImageUsageFlags::DEPTH_STENCIL_ATTACHMENT)
sharing_mode: vk::SharingMode::EXCLUSIVE, .sharing_mode(vk::SharingMode::EXCLUSIVE);
queue_family_index_count: 0,
p_queue_family_indices: ptr::null(),
initial_layout: vk::ImageLayout::UNDEFINED,
};
let depth_image = device.create_image(&depth_image_create_info, None).unwrap(); let depth_image = device.create_image(&depth_image_create_info, None).unwrap();
let depth_image_memory_req = device.get_image_memory_requirements(depth_image); let depth_image_memory_req = device.get_image_memory_requirements(depth_image);
let depth_image_memory_index = find_memorytype_index( let depth_image_memory_index = find_memorytype_index(
@ -591,45 +548,42 @@ impl ExampleBase {
) )
.expect("Unable to find suitable memory index for depth image."); .expect("Unable to find suitable memory index for depth image.");
let depth_image_allocate_info = vk::MemoryAllocateInfo { let depth_image_allocate_info = vk::MemoryAllocateInfo::builder()
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO, .allocation_size(depth_image_memory_req.size)
p_next: ptr::null(), .memory_type_index(depth_image_memory_index);
allocation_size: depth_image_memory_req.size,
memory_type_index: depth_image_memory_index,
};
let depth_image_memory = device let depth_image_memory = device
.allocate_memory(&depth_image_allocate_info, None) .allocate_memory(&depth_image_allocate_info, None)
.unwrap(); .unwrap();
device device
.bind_image_memory(depth_image, depth_image_memory, 0) .bind_image_memory(depth_image, depth_image_memory, 0)
.expect("Unable to bind depth image memory"); .expect("Unable to bind depth image memory");
record_submit_commandbuffer( record_submit_commandbuffer(
&device, &device,
setup_command_buffer, setup_command_buffer,
present_queue, present_queue,
&[vk::PipelineStageFlags::BOTTOM_OF_PIPE], &[],
&[], &[],
&[], &[],
|device, setup_command_buffer| { |device, setup_command_buffer| {
let layout_transition_barrier = vk::ImageMemoryBarrier { let layout_transition_barriers = vk::ImageMemoryBarrier::builder()
s_type: vk::StructureType::IMAGE_MEMORY_BARRIER, .image(depth_image)
p_next: ptr::null(), .dst_access_mask(
src_access_mask: Default::default(), vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ
dst_access_mask: vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_READ
| vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE, | vk::AccessFlags::DEPTH_STENCIL_ATTACHMENT_WRITE,
old_layout: vk::ImageLayout::UNDEFINED, )
new_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, .new_layout(vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
src_queue_family_index: vk::QUEUE_FAMILY_IGNORED, .old_layout(vk::ImageLayout::UNDEFINED)
dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED, .subresource_range(
image: depth_image, vk::ImageSubresourceRange::builder()
subresource_range: vk::ImageSubresourceRange { .aspect_mask(vk::ImageAspectFlags::DEPTH)
aspect_mask: vk::ImageAspectFlags::DEPTH, .layer_count(1)
base_mip_level: 0, .level_count(1)
level_count: 1, .build(),
base_array_layer: 0, );
layer_count: 1,
},
};
device.cmd_pipeline_barrier( device.cmd_pipeline_barrier(
setup_command_buffer, setup_command_buffer,
vk::PipelineStageFlags::BOTTOM_OF_PIPE, vk::PipelineStageFlags::BOTTOM_OF_PIPE,
@ -637,39 +591,29 @@ impl ExampleBase {
vk::DependencyFlags::empty(), vk::DependencyFlags::empty(),
&[], &[],
&[], &[],
&[layout_transition_barrier], &[layout_transition_barriers.build()],
); );
}, },
); );
let depth_image_view_info = vk::ImageViewCreateInfo {
s_type: vk::StructureType::IMAGE_VIEW_CREATE_INFO, let depth_image_view_info = vk::ImageViewCreateInfo::builder()
p_next: ptr::null(), .subresource_range(
flags: Default::default(), vk::ImageSubresourceRange::builder()
view_type: vk::ImageViewType::TYPE_2D, .aspect_mask(vk::ImageAspectFlags::DEPTH)
format: depth_image_create_info.format, .level_count(1)
components: vk::ComponentMapping { .layer_count(1)
r: vk::ComponentSwizzle::IDENTITY, .build(),
g: vk::ComponentSwizzle::IDENTITY, )
b: vk::ComponentSwizzle::IDENTITY, .image(depth_image)
a: vk::ComponentSwizzle::IDENTITY, .format(depth_image_create_info.format)
}, .view_type(vk::ImageViewType::TYPE_2D);
subresource_range: vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::DEPTH,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
},
image: depth_image,
};
let depth_image_view = device let depth_image_view = device
.create_image_view(&depth_image_view_info, None) .create_image_view(&depth_image_view_info, None)
.unwrap(); .unwrap();
let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SEMAPHORE_CREATE_INFO, let semaphore_create_info = vk::SemaphoreCreateInfo::default();
p_next: ptr::null(),
flags: Default::default(),
};
let present_complete_semaphore = device let present_complete_semaphore = device
.create_semaphore(&semaphore_create_info, None) .create_semaphore(&semaphore_create_info, None)
.unwrap(); .unwrap();