vulkano/examples/src/bin/deferred/triangle_draw_system.rs

182 lines
5.9 KiB
Rust
Raw Normal View History

// Copyright (c) 2017 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
use std::sync::Arc;
use vulkano::{
buffer::{Buffer, BufferContents, BufferCreateInfo, BufferUsage, Subbuffer},
command_buffer::{
allocator::StandardCommandBufferAllocator, AutoCommandBufferBuilder,
CommandBufferInheritanceInfo, CommandBufferUsage, SecondaryAutoCommandBuffer,
},
device::Queue,
memory::allocator::{AllocationCreateInfo, MemoryUsage, StandardMemoryAllocator},
pipeline::{
graphics::{
color_blend::ColorBlendState,
depth_stencil::DepthStencilState,
input_assembly::InputAssemblyState,
multisample::MultisampleState,
rasterization::RasterizationState,
vertex_input::{Vertex, VertexDefinition},
viewport::{Viewport, ViewportState},
},
GraphicsPipeline,
},
render_pass::Subpass,
shader::PipelineShaderStageCreateInfo,
};
pub struct TriangleDrawSystem {
gfx_queue: Arc<Queue>,
vertex_buffer: Subbuffer<[TriangleVertex]>,
subpass: Subpass,
pipeline: Arc<GraphicsPipeline>,
command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
}
impl TriangleDrawSystem {
/// Initializes a triangle drawing system.
pub fn new(
gfx_queue: Arc<Queue>,
subpass: Subpass,
2022-10-26 14:25:01 +00:00
memory_allocator: &StandardMemoryAllocator,
command_buffer_allocator: Arc<StandardCommandBufferAllocator>,
) -> TriangleDrawSystem {
let vertices = [
Refactor Vertex trait to allow user-defined formats (#2106) * Refactor Vertex trait to not rely on ShaderInterfaceEntryType::to_format and instead rely on Format provided by VertexMember trait. * Add test for impl_vertex macro, remove tuple implementations as they do not implement Pod, minor cleanups to impl_vertex macro. * #[derive(Vertex)] proc-macro implementation with support for format and name attributes. Tests are implemented for both attributes and inferral matching impl_vertex macro * Rename num_elements into num_locations to make purpose clear, add helper function to calculate num_components and check them properly in BufferDefinition's VertexDefinition implementation. * Rename num_locations back to num_elements to make distinction to locations clear. Updated VertexDefinition implementation for BuffersDefinition to support double precision formats exceeding a single location. * Add additional validation for vertex attributes with formats exceeding their location. * Collect unnecessary, using iterator in loop to avoid unnecessary allocations. * Use field type directly and avoid any form of unsafe blocks. * Match shader scalar type directly in GraphicsPipelineBuilder * Rename impl_vertex test to fit macro name * Add VertexMember implementatinos for nalgebra and cgmath (incl matrices). * Add missing copyright headers to new files in proc macro crate * Document derive vertex with field-attribute options on the Vertex trait * Add example for vertex derive approach. * Do not publish internal macros crate as it is re-exported by vulkano itself * Deprecate impl_vertex and VertexMember and update documentation for Vertex accordingly * Make format field-level attribute mandatory for derive vertex * Update all examples to derive Vertex trait instead of impl_vertex macro * Fix doctests by adding missing imports and re-exporting crate self as vulkano to workaround limitations of distinguishing doctests in proc-macros
2022-12-28 10:23:36 +00:00
TriangleVertex {
position: [-0.5, -0.25],
},
Refactor Vertex trait to allow user-defined formats (#2106) * Refactor Vertex trait to not rely on ShaderInterfaceEntryType::to_format and instead rely on Format provided by VertexMember trait. * Add test for impl_vertex macro, remove tuple implementations as they do not implement Pod, minor cleanups to impl_vertex macro. * #[derive(Vertex)] proc-macro implementation with support for format and name attributes. Tests are implemented for both attributes and inferral matching impl_vertex macro * Rename num_elements into num_locations to make purpose clear, add helper function to calculate num_components and check them properly in BufferDefinition's VertexDefinition implementation. * Rename num_locations back to num_elements to make distinction to locations clear. Updated VertexDefinition implementation for BuffersDefinition to support double precision formats exceeding a single location. * Add additional validation for vertex attributes with formats exceeding their location. * Collect unnecessary, using iterator in loop to avoid unnecessary allocations. * Use field type directly and avoid any form of unsafe blocks. * Match shader scalar type directly in GraphicsPipelineBuilder * Rename impl_vertex test to fit macro name * Add VertexMember implementatinos for nalgebra and cgmath (incl matrices). * Add missing copyright headers to new files in proc macro crate * Document derive vertex with field-attribute options on the Vertex trait * Add example for vertex derive approach. * Do not publish internal macros crate as it is re-exported by vulkano itself * Deprecate impl_vertex and VertexMember and update documentation for Vertex accordingly * Make format field-level attribute mandatory for derive vertex * Update all examples to derive Vertex trait instead of impl_vertex macro * Fix doctests by adding missing imports and re-exporting crate self as vulkano to workaround limitations of distinguishing doctests in proc-macros
2022-12-28 10:23:36 +00:00
TriangleVertex {
position: [0.0, 0.5],
},
Refactor Vertex trait to allow user-defined formats (#2106) * Refactor Vertex trait to not rely on ShaderInterfaceEntryType::to_format and instead rely on Format provided by VertexMember trait. * Add test for impl_vertex macro, remove tuple implementations as they do not implement Pod, minor cleanups to impl_vertex macro. * #[derive(Vertex)] proc-macro implementation with support for format and name attributes. Tests are implemented for both attributes and inferral matching impl_vertex macro * Rename num_elements into num_locations to make purpose clear, add helper function to calculate num_components and check them properly in BufferDefinition's VertexDefinition implementation. * Rename num_locations back to num_elements to make distinction to locations clear. Updated VertexDefinition implementation for BuffersDefinition to support double precision formats exceeding a single location. * Add additional validation for vertex attributes with formats exceeding their location. * Collect unnecessary, using iterator in loop to avoid unnecessary allocations. * Use field type directly and avoid any form of unsafe blocks. * Match shader scalar type directly in GraphicsPipelineBuilder * Rename impl_vertex test to fit macro name * Add VertexMember implementatinos for nalgebra and cgmath (incl matrices). * Add missing copyright headers to new files in proc macro crate * Document derive vertex with field-attribute options on the Vertex trait * Add example for vertex derive approach. * Do not publish internal macros crate as it is re-exported by vulkano itself * Deprecate impl_vertex and VertexMember and update documentation for Vertex accordingly * Make format field-level attribute mandatory for derive vertex * Update all examples to derive Vertex trait instead of impl_vertex macro * Fix doctests by adding missing imports and re-exporting crate self as vulkano to workaround limitations of distinguishing doctests in proc-macros
2022-12-28 10:23:36 +00:00
TriangleVertex {
position: [0.25, -0.1],
},
];
let vertex_buffer = Buffer::from_iter(
memory_allocator,
BufferCreateInfo {
usage: BufferUsage::VERTEX_BUFFER,
..Default::default()
},
AllocationCreateInfo {
usage: MemoryUsage::Upload,
..Default::default()
},
vertices,
)
.expect("failed to create buffer");
let pipeline = {
let vs = vs::load(gfx_queue.device().clone())
.expect("failed to create shader module")
.entry_point("main")
.expect("shader entry point not found");
let fs = fs::load(gfx_queue.device().clone())
.expect("failed to create shader module")
.entry_point("main")
.expect("shader entry point not found");
let vertex_input_state = TriangleVertex::per_vertex()
.definition(&vs.info().input_interface)
.unwrap();
GraphicsPipeline::start()
.stages([
PipelineShaderStageCreateInfo::entry_point(vs),
PipelineShaderStageCreateInfo::entry_point(fs),
])
.vertex_input_state(vertex_input_state)
.input_assembly_state(InputAssemblyState::default())
.viewport_state(ViewportState::viewport_dynamic_scissor_irrelevant())
.rasterization_state(RasterizationState::default())
.depth_stencil_state(DepthStencilState::simple_depth_test())
.multisample_state(MultisampleState::default())
.color_blend_state(ColorBlendState::new(subpass.num_color_attachments()))
.render_pass(subpass.clone())
.build(gfx_queue.device().clone())
.unwrap()
};
TriangleDrawSystem {
gfx_queue,
vertex_buffer,
subpass,
pipeline,
command_buffer_allocator,
}
}
/// Builds a secondary command buffer that draws the triangle on the current subpass.
pub fn draw(&self, viewport_dimensions: [u32; 2]) -> SecondaryAutoCommandBuffer {
let mut builder = AutoCommandBufferBuilder::secondary(
&self.command_buffer_allocator,
self.gfx_queue.queue_family_index(),
CommandBufferUsage::MultipleSubmit,
CommandBufferInheritanceInfo {
render_pass: Some(self.subpass.clone().into()),
..Default::default()
},
)
.unwrap();
builder
.set_viewport(
0,
[Viewport {
origin: [0.0, 0.0],
dimensions: [viewport_dimensions[0] as f32, viewport_dimensions[1] as f32],
depth_range: 0.0..1.0,
}],
)
.bind_pipeline_graphics(self.pipeline.clone())
.bind_vertex_buffers(0, self.vertex_buffer.clone())
.draw(self.vertex_buffer.len() as u32, 1, 0, 0)
.unwrap();
builder.build().unwrap()
}
}
#[derive(BufferContents, Vertex)]
2021-11-24 14:19:57 +00:00
#[repr(C)]
Refactor Vertex trait to allow user-defined formats (#2106) * Refactor Vertex trait to not rely on ShaderInterfaceEntryType::to_format and instead rely on Format provided by VertexMember trait. * Add test for impl_vertex macro, remove tuple implementations as they do not implement Pod, minor cleanups to impl_vertex macro. * #[derive(Vertex)] proc-macro implementation with support for format and name attributes. Tests are implemented for both attributes and inferral matching impl_vertex macro * Rename num_elements into num_locations to make purpose clear, add helper function to calculate num_components and check them properly in BufferDefinition's VertexDefinition implementation. * Rename num_locations back to num_elements to make distinction to locations clear. Updated VertexDefinition implementation for BuffersDefinition to support double precision formats exceeding a single location. * Add additional validation for vertex attributes with formats exceeding their location. * Collect unnecessary, using iterator in loop to avoid unnecessary allocations. * Use field type directly and avoid any form of unsafe blocks. * Match shader scalar type directly in GraphicsPipelineBuilder * Rename impl_vertex test to fit macro name * Add VertexMember implementatinos for nalgebra and cgmath (incl matrices). * Add missing copyright headers to new files in proc macro crate * Document derive vertex with field-attribute options on the Vertex trait * Add example for vertex derive approach. * Do not publish internal macros crate as it is re-exported by vulkano itself * Deprecate impl_vertex and VertexMember and update documentation for Vertex accordingly * Make format field-level attribute mandatory for derive vertex * Update all examples to derive Vertex trait instead of impl_vertex macro * Fix doctests by adding missing imports and re-exporting crate self as vulkano to workaround limitations of distinguishing doctests in proc-macros
2022-12-28 10:23:36 +00:00
struct TriangleVertex {
#[format(R32G32_SFLOAT)]
position: [f32; 2],
}
mod vs {
vulkano_shaders::shader! {
ty: "vertex",
src: r"
#version 450
layout(location = 0) in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
}
}
mod fs {
vulkano_shaders::shader! {
ty: "fragment",
src: r"
#version 450
layout(location = 0) out vec4 f_color;
layout(location = 1) out vec3 f_normal;
void main() {
f_color = vec4(1.0, 1.0, 1.0, 1.0);
f_normal = vec3(0.0, 0.0, 1.0);
}
",
}
}