moved around the file heirarchy to make these handles safer

This commit is contained in:
2020-02-04 23:02:21 -08:00
parent bb5617420e
commit 8fcd26063a
23 changed files with 163 additions and 127 deletions

View File

@@ -0,0 +1,103 @@
use std::sync::Arc;
use vulkano::device::Device;
use vulkano::buffer::{CpuAccessibleBuffer, BufferUsage};
use vulkano::pipeline::ComputePipeline;
use vulkano::descriptor::pipeline_layout::PipelineLayout;
use vulkano::descriptor::descriptor_set::{PersistentDescriptorSet, PersistentDescriptorSetBuf};
use image::ImageBuffer;
use image::Rgba;
use shade_runner::Layout;
use crate::compute::managed::handles::CompuBufferHandle;
#[derive(Clone)]
pub struct CompuBuffers {
dimensions: (u32, u32),
device: Arc<Device>,
handle: Arc<CompuBufferHandle>,
io_buffers: Vec<Arc<CpuAccessibleBuffer<[u8]>>>,
settings_buffer: Arc<CpuAccessibleBuffer<[u32]>>,
}
impl CompuBuffers {
pub fn new(device: Arc<Device>, data: Vec<u8>,
dimensions: (u32, u32), stride: u32,
handle: Arc<CompuBufferHandle>) -> CompuBuffers {
let data_length = dimensions.0 * dimensions.1 * stride;
let input_buffer = {
let mut buff = data.iter();
let data_iter = (0..data_length).map(|n| *(buff.next().unwrap()));
CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter).unwrap()
};
let output_buffer = {
let mut buff = data.iter();
let data_iter = (0..data_length).map(|n| *(buff.next().unwrap()));
CpuAccessibleBuffer::from_iter(device.clone(), BufferUsage::all(), data_iter).unwrap()
};
// Settings buffer which holds i32's
// Compile macros into the kernel eventually to index them
let settings_buffer = {
let vec = vec![dimensions.0, dimensions.1];
let mut buff = vec.iter();
let data_iter =
(0..2).map(|n| *(buff.next().unwrap()));
CpuAccessibleBuffer::from_iter(device.clone(),
BufferUsage::all(),
data_iter).unwrap()
};
CompuBuffers {
dimensions: dimensions,
device: device.clone(),
handle: handle,
io_buffers: vec![input_buffer, output_buffer],
settings_buffer: settings_buffer,
}
}
pub fn get_size(&self) -> (u32, u32) {
self.dimensions
}
pub fn get_descriptor_set(&self, compute_pipeline: std::sync::Arc<ComputePipeline<PipelineLayout<Layout>>>)
-> Arc<PersistentDescriptorSet<std::sync::Arc<ComputePipeline<PipelineLayout<Layout>>>, ((((),
PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u8]>>>),
PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u8]>>>),
PersistentDescriptorSetBuf<std::sync::Arc<vulkano::buffer::cpu_access::CpuAccessibleBuffer<[u32]>>>)>> {
Arc::new(PersistentDescriptorSet::start(compute_pipeline.clone(), 0)
.add_buffer(self.io_buffers.get(0).unwrap().clone()).unwrap()
.add_buffer(self.io_buffers.get(1).unwrap().clone()).unwrap()
.add_buffer(self.settings_buffer.clone()).unwrap()
.build().unwrap())
}
pub fn read_output_buffer(&self) -> ImageBuffer<Rgba<u8>, Vec<u8>> {
let xy = self.get_size();
self.io_buffers.get(1).unwrap().write().unwrap().map(|x| x);
let data_buffer_content = self.io_buffers.get(1).unwrap().read().unwrap();
ImageBuffer::from_fn(xy.0, xy.1, |x, y| {
let r = data_buffer_content[((xy.0 * y + x) * 4 + 0) as usize] as u8;
let g = data_buffer_content[((xy.0 * y + x) * 4 + 1) as usize] as u8;
let b = data_buffer_content[((xy.0 * y + x) * 4 + 2) as usize] as u8;
let a = data_buffer_content[((xy.0 * y + x) * 4 + 3) as usize] as u8;
image::Rgba([r, g, b, a])
})
}
pub fn get_input_buffer(&self) -> Arc<CpuAccessibleBuffer<[u8]>> {
self.io_buffers.get(0).unwrap().clone()
}
pub fn get_output_buffer(&self) -> Arc<CpuAccessibleBuffer<[u8]>> {
self.io_buffers.get(1).unwrap().clone()
}
}

View File

@@ -0,0 +1,161 @@
use vulkano::device::{Device};
use vulkano::pipeline::{ComputePipeline};
use std::sync::Arc;
use std::ffi::CStr;
use std::path::PathBuf;
use shade_runner as sr;
use vulkano::descriptor::pipeline_layout::PipelineLayout;
use shade_runner::{CompileError, Layout, Input, Output, CompiledShaders, Entry, CompiledShader};
use shaderc::CompileOptions;
use vulkano::pipeline::shader::{ShaderModule, GraphicsEntryPoint, SpecializationConstants, SpecializationMapEntry};
use crate::compute::managed::handles::CompuKernelHandle;
#[derive(Clone)]
pub struct CompuKernel {
handle: Arc<CompuKernelHandle>,
compute_pipeline: Option<std::sync::Arc<ComputePipeline<PipelineLayout<Layout>>>>,
compute_kernel_path: PathBuf,
name: String,
shader: CompiledShader,
entry: Entry,
shader_module: Arc<ShaderModule>,
device: Arc<Device>,
specialization_constants: ComputeSpecializationConstants,
}
impl CompuKernel {
fn get_path(filename: String) -> PathBuf {
let project_root =
std::env::current_dir()
.expect("failed to get root directory");
let mut compute_path = project_root.clone();
compute_path.push(PathBuf::from("resources/shaders/"));
compute_path.push(PathBuf::from(filename));
compute_path
}
pub fn new(filename: String, device: Arc<Device>,
handle: Arc<CompuKernelHandle>) -> CompuKernel {
let compute_path = CompuKernel::get_path(filename.clone());
let mut options = CompileOptions::new().ok_or(CompileError::CreateCompiler).unwrap();
let shader = sr::load_compute_with_options(compute_path.clone(), options)
.expect("Failed to compile");
let entry = sr::parse_compute(&shader)
.expect("Failed to parse");
let shader_module = unsafe {
vulkano::pipeline::shader::ShaderModule::from_words(device.clone(), &shader.spriv)
}.unwrap();
CompuKernel {
name: filename,
handle: handle,
device: device,
shader: shader,
compute_pipeline: Option::None,
compute_kernel_path: compute_path,
entry: entry,
shader_module: shader_module,
specialization_constants: ComputeSpecializationConstants {
first_constant: 0,
second_constant: 0,
third_constant: 0.0
}
}
}
pub fn get_pipeline(&mut self) -> std::sync::Arc<ComputePipeline<PipelineLayout<Layout>>> {
match self.compute_pipeline.clone() {
Some(t) => t,
None => {
self.compute_pipeline = Some(Arc::new({
unsafe {
ComputePipeline::new(self.device.clone(), &self.shader_module.compute_entry_point(
CStr::from_bytes_with_nul_unchecked(b"main\0"),
self.entry.layout.clone()), &self.specialization_constants,
).unwrap()
}
}));
self.compute_pipeline.clone().unwrap()
}
}
}
pub fn recompile_kernel(&mut self) -> std::sync::Arc<ComputePipeline<PipelineLayout<shade_runner::layouts::Layout>>> {
self.compile_kernel(String::from(self.compute_kernel_path.clone().to_str().unwrap()))
}
pub fn compile_kernel(&mut self, filename: String) -> std::sync::Arc<ComputePipeline<PipelineLayout<Layout>>> {
let mut options = CompileOptions::new().ok_or(CompileError::CreateCompiler).unwrap();
self.compute_kernel_path = CompuKernel::get_path(filename);
self.shader =
sr::load_compute_with_options(self.compute_kernel_path.clone(), options)
.expect("Failed to compile");
self.entry =
sr::parse_compute(&self.shader)
.expect("Failed to parse");
self.shader_module = unsafe {
vulkano::pipeline::shader::ShaderModule::from_words(self.device.clone(), &self.shader.spriv)
}.unwrap();
self.get_pipeline()
}
pub fn get_handle(&self) -> Arc<CompuKernelHandle> {
self.handle.clone()
}
pub fn get_name(&self) -> String {
self.name.clone()
}
}
#[repr(C)]
#[derive(Default, Debug, Clone)]
pub struct ComputeSpecializationConstants {
first_constant: i32,
second_constant: u32,
third_constant: f32,
}
unsafe impl SpecializationConstants for ComputeSpecializationConstants {
fn descriptors() -> &'static [SpecializationMapEntry] {
static DESCRIPTORS: [SpecializationMapEntry; 3] = [
SpecializationMapEntry {
constant_id: 0,
offset: 0,
size: 4,
},
SpecializationMapEntry {
constant_id: 1,
offset: 4,
size: 4,
},
SpecializationMapEntry {
constant_id: 2,
offset: 8,
size: 4,
},
];
&DESCRIPTORS
}
}

View File

@@ -0,0 +1,71 @@
use crate::canvas::canvas_state::{Drawable};
use std::sync::Arc;
use crate::canvas::managed::handles::{CanvasImageHandle, CanvasTextureHandle};
pub struct CompuSprite {
pub vertices: [(f32, f32, f32); 6],
pub ti_position: [(f32, f32); 6],
position: (f32, f32),
size: (f32, f32),
color: (f32, f32, f32, f32),
image_handle: Arc<CanvasImageHandle>,
}
impl CompuSprite {
pub fn new(position: (f32, f32),
size: (f32, f32),
depth: u32,
image_size: (f32, f32),
image_handle: Arc<CanvasImageHandle>) -> CompuSprite {
let normalized_depth = (depth as f32 / 255.0);
CompuSprite {
vertices: [
(position.0, position.1 , normalized_depth), // top left
(position.0, position.1 + size.1 , normalized_depth), // bottom left
(position.0 + size.0, position.1 + size.1, normalized_depth), // bottom right
(position.0, position.1 , normalized_depth), // top left
(position.0 + size.0, position.1 + size.1, normalized_depth), // bottom right
(position.0 + size.0, position.1 , normalized_depth), // top right
],
ti_position: [
(0.0 , 0.0 ), // top left
(0.0 , image_size.1), // bottom left
(image_size.0, image_size.1), // bottom right
(0.0 , 0.0 ), // top left
(image_size.0, image_size.1), // bottom right
(image_size.0, 0.0 ), // top right
],
position: position,
size: size,
color: (0.0, 0.0, 0.0, 0.0),
image_handle: image_handle.clone(),
}
}
}
impl Drawable for CompuSprite {
fn get_vertices(&self) -> Vec<(f32, f32, f32)> {
self.vertices.to_vec()
}
fn get_color(&self) -> (f32, f32, f32, f32) {
self.color
}
fn get_ti_coords(&self) -> Vec<(f32, f32)> {
self.ti_position.to_vec()
}
fn get_texture_handle(&self) -> Option<Arc<CanvasTextureHandle>> {
None
}
fn get_image_handle(&self) -> Option<Arc<CanvasImageHandle>> {
Some(self.image_handle.clone())
}
}

View File

@@ -0,0 +1,29 @@
use crate::canvas::managed::handles::Handle;
/// Typed wrapper for a u32 handle
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct CompuBufferHandle {
pub(in crate::compute) handle: u32,
}
impl Handle for CompuBufferHandle {
fn get_handle(&self) -> u32 {
self.handle
}
}
/// Typed wrapper for a u32 handle
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct CompuKernelHandle {
pub(in crate::compute) handle: u32,
}
impl Handle for CompuKernelHandle {
fn get_handle(&self) -> u32 {
self.handle
}
}

View File

@@ -0,0 +1,5 @@
pub mod compu_buffer;
pub mod compu_sprite;
pub mod compu_kernel;
pub mod handles;