Compare commits

..

No commits in common. 'working' and 'main' have entirely different histories.

@ -1,5 +1,5 @@
[package]
name = "particles"
name = "tri"
version = "0.1.0"
edition = "2021"

@ -0,0 +1,131 @@
let SessionLoad = 1
let s:so_save = &g:so | let s:siso_save = &g:siso | setg so=0 siso=0 | setl so=-1 siso=-1
let v:this_session=expand("<sfile>:p")
silent only
silent tabonly
cd ~/bin/rs/tri
if expand('%') == '' && !&modified && line('$') <= 1 && getline(1) == ''
let s:wipebuf = bufnr('%')
endif
let s:shortmess_save = &shortmess
if &shortmess =~ 'A'
set shortmess=aoOA
else
set shortmess=aoO
endif
badd +1 ~/bin/rs/tri
badd +1 src/render.rs
badd +0 src/utility/share.rs
argglobal
%argdel
$argadd ~/bin/rs/tri
edit src/render.rs
let s:save_splitbelow = &splitbelow
let s:save_splitright = &splitright
set splitbelow splitright
wincmd _ | wincmd |
vsplit
wincmd _ | wincmd |
vsplit
2wincmd h
wincmd w
wincmd w
let &splitbelow = s:save_splitbelow
let &splitright = s:save_splitright
wincmd t
let s:save_winminheight = &winminheight
let s:save_winminwidth = &winminwidth
set winminheight=0
set winheight=1
set winminwidth=0
set winwidth=1
exe 'vert 1resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 2resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 3resize ' . ((&columns * 70 + 107) / 214)
argglobal
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 61 - ((45 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 61
normal! 0
lcd ~/bin/rs/tri
wincmd w
argglobal
if bufexists(fnamemodify("~/bin/rs/tri/src/utility/share.rs", ":p")) | buffer ~/bin/rs/tri/src/utility/share.rs | else | edit ~/bin/rs/tri/src/utility/share.rs | endif
if &buftype ==# 'terminal'
silent file ~/bin/rs/tri/src/utility/share.rs
endif
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 190 - ((53 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 190
normal! 013|
lcd ~/bin/rs/tri
wincmd w
argglobal
if bufexists(fnamemodify("~/bin/rs/tri/src/utility/share.rs", ":p")) | buffer ~/bin/rs/tri/src/utility/share.rs | else | edit ~/bin/rs/tri/src/utility/share.rs | endif
if &buftype ==# 'terminal'
silent file ~/bin/rs/tri/src/utility/share.rs
endif
setlocal fdm=manual
setlocal fde=0
setlocal fmr={{{,}}}
setlocal fdi=#
setlocal fdl=0
setlocal fml=1
setlocal fdn=20
setlocal fen
silent! normal! zE
let &fdl = &fdl
let s:l = 1651 - ((36 * winheight(0) + 40) / 81)
if s:l < 1 | let s:l = 1 | endif
keepjumps exe s:l
normal! zt
keepjumps 1651
normal! 016|
lcd ~/bin/rs/tri
wincmd w
3wincmd w
exe 'vert 1resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 2resize ' . ((&columns * 71 + 107) / 214)
exe 'vert 3resize ' . ((&columns * 70 + 107) / 214)
tabnext 1
if exists('s:wipebuf') && len(win_findbuf(s:wipebuf)) == 0 && getbufvar(s:wipebuf, '&buftype') isnot# 'terminal'
silent exe 'bwipe ' . s:wipebuf
endif
unlet! s:wipebuf
set winheight=1 winwidth=20
let &shortmess = s:shortmess_save
let &winminheight = s:save_winminheight
let &winminwidth = s:save_winminwidth
let s:sx = expand("<sfile>:p:r")."x.vim"
if filereadable(s:sx)
exe "source " . fnameescape(s:sx)
endif
let &g:so = s:so_save | let &g:siso = s:siso_save
set hlsearch
doautoall SessionLoadPost
unlet SessionLoad
" vim: set ft=vim :

@ -6,11 +6,6 @@ use std::process::Command;
fn main() -> std::io::Result<()> {
println!("building shaders...");
//rm shader target path if it exists
if Path::new("./target/shaders").exists() {
println!("exists");
Command::new("rm").args(["-rf", "target/shaders"]).status().unwrap();
}
//shaders path
let shaders = Path::new("./src/shaders");
//shader target path

2482
rnd.rs

File diff suppressed because it is too large Load Diff

@ -8,51 +8,15 @@ use rand::{
use crate::utility::constants::*;
use std::f32::consts::PI;
use std::ffi::c_void;
use std::{ fmt, slice };
pub const PARTICLE_COUNT: u64 = 5;
pub const PARTICLE_COUNT: u64 = 1;
#[repr(C)]
#[derive(Clone, Debug, Copy)]
pub struct Particle {
pub pos: (f32, f32),
pub vel: (f32, f32),
pub color: (f32, f32, f32, f32),
}
pub struct ParticlesList(pub Vec<Particle>);
impl ParticlesList {
pub fn from_vec(particles: Vec<Particle>) -> ParticlesList {
ParticlesList(particles)
}
pub fn from_raw_ptr(ptr: *const Particle, len: usize) -> ParticlesList {
let mut vec = vec![];
vec.extend_from_slice(
unsafe { slice::from_raw_parts(ptr, len) as &[Particle] }
);
ParticlesList(
vec
)
}
}
impl fmt::Display for ParticlesList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "PARTICLES, LEN IS {}\n\n", self.0.len())?;
for (i, particle) in self.0.iter().enumerate() {
write!(
f,
" Particle {{\n pos: {:?}\n vel: {:?}\n color: {:?}\n }}",
particle.pos,
particle.vel,
particle.color,
)?;
}
Ok(())
}
pos: (f32, f32),
vel: (f32, f32),
color: (f32, f32, f32, f32),
}
fn normalize(vec2: (f32, f32)) -> (f32, f32) {
@ -82,11 +46,10 @@ impl Particle {
println!("THETA {}", theta);
let x = r * theta.cos() * WINDOW_HEIGHT as f32 / WINDOW_WIDTH as f32;
let y = r * theta.sin();
//let (x, y) = (100000.0, 0.0);
let (x, y) = (10.0, 0.0);
res.push(Particle {
pos: (x, y),
//vel: vec2_scalar_mul(normalize((x, y)), 0.00025),
vel: (10000.1, 10000.1),
vel: vec2_scalar_mul(normalize((x, y)), 0.00025),
color: (
between.sample(&mut rng),
between.sample(&mut rng),

@ -5,14 +5,15 @@ pub mod render;
pub mod shaders;
pub mod utility;
use render::{ App };
use utility::window::*;
use render::{ App, ProgramProc };
use winit::event_loop::EventLoop;
fn main() {
let program = ProgramProc::new();
let program = ProgramProc {
event_loop: EventLoop::new()
};
let app = App::new(&program.event_loop);
let app = App::new();
program.main_loop(app);
}
// -------------------------------------------------------------------------------------------

@ -2,7 +2,6 @@ use winit::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEve
use winit::event_loop::{ControlFlow, EventLoop};
use ash::vk;
use ash::util::Align;
use image;
use image::GenericImageView;
@ -14,13 +13,11 @@ use crate::utility::fps_limiter::*;
use crate::utility::{debug, platforms};
use crate::utility::tools::*;
use crate::entities::*;
use crate::VulkanApp;
use crate::shaders::shaders;
use std::ffi::CString;
use std::ptr;
use std::mem;
use mem::size_of;
use std::mem::size_of;
use std::default;
use std::os::raw::{ c_void, c_char };
@ -30,6 +27,76 @@ const WINDOW_TITLE: &'static str = "Template";
const IS_PAINT_FPS_COUNTER: bool = true;
pub struct ProgramProc {
pub event_loop: EventLoop<()>,
}
impl ProgramProc {
pub fn new() -> ProgramProc {
// init window stuff
let event_loop = EventLoop::new();
ProgramProc { event_loop }
}
pub fn main_loop(self, mut vulkan_app: App) {
let mut tick_counter = utility::fps_limiter::FPSLimiter::new();
self.event_loop.run(move |event, _, control_flow| {
match event {
| Event::WindowEvent { event, .. } => {
match event {
| WindowEvent::CloseRequested => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
},
| WindowEvent::KeyboardInput { input, .. } => {
match input {
| KeyboardInput { virtual_keycode, state, .. } => {
match (virtual_keycode, state) {
| (Some(VirtualKeyCode::Escape), ElementState::Pressed) => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
},
| _ => {},
}
},
}
},
| WindowEvent::Resized(_new_size) => {
vulkan_app.wait_device_idle();
vulkan_app.is_framebuffer_resized = true;
},
| _ => {},
}
},
| Event::MainEventsCleared => {
&vulkan_app.window.request_redraw();
},
| Event::RedrawRequested(_window_id) => {
let delta_time = tick_counter.delta_time();
vulkan_app.draw_frame();
if IS_PAINT_FPS_COUNTER {
print!("FPS: {}\r", tick_counter.fps());
}
tick_counter.tick_frame();
},
| Event::LoopDestroyed => {
vulkan_app.wait_device_idle();
},
_ => (),
}
})
}
}
pub fn create_instance(
entry: &ash::Entry,
window_title: &str,
@ -173,8 +240,9 @@ pub fn find_memory_type(
panic!("Failed to find suitable memory type!")
}
pub struct App<'a> {
pub struct App {
pub window: winit::window::Window,
pub event_loop: winit::event_loop::EventLoop<()>,
// vulkan stuff
pub entry: ash::Entry,
@ -245,15 +313,12 @@ pub struct App<'a> {
pub last_time: f64,
pub physical_device_memory_properties: vk::PhysicalDeviceMemoryProperties,
pub query_pool: vk::QueryPool,
pub query_memory: vk::DeviceMemory,
pub query_mapped: &'a mut [u64],
}
impl<'a> App<'a> {
impl App {
pub fn new(event_loop: &winit::event_loop::EventLoop<()>) -> Self {
pub fn new() -> Self {
let event_loop = winit::event_loop::EventLoop::new();
let window = init_window(&event_loop, WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT);
let entry = unsafe { ash::Entry::load().unwrap() };
@ -328,91 +393,14 @@ impl<'a> App<'a> {
let command_buffers = Self::create_command_buffers(&device, command_pool);
let compute_command_buffers = Self::create_compute_command_buffers(&device, command_pool);
let compute_command_buffers = Self::create_command_buffers(&device, command_pool);
let sync_objects = SyncObjects::new(&device, MAX_FRAMES_IN_FLIGHT);
//setup logging of compute shader invocations
// Define the buffer to hold query results
let mut query_results_data: [u64; 1] = [0]; // Assuming we're querying one result
// Create a buffer to hold the query results
let buffer_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
size: 8,
usage: vk::BufferUsageFlags::TRANSFER_DST,
sharing_mode: vk::SharingMode::EXCLUSIVE,
..Default::default()
};
let query_result_buffer = unsafe {
device
.create_buffer(&buffer_info, None)
.expect("Failed to create query result buffer")
};
// Allocate memory for the buffer
let mem_requirements = unsafe { device.get_buffer_memory_requirements(query_result_buffer) };
let memory_type_index = find_memory_type(
mem_requirements.memory_type_bits,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
&physical_device_memory_properties,
);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
allocation_size: mem_requirements.size,
memory_type_index,
..Default::default()
};
let query_memory = unsafe {
device
.allocate_memory(&allocate_info, None)
.expect("Failed to allocate query result memory")
};
unsafe {
// Bind the buffer with allocated memory
device
.bind_buffer_memory(query_result_buffer, query_memory, 0)
.expect("Failed to bind buffer memory")
};
// Now we can use this buffer to store query results
let query_mapped = unsafe {
let raw_ptr = device
.map_memory(
query_memory,
0,
std::mem::size_of_val(&query_results_data) as u64,
vk::MemoryMapFlags::empty(),
)
.expect("Failed to map memory");
std::slice::from_raw_parts_mut(raw_ptr as *mut u64, 1)
};
// Create a query pool
let query_pool_info = vk::QueryPoolCreateInfo {
s_type: vk::StructureType::QUERY_POOL_CREATE_INFO,
query_type: vk::QueryType::PIPELINE_STATISTICS,
query_count: 1, // We're only querying one statistic
pipeline_statistics: vk::QueryPipelineStatisticFlags::COMPUTE_SHADER_INVOCATIONS,
..Default::default()
};
let query_pool = unsafe {
device
.create_query_pool(&query_pool_info, None)
.expect("Failed to create query pool")
};
Self {
window,
event_loop,
entry,
instance,
@ -463,14 +451,79 @@ impl<'a> App<'a> {
last_time: 0.0,
physical_device_memory_properties,
}
}
query_pool,
query_memory,
query_mapped,
/*fn create_vertex_buffer(
instance: &ash::Instance,
device: &ash::Device,
physical_device: vk::PhysicalDevice,
) -> (vk::Buffer, vk::DeviceMemory) {
let vertex_buffer_create_info = vk::BufferCreateInfo {
s_type: vk::StructureType::BUFFER_CREATE_INFO,
p_next: ptr::null(),
flags: vk::BufferCreateFlags::empty(),
size: std::mem::size_of_val(&TRI_VERT_DATA) as u64,
usage: vk::BufferUsageFlags::VERTEX_BUFFER
| vk::BufferUsageFlags::STORAGE_BUFFER
| vk::BufferUsageFlags::TRANSFER_DST,
sharing_mode: vk::SharingMode::EXCLUSIVE,
queue_family_index_count: 0,
p_queue_family_indices: ptr::null(),
};
let vertex_buffer = unsafe {
device
.create_buffer(&vertex_buffer_create_info, None)
.expect("Failed to create Vertex Buffer")
};
let mem_requirements = unsafe { device.get_buffer_memory_requirements(vertex_buffer) };
let mem_properties =
unsafe { instance.get_physical_device_memory_properties(physical_device) };
let required_memory_flags: vk::MemoryPropertyFlags =
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
let memory_type = App::find_memory_type(
mem_requirements.memory_type_bits,
required_memory_flags,
mem_properties,
);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
allocation_size: mem_requirements.size,
memory_type_index: memory_type,
};
let vertex_buffer_memory = unsafe {
device
.allocate_memory(&allocate_info, None)
.expect("Failed to allocate vertex buffer memory!")
};
unsafe {
device
.bind_buffer_memory(vertex_buffer, vertex_buffer_memory, 0)
.expect("Failed to bind Buffer");
let data_ptr = device
.map_memory(
vertex_buffer_memory,
0,
vertex_buffer_create_info.size,
vk::MemoryMapFlags::empty(),
)
.expect("Failed to Map Memory") as *mut Vertex;
data_ptr.copy_from_nonoverlapping(TRI_VERT_DATA.as_ptr(), TRI_VERT_DATA.len());
device.unmap_memory(vertex_buffer_memory);
}
}
(vertex_buffer, vertex_buffer_memory)
}*/
fn find_memory_type(
type_filter: u32,
@ -496,7 +549,6 @@ impl<'a> App<'a> {
for (shader, stage_i) in shaders() {
//check if graphics shader
if stage_i == vk::ShaderStageFlags::VERTEX || stage_i == vk::ShaderStageFlags::FRAGMENT {
println!("shader stage: {:?}", stage_i);
shader_modules.push(
vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
@ -760,35 +812,25 @@ impl<'a> App<'a> {
fn record_compute_command_buffer(
&mut self,
&self,
device: &ash::Device,
command_buffer: vk::CommandBuffer
) {
let begin_info = vk::CommandBufferBeginInfo::default();
unsafe {
self.device
device
.begin_command_buffer(command_buffer, &begin_info)
.expect("failed to begin recording compute command buffer");
println!("resetting query pool for command buffer: {}", self.current_frame);
self.device
.cmd_reset_query_pool(
self.compute_command_buffers[self.current_frame],
self.query_pool,
0,
1,
);
self.device.cmd_begin_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0, vk::QueryControlFlags::empty());
self.device
device
.cmd_bind_pipeline(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
self.compute_pipeline,
);
self.device
device
.cmd_bind_descriptor_sets(
command_buffer,
vk::PipelineBindPoint::COMPUTE,
@ -798,36 +840,169 @@ impl<'a> App<'a> {
&[],
);
self.device
device
.cmd_dispatch(
command_buffer,
(PARTICLE_COUNT / 256) as u32,
1,
1,
);
device
.end_command_buffer(command_buffer)
.expect("failed ending compute command buffer");
}
}
fn draw_frame(&mut self) {
//compute submission
let mut submit_infos;
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.compute_inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
//log compute shader invocations
self.update_uniform_buffer(self.current_frame);
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0);
unsafe {
self.device
.reset_fences(&[self.sync_objects.compute_inflight_fences[self.current_frame]]);
/*let query_results = unsafe {
self.device.get_query_pool_results::<u64>(
self.query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
self.query_mapped, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)
.expect("Failed to retrieve query pool results"
)};
self.device
.reset_command_buffer(self.compute_command_buffers[self.current_frame], vk::CommandBufferResetFlags::empty());
}
self.record_compute_command_buffer(&self.device, self.compute_command_buffers[self.current_frame]);
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.compute_command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.compute_finished_semaphores[self.current_frame],
..Default::default()
}];
println!("Compute shader invocations: {:?}", self.query_mapped[0]);*/
unsafe {
self.device
.end_command_buffer(command_buffer)
.expect("failed ending compute command buffer");
.queue_submit(
self.compute_queue,
&submit_infos,
self.sync_objects.compute_inflight_fences[self.current_frame]
);
}
//graphics submission
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
let (image_index, _is_sub_optimal) = unsafe {
let result = self.swapchain_stuff.swapchain_loader.acquire_next_image(
self.swapchain_stuff.swapchain,
std::u64::MAX,
self.sync_objects.image_available_semaphores[self.current_frame],
vk::Fence::null(),
);
match result {
Ok(image_index) => image_index,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR => {
SwapChainStuff::recreate_swapchain(self);
return;
}
_ => panic!("Failed to acquire Swap Chain Image!"),
},
}
};
unsafe {
self.device
.reset_fences(&[self.sync_objects.inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(
self.command_buffers[self.current_frame],
vk::CommandBufferResetFlags::empty(),
);
}
self.record_command_buffer(self.command_buffers[self.current_frame], image_index as usize);
let wait_semaphores = [
self.sync_objects.compute_finished_semaphores[self.current_frame],
self.sync_objects.image_available_semaphores[self.current_frame],
];
let wait_stages = [
vk::PipelineStageFlags::VERTEX_INPUT,
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
];
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
wait_semaphore_count: 2,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.graphics_queue,
&submit_infos,
self.sync_objects.inflight_fences[self.current_frame],
)
.expect("failed to submit draw command buffer");
}
let swapchains = [self.swapchain_stuff.swapchain];
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PRESENT_INFO_KHR,
p_next: ptr::null(),
wait_semaphore_count: 1,
p_wait_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
swapchain_count: 1,
p_swapchains: swapchains.as_ptr(),
p_image_indices: &image_index,
p_results: ptr::null_mut(),
};
let result = unsafe {
self.swapchain_stuff.swapchain_loader
.queue_present(self.present_queue, &present_info)
};
let is_resized = match result {
Ok(_) => self.is_framebuffer_resized,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR | vk::Result::SUBOPTIMAL_KHR => true,
_ => panic!("Failed to execute queue present."),
},
};
if is_resized {
self.is_framebuffer_resized = false;
SwapChainStuff::recreate_swapchain(self);
}
self.current_frame = (self.current_frame + 1) % MAX_FRAMES_IN_FLIGHT;
}
pub fn create_shader_storage_buffers(
@ -838,13 +1013,7 @@ impl<'a> App<'a> {
) -> (Vec<vk::Buffer>, Vec<vk::DeviceMemory>) {
let mut particles = Particle::gen();
let mut particles_slice_data = particles.as_mut_slice();
//let mut slice = Align::new();
let mut buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * particles_slice_data.len() as u64;
println!("particles count: {}, particle size: {}, buffer size: {}", PARTICLE_COUNT as u64, std::mem::size_of::<Particle>() as u64, buffer_size as usize);
let buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * PARTICLE_COUNT as u64;
let (staging_buffer, staging_buffer_memory) = Self::create_buffer(
@ -860,9 +1029,7 @@ impl<'a> App<'a> {
let mut shader_storage_buffers_memory = vec![];
unsafe {
println!("isize max is {}", isize::MAX);
println!("mapping device memory");
let mut data = device
let data = device
.map_memory(
staging_buffer_memory,
0,
@ -870,21 +1037,11 @@ impl<'a> App<'a> {
vk::MemoryMapFlags::empty(),
)
.expect("failed to map shader storage buffer memory");
let mem_requirements = unsafe { device.get_buffer_memory_requirements(staging_buffer) };
println!("mem req: {}", mem_requirements.size);
let mut slice = Align::new(
ptr::copy_nonoverlapping(
data,
mem::align_of::<Particle>() as u64,
mem_requirements.size,
particles.as_mut_ptr() as *mut c_void,
buffer_size as usize,
);
slice.copy_from_slice(&particles_slice_data);
println!("DATA INSIDE PARTICLES BUFFER: {}", ParticlesList::from_raw_ptr(data as *const Particle, particles.len()));
//println!("copying to device memory");
device
.unmap_memory(staging_buffer_memory);
@ -895,8 +1052,7 @@ impl<'a> App<'a> {
vk::BufferUsageFlags::STORAGE_BUFFER |
vk::BufferUsageFlags::VERTEX_BUFFER |
vk::BufferUsageFlags::TRANSFER_DST,
vk::MemoryPropertyFlags::DEVICE_LOCAL |
vk::MemoryPropertyFlags::HOST_VISIBLE,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
physical_device_memory_properties,
);
@ -978,9 +1134,6 @@ impl<'a> App<'a> {
device.end_command_buffer(alloced_command_buffer);
}
println!("src_buffer: {:?}", src_buffer);
println!("dst_buffer: {:?}", dst_buffer);
let submit_info = vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
command_buffer_count: 1,
@ -1024,7 +1177,6 @@ impl<'a> App<'a> {
p_queue_family_indices: ptr::null(),
};
println!("actual buffer size: {}", size);
let buffer = unsafe {
device
.create_buffer(&buffer_create_info, None)
@ -1033,8 +1185,6 @@ impl<'a> App<'a> {
let mem_requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
println!("memory allocation size: {}", mem_requirements.size);
let allocate_info = vk::MemoryAllocateInfo {
s_type: vk::StructureType::MEMORY_ALLOCATE_INFO,
p_next: ptr::null(),
@ -1128,7 +1278,6 @@ impl<'a> App<'a> {
let physical_device_features = vk::PhysicalDeviceFeatures {
sampler_anisotropy: vk::TRUE, // enable anisotropy device feature from Chapter-24.
pipeline_statistics_query: vk::TRUE,
..Default::default()
};
@ -1200,7 +1349,7 @@ impl<'a> App<'a> {
}
let clear_color = [vk::ClearValue {
color: vk::ClearColorValue {
float32: [0.0, 0.0, 1.0, 1.0],
float32: [1.0, 1.0, 1.0, 1.0],
},
}];
@ -1275,7 +1424,6 @@ impl<'a> App<'a> {
&[self.shader_storage_buffers[self.current_frame]],
offsets,
);
println!("binding to shader storage buffer index: {}", self.current_frame);
self.device
.cmd_draw(
command_buffer,
@ -1703,8 +1851,6 @@ impl<'a> App<'a> {
range: size_of::<UniformBufferObject>() as u64,
};
println!("STORAGE BUFFERS INDEXES: {}, {}", (i as i32 - 1) as usize % MAX_FRAMES_IN_FLIGHT, i);
let storage_buffer_info_last_frame = vk::DescriptorBufferInfo {
buffer: shader_storage_buffers[(i as i32 - 1) as usize % MAX_FRAMES_IN_FLIGHT],
offset: 0,
@ -1832,27 +1978,6 @@ impl<'a> App<'a> {
command_buffers
}
pub fn create_compute_command_buffers(
device: &ash::Device,
command_pool: vk::CommandPool,
) -> Vec<vk::CommandBuffer> {
let command_buffer_allocate_info = vk::CommandBufferAllocateInfo {
s_type: vk::StructureType::COMMAND_BUFFER_ALLOCATE_INFO,
p_next: ptr::null(),
command_buffer_count: MAX_FRAMES_IN_FLIGHT as u32,
command_pool,
level: vk::CommandBufferLevel::PRIMARY,
};
let command_buffers = unsafe {
device
.allocate_command_buffers(&command_buffer_allocate_info)
.expect("Failed to allocate Command Buffers!")
};
command_buffers
}
fn wait_device_idle(&self) {
unsafe {
self.device
@ -1861,238 +1986,3 @@ impl<'a> App<'a> {
};
}
}
impl VulkanApp for App<'_> {
fn wait_device_idle(&self) {
unsafe {
self.device
.device_wait_idle()
.expect("Failed to wait device idle!")
};
}
fn resize_framebuffer(&mut self) {
self.is_framebuffer_resized = true;
}
fn window_ref(&self) -> &winit::window::Window {
&self.window
}
fn cleanup_swapchain(&self) {
self.swapchain_stuff.cleanup_swapchain(&self.device)
}
fn recreate_swapchain(&mut self) {
SwapChainStuff::recreate_swapchain(self);
}
fn draw_frame(&mut self) {
let mut buffer_size: u64 = std::mem::size_of::<Particle>() as u64 * PARTICLE_COUNT as u64;
//compute submission
let mut submit_infos;
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.compute_inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
self.update_uniform_buffer(self.current_frame);
unsafe {
self.device
.reset_fences(&[self.sync_objects.compute_inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(self.compute_command_buffers[self.current_frame], vk::CommandBufferResetFlags::empty());
}
//RESET query pool for compute shader statistics
/*unsafe {
self.device
.cmd_reset_query_pool(
self.compute_command_buffers[self.current_frame],
self.query_pool,
0,
1,
);
}*/
self.record_compute_command_buffer(self.compute_command_buffers[self.current_frame]);
self.update_uniform_buffer(self.current_frame);
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.compute_command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.compute_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.compute_queue,
&submit_infos,
self.sync_objects.compute_inflight_fences[self.current_frame]
);
}
/*log compute shader invocations
unsafe {
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], query_pool, 0);
}
let query_results = unsafe {
self.device.get_query_pool_results::<u32>(
query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
data, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)
.expect("Failed to retrieve query pool results"
)};
println!("Compute shader invocations: {:?}", data[0]);*/
//graphics submission
unsafe {
self.device
.wait_for_fences(
&[self.sync_objects.inflight_fences[self.current_frame]],
true,
u64::MAX,
);
}
let (image_index, _is_sub_optimal) = unsafe {
let result = self.swapchain_stuff.swapchain_loader.acquire_next_image(
self.swapchain_stuff.swapchain,
std::u64::MAX,
self.sync_objects.image_available_semaphores[self.current_frame],
vk::Fence::null(),
);
match result {
Ok(image_index) => image_index,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR => {
SwapChainStuff::recreate_swapchain(self);
return;
}
_ => panic!("Failed to acquire Swap Chain Image!"),
},
}
};
unsafe {
self.device
.reset_fences(&[self.sync_objects.inflight_fences[self.current_frame]]);
self.device
.reset_command_buffer(
self.command_buffers[self.current_frame],
vk::CommandBufferResetFlags::empty(),
);
}
self.record_command_buffer(self.command_buffers[self.current_frame], image_index as usize);
let wait_semaphores = [
self.sync_objects.compute_finished_semaphores[self.current_frame],
self.sync_objects.image_available_semaphores[self.current_frame],
];
let wait_stages = [
vk::PipelineStageFlags::VERTEX_INPUT,
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
];
submit_infos = [vk::SubmitInfo {
s_type: vk::StructureType::SUBMIT_INFO,
wait_semaphore_count: 2,
p_wait_semaphores: wait_semaphores.as_ptr(),
p_wait_dst_stage_mask: wait_stages.as_ptr(),
p_next: ptr::null(),
command_buffer_count: 1,
p_command_buffers: &self.command_buffers[self.current_frame],
signal_semaphore_count: 1,
p_signal_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
..Default::default()
}];
unsafe {
self.device
.queue_submit(
self.graphics_queue,
&submit_infos,
self.sync_objects.inflight_fences[self.current_frame],
)
.expect("failed to submit draw command buffer");
}
let swapchains = [self.swapchain_stuff.swapchain];
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PRESENT_INFO_KHR,
p_next: ptr::null(),
wait_semaphore_count: 1,
p_wait_semaphores: &self.sync_objects.render_finished_semaphores[self.current_frame],
swapchain_count: 1,
p_swapchains: swapchains.as_ptr(),
p_image_indices: &image_index,
p_results: ptr::null_mut(),
};
let result = unsafe {
self.swapchain_stuff.swapchain_loader
.queue_present(self.present_queue, &present_info)
};
let is_resized = match result {
Ok(_) => self.is_framebuffer_resized,
Err(vk_result) => match vk_result {
vk::Result::ERROR_OUT_OF_DATE_KHR | vk::Result::SUBOPTIMAL_KHR => true,
_ => panic!("Failed to execute queue present."),
},
};
if is_resized {
self.is_framebuffer_resized = false;
SwapChainStuff::recreate_swapchain(self);
}
//println!("resized {}", self.is_framebuffer_resized);
//log compute shader invocations
/*unsafe {
self.device.cmd_end_query(self.compute_command_buffers[self.current_frame], self.query_pool, 0);
}*/
let query_results = unsafe {
self.device.get_query_pool_results::<u64>(
self.query_pool,
0, // Starting query index
1, // Number of queries to retrieve (1 in this case)
self.query_mapped, // Results will be stored here
//0, // Query results stride (optional)
vk::QueryResultFlags::TYPE_64, // Flags specifying the type of query results
)};
println!("Compute shader invocations: {:?}", self.query_mapped[0]);
self.current_frame = (self.current_frame + 1) % MAX_FRAMES_IN_FLIGHT;
}
}

@ -3,7 +3,7 @@
struct Particle {
vec2 position;
vec2 velocity;
vec4 color;
vec4 color;
};
layout (binding = 0) uniform ParameterUBO {
@ -27,17 +27,10 @@ void main()
Particle particleIn = particlesIn[index];
//particlesOut[index].position = particleIn.position + particleIn.velocity.xy * ubo.deltaTime;
particlesOut[index].position = particleIn.position + vec2(1.0, 1.0) * ubo.deltaTime;
particlesOut[index].position = vec2(100.0, 100.0);
particlesOut[0].position = vec2(100.0, 100.0);
//particlesOut[index].position = vec2(100, 100);
particlesOut[index].velocity = particleIn.velocity;
particlesOut[index].color = vec4(150.0, 150.0, 150.0, 150.0);
particlesOut[0].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[1].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[2].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[3].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[4].color = vec4(1.0, 1.0, 1.0, 1.0);
particlesOut[index].position = vec2(5, 5)
// Flip movement at window border
if ((particlesOut[index].position.x <= -1.0) || (particlesOut[index].position.x >= 1.0)) {

@ -7,6 +7,5 @@ layout(location = 0) out vec4 outColor;
void main() {
vec2 coord = gl_PointCoord - vec2(0.5);
//outColor = vec4(fragColor, 0.5 - length(coord));
outColor = vec4(fragColor, 1.0);
outColor = vec4(fragColor, 0.5 - length(coord));
}

@ -8,7 +8,6 @@ layout(location = 0) out vec3 fragColor;
void main() {
gl_PointSize = 14.0;
gl_Position = vec4(inPosition, 1.0, 1.0);
gl_Position = vec4(inPosition.xy, 1.0, 1.0);
fragColor = inColor.rgb;
//fragColor = vec3(1.0, 1.0, 1.0);
}

@ -2,6 +2,6 @@ pub mod constants;
pub mod debug;
pub mod fps_limiter;
pub mod platforms;
pub mod window;
//pub mod share;
pub mod structures;
pub mod tools;

@ -18,7 +18,7 @@ pub const DEVICE_EXTENSIONS: DeviceExtension = DeviceExtension {
names: ["VK_KHR_swapchain"],
};
pub const MAX_FRAMES_IN_FLIGHT: usize = 2;
pub const IS_PAINT_FPS_COUNTER: bool = false;
pub const IS_PAINT_FPS_COUNTER: bool = true;
impl DeviceExtension {
pub fn get_extensions_raw_names(&self) -> [*const c_char; 1] {

@ -8,7 +8,6 @@ use memoffset::offset_of;
use super::platforms;
use crate::render::App;
use crate::render::*;
use crate::utility::window::VulkanApp;
pub struct DeviceExtension {
pub names: [&'static str; 1],
@ -152,11 +151,6 @@ impl SwapChainStuff {
.destroy_image_view(*imageview, None)
}
}
unsafe {
self.swapchain_loader
.destroy_swapchain(self.swapchain, None)
}
}
pub fn recreate_swapchain(app: &mut App) {
@ -165,7 +159,7 @@ impl SwapChainStuff {
.device_wait_idle();
}
app.cleanup_swapchain();
app.swapchain_stuff.cleanup_swapchain(&app.device);
app.swapchain_stuff = SwapChainStuff::new(
&app.instance,
@ -176,8 +170,8 @@ impl SwapChainStuff {
&app.queue_family,
);
app.swapchain_stuff.swapchain_imageviews = App::create_image_views(&app.device, &app.swapchain_stuff.swapchain_format, &app.swapchain_stuff.swapchain_images);
app.swapchain_stuff.swapchain_framebuffers = App::create_framebuffers(&app.device, app.render_pass, &app.swapchain_stuff.swapchain_imageviews, &app.swapchain_stuff.swapchain_extent);
App::create_image_views(&app.device, &app.swapchain_stuff.swapchain_format, &app.swapchain_stuff.swapchain_images);
App::create_framebuffers(&app.device, app.render_pass, &app.swapchain_stuff.swapchain_imageviews, &app.swapchain_stuff.swapchain_extent);
}
pub fn choose_swapchain_extent(

@ -1,91 +0,0 @@
use winit::event::{Event, VirtualKeyCode, ElementState, KeyboardInput, WindowEvent};
use winit::event_loop::{EventLoop, ControlFlow};
const IS_PAINT_FPS_COUNTER: bool = true;
pub fn init_window(
event_loop: &EventLoop<()>,
title: &str,
width: u32,
height: u32,
) -> winit::window::Window {
winit::window::WindowBuilder::new()
.with_title(title)
.with_inner_size(winit::dpi::LogicalSize::new(width, height))
.build(event_loop)
.expect("Failed to create window.")
}
pub trait VulkanApp {
fn draw_frame(&mut self);
fn recreate_swapchain(&mut self);
fn cleanup_swapchain(&self);
fn wait_device_idle(&self);
fn resize_framebuffer(&mut self);
fn window_ref(&self) -> &winit::window::Window;
}
pub struct ProgramProc {
pub event_loop: EventLoop<()>,
}
impl ProgramProc {
pub fn new() -> ProgramProc {
ProgramProc { event_loop: EventLoop::new() }
}
pub fn main_loop<A: 'static + VulkanApp>(self, mut vulkan_app: A) {
let mut tick_counter = super::fps_limiter::FPSLimiter::new();
self.event_loop
.run(move |event, _, control_flow| {/*println!("evl");*/match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
}
WindowEvent::KeyboardInput { input, .. } => match input {
KeyboardInput {
virtual_keycode,
state,
..
} => match (virtual_keycode, state) {
(Some(VirtualKeyCode::Escape), ElementState::Pressed) => {
vulkan_app.wait_device_idle();
*control_flow = ControlFlow::Exit
}
_ => {}
},
},
WindowEvent::Resized(_new_size) => {
println!("resizing framebuffer event");
vulkan_app.wait_device_idle();
vulkan_app.resize_framebuffer();
}
_ => {}
},
Event::MainEventsCleared => {
vulkan_app.window_ref().request_redraw();
}
Event::RedrawRequested(_window_id) => {
//println!("redraw req");
let delta_time = tick_counter.delta_time();
vulkan_app.draw_frame();
//println!("frame drawn!");
if IS_PAINT_FPS_COUNTER {
print!("FPS: {}\r", tick_counter.fps());
}
tick_counter.tick_frame();
}
Event::LoopDestroyed => {
vulkan_app.wait_device_idle();
}
_ => (),
}})
}
}
Loading…
Cancel
Save